java - 如何读取仅由空格分隔的一行?

标签 java integer whitespace java.util.scanner boolean-expression

    int a; 
    int b;                           
    int c;

    Scanner input = new Scanner (System.in);

    //how to read three integers with white space delimiter 
    System.out.print("Enter the 3 edges of the triangle to be calculated: "); 
    int numbers = input.nextInt();

    //then turn 3 integers into boolean form
    //this is only the algorithm
    Boolean isTriangle = ((a+b>c)  && (b+c > a)  && (c+a > b));

           System.out.print(isTriangle);

    else

            System.out.print(isTriangle);

因此,我不想在单独的行或换行符中输入 3 个整数,而是希望它们全部位于同一行中,只是用空格分隔。我是否需要将标准输入更改为字符串,然后解析 boolean 部分?我很困惑,因为输入整数后我不知道在哪里存储它们以用于 boolean 部分。

编辑部分:

    public static void main(String[] args){
    int x;
    int y;
    int z;

    Scanner input = new Scanner(System.in);
    System.out.println("Enter three edges: ");

    x = input.nextInt();
    y = input.nextInt();
    z = input.nextInt();

    boolean isTriangle = ((x+y>z)  && (y+z > x)  && (z+x > y));

    if (isTriangle){
        System.out.print("Can edges " + x + ", " + y + ", " + z + " form a triangle"+ isTriangle);
    }
    else {
        System.out.print("Can edges " + x + ", " + y + ", " + z + " form a triangle"+ isTriangle);
    }
    }

为什么当我在 system.out 中调用 x y 和 z 时,它们不显示输入的输入,但当我只将 isTriangle 放在 system.out 上时,它会给我输出

最佳答案

只需调用 nextInt 三次即可。

System.out.print("Enter the 3 edges of the triangle to be calculated: ");
a = input.nextInt();
b = input.nextInt();
c = input.nextInt();

有输入

5 5 5

它打印true

您必须检查是否有三个可用的数字(使用input.hasNextInt()beforeinput.nextInt()) :

System.out.print("Enter the 3 edges of the triangle to be calculated: ");
if(input.hasNextInt()) {
    a = input.nextInt();
} else {
    //handle it, you don't have ints!
}
if(input.hasNextInt()) {
    b = input.nextInt();
} else {
    //handle it, you have just one int!
}
if(input.hasNextInt()) {
    c = input.nextInt();
} else {
    //handle it, you have just two ints!
}

DEMO

关于java - 如何读取仅由空格分隔的一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25660338/

相关文章:

java - Eclipse 在 Ubuntu 上找不到 Java

java - 如何使用 CompletableFuture 返回一个值

java - 访问FXML生成的节点

java - 使用特定数字来达到目标​​数字

Java 客户端/服务器不返回 UTF-8 字符串

java - 如何在 Java 中将整数的字符串表示形式转换为字符串?

c - 如何为大整数实现整数数组加法器?

python - 我如何在python上找到第一个路径空白的索引

css - 页面顶部的神秘空白

html - 使用 "white-space: pre"NOT working 在 HTML 选择元素选项中保留空格