在Java中返回给定号码的倒数第二个数字
时间:2020-02-23 14:35:33 来源:igfitidea点击:
在本主题中,我们将学习在示例的帮助下获取Java中的倒数第二个数字。
使用Modulo Operator.
其中我们正在使用Modulo和Divide Operator来找到第二个最后一位数。
Modulo运算符在剩余的数量上提供,而鸿沟运算符会提供商品。
public class Main{
public static void main(String[] args){
int a = 120025;
int secondLastDigit = (a % 100)/10;
System.out.println(secondLastDigit);
secondLastDigit = (a/10) % 10;
System.out.println(secondLastDigit);
}
}
输出
2
使用String的Chartat()方法
还有另一个例子,我们可以将数字转换为字符串然后使用 charAt()在该结果转换回数之后,我们获得第二个最后一个值 Character类。
public class Main{
public static void main(String[] args){
int a = 120025;
String number = Integer.toString(a);
System.out.println(number);
int secondLastDigit = Character.getNumericValue((number.charAt(number.length()-2)));
System.out.println(secondLastDigit);
}
}

