【发布时间】:2017-03-08 04:25:45
【问题描述】:
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));
}
【问题讨论】:
-
很糟糕,但它几乎是一个解决方案:stackoverflow.com/questions/513832/… - 您可以使用stackoverflow.com/questions/90238/… 使其成为一个简单的单线
-
感谢您的建议,但是您知道为什么它会打印出两个错误的陈述吗? @zapl
-
第一个链接,== 不符合你的想法
-
所以我应该用 .equals() 替换 ==? @zapl
标签: java methods bluej user-defined