java - 如何将一个数字的最后一位数字与另一个数字的最后一位数字进行比较?

标签 java methods bluej user-defined

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/

相关文章:

java - JTextArea - setText() 和 append() 在 Listener method() 中不起作用

java - Cucumber 运行场景取决于不同功能文件中的另一个

java - 如何在 AspectJ 中将方法与带注释的参数匹配

c++ - 调用不通过空指针访问成员的非静态方法是否合法/定义明确的 C++?

java - Blue J,我的 listMembers 方法没有从我的数组列表中打印出正确的数据

java - 如何在 Java 中向文本字段添加 Action 监听器

Java Couchbase SDK - 没有 View 的查询

java - 阐明:在我的 wadl 中,为什么我的所有资源路径属性都以 "/rest"为前缀?

unit-testing - PHPunit 调用魔术方法

java - BlueJ 中 JVM 的重置与 JVM 的终止相同吗?