【问题标题】:What's the problem with this code in Java?Java中的这段代码有什么问题?
【发布时间】:2023-03-09 15:05:02
【问题描述】:

我想在 Eclipse 中用 Java 编写一个程序,告诉我是否可以制作三角形。这是我的代码:

import java.io.IOException;

public class haromszog {
    public static void main(String[] args) throws IOException {

        int a;
        int b;
        int c;

    System.out.print("Please insert the 'a' side of the triangle:");
    a = System.in.read();

    System.out.print("Please insert the 'b' side of the triangle:");
    b = System.in.read();

    System.out.print("Please insert the 'c' side of the triangle:");
    c = System.in.read();

    if ((a+b)>c)
    {
        if ((a+c)>b)
        {
            if ((b+c)>a)
            {System.out.print("You can make this triangle");
            }
            else 
                System.out.print("You can't make this triangle");

        }
    }
    }
}

Eclipse,可以运行它,但它写道:

请插入三角形的'a'边:(例如我写:)5

请插入三角形的'b'边:

请插入三角形的“c”边:

你不能做这个三角形

而且我不能在 b 和 c 端写任何东西。这有什么问题?

【问题讨论】:

标签: java eclipse


【解决方案1】:

System.in.read() 从应用程序的标准输入中读取单个 byte。这几乎可以肯定不是您想要的(除非某些东西正在将二进制数据传递给您的应用程序)。

您可以尝试改用System.console().readLine()(后面跟Integer.parseInt() 将生成的String 转换为int)。

【讨论】:

  • 这很好,虽然我没有编写 if 表达式,但当我编写它们时编译器告诉错误。但是谢谢:)
【解决方案2】:

来自http://download.oracle.com/javase/1.4.2/docs/api/java/io/InputStream.html:

read() : 从输入流中读取下一个字节的数据。

您读取的不是整数,而是字符代码。

你应该这样做:

java.util.Scanner s = new java.util.Scanner(System.in); 
int k = s.nextInt();

【讨论】:

  • 可能不是扫描仪。他看起来正在处理命令行输入。在这种情况下,我可能会在由 new BufferedReader( new InputStreamReader( System.in ) ) 创建的阅读器上使用 readLine() 后跟 Integer.parseInt()。
  • @Konstantin Komissarchik Scanner 有什么问题?少写代码:)
  • 如果 Scanner 正确处理输入之间的新行,那么它也可以使用。
  • @Konstantin:这是“控制台输入”而不是“命令行输入”。后者将暗示参数(即String[] args)。
【解决方案3】:

除了 System.in.read() 的问题,你需要结合你的 if 语句,因为 else 子句目前只适用于内部的。

if ((a+b)>c && (a+c)>b && (b+c)>a) { 
   System.out.print("You can make this triangle");
}
else {
   System.out.print("You can't make this triangle");
}

【讨论】:

    【解决方案4】:

    您读取一个字节,因此如果它是 ascii 字符“5”,则它不是数字 5,而是 53。您的下一个问题是回车,它被读取为下一个字节。

    改用 java.util.Scanner 类:

    Scanner sc = new Scanner (System.in);
    int a = sc.nextInt ();
    

    【讨论】:

      【解决方案5】:

      添加到 Joachim 的答案,试试这个:

      import java.io.IOException;
      import java.util.Scanner;
      
      public class foo {
          public static void main(String[] args) throws IOException {
      
          Scanner s = new Scanner(System.in);
      
          System.out.print("Please insert the 'a' side of the triangle:");
          int a = s.nextInt();
      
          System.out.print("Please insert the 'b' side of the triangle:");
          int b = s.nextInt();
      
          System.out.print("Please insert the 'c' side of the triangle:");
          int c = s.nextInt();
      
          }
      }
      

      【讨论】:

      • 这对我来说是最好的答案,因为它对初学者来说也很容易:) 谢谢。
      猜你喜欢
      • 2018-07-05
      • 1970-01-01
      • 2015-04-25
      • 2018-09-09
      相关资源
      最近更新 更多