【问题标题】:How to compare last digit of number w/ last digit of another number?如何比较数字的最后一位数字与另一个数字的最后一位数字?
【发布时间】: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));
}

【问题讨论】:

标签: java methods bluej user-defined


【解决方案1】:

我的猜测是您的原始实现不起作用,因为您在应该使用String#equals(Object) 时使用== 运算符来比较字符串。 == 是身份平等。如果您有两个不同的 String 实例——即使它们具有相同的内容——== 将始终返回 false。

改用Integer#toString() 怎么样?

public static boolean retsim(Integer x, Integer y) {
    if (null == x || null == y) {
         throw new IllegalArgumentException("x and y must not be null!");
    }

    String xString = x.toString();
    String yString = y.toString();

    return xString.charAt(xString.length-1) == xString.charAt(yString.length-1);
}

return 语句正在处理两个 char 原语,在这种情况下使用 == 是正确的。

【讨论】:

  • 抱歉,您能解释一下: throw 的作用吗?我试图遵循你所做的。 @nasukkin
  • @S.Nary 啊,这只是参数验证。如果 x 或 y 以 null 的值进入方法,则会抛出 IllegalArgumentException 并显示一条有用的消息,说明该方法无法对这些参数进行操作。
【解决方案2】:

zapl 的第一条评论已经给出了很好的提示。

public static boolean retsim(int x, int y)
{
    return Math.abs(x)%10 == Math.abs(y)%10;
}

【讨论】:

  • 这会返回 true 吗? @Dino Tw
  • 如果其中一个数字是负数(例如 -79 和 29),它将返回 false。你应该使用Math.abs() 作为两个参数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 2013-06-13
  • 1970-01-01
  • 2022-01-08
  • 2013-08-01
  • 1970-01-01
相关资源
最近更新 更多