public static boolean retsim(int x, int y)
{
String xx = x + "";
String yy = y + "";
boolean returnValue = false;
if(xx.substring(xx.length() - 1) == yy.substring(yy.length() - 1))
{
returnValue = true;
}
return returnValue;
}
所以当我编译并运行它时没有错误。然而,当只有一个正确或错误的陈述时,它却打印出 2 个错误的陈述。 例如:
Enter in two sets of numbers with either,
The same or different end digit
7
7
// ^^ The two sevens are the inputs
false
false
// ^^ The two false statements that should only be printing out one
当最后一个数字与另一个最后一个数字相同时,它应该返回 true, 当这两个数字不相同时,程序应该返回 false。 请帮忙?!
public static boolean retsim(int x, int y)
{
String xx = x + "";
String yy = y + "";
boolean returnValue = false;
if(xx.substring(xx.length() - 1).equals(yy.substring(yy.length() - 1)))
{
returnValue = true;
}
return returnValue;
}
现在它返回:
Enter in two sets of numbers with either,
The same or different end digit
7
7
// ^^ The two sevens are the inputs
true
false
// ^^ The two false statements that should only be printing out one
有人对如何摆脱最后一个错误有任何想法吗?
我用来调用该类的代码是:
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter in two sets of numbers with either,\nThe same or different end digit");
int x2 = console.nextInt();
int y = console.nextInt();
System.out.println(retsim(x2,y));
}
最佳答案
zapl 的第一条评论已经给出了很好的提示。
public static boolean retsim(int x, int y)
{
return Math.abs(x)%10 == Math.abs(y)%10;
}
关于java - 如何将一个数字的最后一位数字与另一个数字的最后一位数字进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40251517/