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

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

    You want to take the numbers in as a String and then use String.split(" ") to get the 3 numbers.

    String input = scanner.nextLine();    // get the entire line after the prompt 
    String[] numbers = input.split(" "); // split by spaces
    

    Each index of the array will hold a String representation of the numbers which can be made to be ints by Integer.parseInt()

    0 讨论(0)
  • 2020-11-27 03:33

    Using BufferedReader -

    StringTokenizer st = new StringTokenizer(buf.readLine());
    
    while(st.hasMoreTokens())
    {
      arr[i++] = Integer.parseInt(st.nextToken());
    }
    
    0 讨论(0)
  • 2020-11-27 03:37

    This works fine ....

    int a = nextInt(); int b = nextInt(); int c = nextInt();

    Or you can read them in a loop

    0 讨论(0)
  • 2020-11-27 03:41

    Here is how you would use the Scanner to process as many integers as the user would like to input and put all values into an array. However, you should only use this if you do not know how many integers the user will input. If you do know, you should simply use Scanner.nextInt() the number of times you would like to get an integer.

    import java.util.Scanner; // imports class so we can use Scanner object
    
    public class Test
    {
        public static void main( String[] args )
        {
            Scanner keyboard = new Scanner( System.in );
            System.out.print("Enter numbers: ");
    
            // This inputs the numbers and stores as one whole string value
            // (e.g. if user entered 1 2 3, input = "1 2 3").
            String input = keyboard.nextLine();
    
            // This splits up the string every at every space and stores these
            // values in an array called numbersStr. (e.g. if the input variable is 
            // "1 2 3", numbersStr would be {"1", "2", "3"} )
            String[] numbersStr = input.split(" ");
    
            // This makes an int[] array the same length as our string array
            // called numbers. This is how we will store each number as an integer 
            // instead of a string when we have the values.
            int[] numbers = new int[ numbersStr.length ];
    
            // Starts a for loop which iterates through the whole array of the
            // numbers as strings.
            for ( int i = 0; i < numbersStr.length; i++ )
            {
                // Turns every value in the numbersStr array into an integer 
                // and puts it into the numbers array.
                numbers[i] = Integer.parseInt( numbersStr[i] );
                // OPTIONAL: Prints out each value in the numbers array.
                System.out.print( numbers[i] + ", " );
            }
            System.out.println();
        }
    }
    
    0 讨论(0)
  • 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]);
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:42

    Try this

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in); 
        while (in.hasNext()) {
            if (in.hasNextInt())
                System.out.println(in.nextInt());
            else 
                in.next();
        }
    }
    

    By default, Scanner uses the delimiter pattern "\p{javaWhitespace}+" which matches at least one white space as delimiter. you don't have to do anything special.

    If you want to match either whitespace(1 or more) or a comma, replace the Scanner invocation with this

    Scanner in = new Scanner(System.in).useDelimiter("[,\\s+]");
    
    0 讨论(0)
提交回复
热议问题