How to read multiple Integer values from a single line of input in Java?

后端 未结 17 1402
天涯浪人
天涯浪人 2020-11-27 03:16

I am working on a program and I want to allow a user to enter multiple integers when prompted. I have tried to use a scanner but I found that it only stores the first intege

17条回答
  •  半阙折子戏
    2020-11-27 03:46

    When we want to take Integer as inputs
    For just 3 inputs as in your case:

    import java.util.Scanner;
    Scanner scan = new Scanner(System.in);
    int a,b,c;
    a = scan.nextInt();
    b = scan.nextInt();
    c = scan.nextInt();
    

    For more number of inputs we can use a loop:

    import java.util.Scanner;
    Scanner scan = new Scanner(System.in);
    int a[] = new int[n]; //where n is the number of inputs
    for(int i=0;i

提交回复
热议问题