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

后端 未结 17 1365
天涯浪人
天涯浪人 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:41

    There is more than one way to do that but simple one is using String.split(" ") this is a method of String class that separate words by a spacial character(s) like " " (space)


    All we need to do is save this word in an Array of Strings.

    Warning : you have to use scan.nextLine(); other ways its not going to work(Do not use scan.next();

    String user_input = scan.nextLine();
    String[] stringsArray = user_input.split(" ");
    

    now we need to convert these strings to Integers. create a for loop and convert every single index of stringArray :

    for (int i = 0; i < stringsArray.length; i++) {
        int x = Integer.parseInt(stringsArray[i]);
        // Do what you want to do with these int value here
    }
    

    Best way is converting the whole stringArray to an intArray :

     int[] intArray = new int[stringsArray.length];
     for (int i = 0; i < stringsArray.length; i++) {
        intArray[i] = Integer.parseInt(stringsArray[i]);
     }
    

    now do any proses you want like print or sum or... on intArray


    The whole code will be like this :

    import java.util.Scanner;
    public class Main {
        public static void main(String[] args) {
    
            Scanner scan = new Scanner(System.in);
            String user_input = scan.nextLine();
            String[] stringsArray = user_input.split(" ");
    
            int[] intArray = new int[stringsArray.length];
            for (int i = 0; i < stringsArray.length; i++) {
                intArray[i] = Integer.parseInt(stringsArray[i]);
            }
        }
    }
    

提交回复
热议问题