【问题标题】:Confusion over doing + with strings and ints对使用字符串和整数做 + 感到困惑
【发布时间】:2011-04-08 18:39:06
【问题描述】:

我正在制作一个程序,我想要求用户输入每个评委的分数,但是当它开始并要求第一位评委时,正确地说“输入分数判断01"

但是当它进入下一个时,它会跳过 02 并直接进入 11,然后是 21。我做错了什么?这是该区域的代码行

int[] judge = new int[7];


    for(int i = 0; i<judge.length; i++)
    {
    System.out.println("Enter the difficulty score for each judge (0-10)");

        System.out.println("Enter the score for judge" + i+1);
        judge[i]=keyboard.nextInt();
while(score > 0 && score <=10);
    }

}

【问题讨论】:

    标签: java arrays increment


    【解决方案1】:

    + 运算符从左到右工作。运算符左侧是一个字符串,右侧是“i”。因此发生了字符串的连接。 "i" 被转换为字符串。然后另一个 + 1 出现,这再次被视为字符串的连接。

    要将 i+1 视为加法,请将其放在括号内。

    System.out.println("Enter the score for judge" + (i+1));
    

    【讨论】:

      【解决方案2】:

      运算符优先级是关键。 (i+1) 应该在括号中。

      没有它,所有+ 操作都会从左到右进行评估。

      在 Java 中,字符串 + 任何东西都是字符串。 "foo"+bar 只是 "foo" + String.valueOf( bar ); 的简写。

      您可以在此here 上阅读更多信息。我承认这有点乏味,但值得一读。它会为您省去很多麻烦。

      【讨论】:

      • 谢谢。是括号
      【解决方案3】:

      试试这个:

      System.out.println("输入评委分数" + (i+i));

      因为如果您在 + 运算符之后使用任何原语而不带括号的字符串,那么它会继续附加它们。例如

      字符串 = "大师" + 123 + 5;

      是 Guru1235

      在哪里

      字符串 = "大师" + (123 + 5);

      即大师128

      【讨论】:

        【解决方案4】:

        发生的事情是在行中

        System.out.println("Enter the score for judge" + i+1);
        

        它正在对字符串和 i 进行字符串连接,然后再次与 1 连接。

        要修复它,请在 i+1 周围加上括号,如下所示:

        System.out.println("Enter the score for judge" + (i+1));
        

        【讨论】:

          【解决方案5】:

          试试这个代码:

          int[] judge = new int[7];
          
          for(int i = 0; i < judge.length; i++)
          {
             System.out.println("Enter the difficulty score for each judge (0-10)");
             System.out.println("Enter the score for judge 0" + (i + 1));
          
             judge[i] = keyboard.nextInt();
             while (score > 0 && score <= 10);
          }
          

          【讨论】:

            猜你喜欢
            • 2020-08-16
            • 1970-01-01
            • 2015-03-13
            • 1970-01-01
            • 1970-01-01
            • 2017-10-19
            • 1970-01-01
            • 2021-11-28
            • 1970-01-01
            相关资源
            最近更新 更多