Java添加错误的答案

时间:2014-09-16 13:24:54

标签: java

我试图添加四个整数,即4 + 3 + 2 + 1,但我得到值202

class Task3{
public static void main (String args[]){
    String x=(args[0]);
    int I = Integer.parseInt (x);   
    char c1 = x.charAt(0);
    char c2 = x.charAt(1);
    char c3 = x.charAt(2);
    char c4 = x.charAt(3);
    System.out.println("First and last digit is: " + c1 +"," + c4);
    if (c1 > c4)
        System.out.println("The first digit is larger");
    else
        System.out.println("The second digit is larger");
    int sum = c1 + c2 + c3 + c4;
    System.out.println(sum);
}

}

6 个答案:

答案 0 :(得分:2)

这是因为您要添加UNICODE代码点的数值,而不是相应字符所代表的数字。

为了从字符代码中获取数字,请调用Character.digit(c1, 10)(10表示您需要十进制数字)。

int c1 = Character.digit(x.charAt(0), 10);
int c2 = Character.digit(x.charAt(1), 10);
int c3 = Character.digit(x.charAt(2), 10);
int c4 = Character.digit(x.charAt(3), 10);

答案 1 :(得分:2)

char c1 = x.charAt(0);替换为Character.getNumericValue(x.charAt(0))

答案 2 :(得分:2)

更改

int sum = c1 + c2 + c3 + c4;

int sum = c1 + c2 + c3 + c4 - 4 * '0';

由于c1,c2,c3,c4都是字符,所以数字说。 4取'4'基本上是ASCII值,所以得到4而不是'4'你需要从c1,c2,c3,c4中减去'0',所以减去4 *'0'

答案 3 :(得分:2)

您正在尝试总结char的ASCII代码而不是数字值。您必须为每个字符检索相应的数字,然后评估您的添加结果:

class Task3
{
  public static void main (String args[])
  {
    String x=(args[0]);
    int I = Integer.parseInt (x);   
    char c1 = x.charAt(0);
    char c2 = x.charAt(1);
    char c3 = x.charAt(2);
    char c4 = x.charAt(3);
    int i1 = Character.digit(c1, 10);
    int i2 = Character.digit(c2, 10);
    int i3 = Character.digit(c3, 10);
    int i4 = Character.digit(c4, 10);
    System.out.println("First and last digit is: " + i1 +"," + i4);
    if (i1 > i4)
      System.out.println("The first digit is larger");
    else
      System.out.println("The second digit is larger");
    int sum = i1 + i2 + i3 + i4;
    System.out.println(sum);
  }

}

答案 4 :(得分:1)

错误输出的原因其他人已经解释了它现在获得正确输出的方法之一

int sum =0;
while(I>0){
    int rem = I%10;
    sum+=rem;
    I = I/10;
}
System.out.println(sum);

答案 5 :(得分:0)

我认为你正在通过“4321”或类似的程序。

c1不是数字1,但实际上是表示字符“1”的Unicode数字,实际上是31(十六进制)。最新增加的是添加这些Unicode数字。

有关字符的unicode编号列表,请参阅http://unicode-table.com/en/,有关Java中字符的更多详细信息,请参阅http://docs.oracle.com/javase/tutorial/i18n/text/unicode.html

相关问题