如何从仅用空格分隔的一行读取?

时间:2014-09-04 08:08:19

标签: 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个整数,而是希望它们全部位于用空格分隔的同一行中。我是否需要将标准输入更改为字符串然后在布尔部分之后解析它?我很困惑,因为在输入整数之后,我不知道将它们存储在哪里用于布尔部分。

编辑部分:

    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上时它会给我输出

3 个答案:

答案 0 :(得分:1)

最好在下面使用。

    String values=scanner.next();//if your input 5 5 5
   String numinString[]=values.split(" ");
   int a=Integer.parseInt(numinString[0]);//a=5
   int b=Integer.parseInt(numinString[1]);//b=5
   int c=Integer.parseInt(numinString[2]);//c=5

答案 1 :(得分:0)

只需拨打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()之前使用input.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

答案 2 :(得分:0)

你可以这样做:

    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: ");
    a = input.nextInt();
    b = input.nextInt();
    c = 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));
    if (isTriangle)
        System.out.print(isTriangle);

    else

        System.out.print(isTriangle);