Home > Software design >  How do the user input space separated values get stored until they are assigned to the variable in t
How do the user input space separated values get stored until they are assigned to the variable in t

Time:02-24

Consider the following code;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        for (int i=0;i<5;i  ) {
          int n = in.nextInt();
          System.out.print(v);  
        }
   }
}

For the above code, if we enter the input by giving some random numbers separated by a space; eg: 7 8 9, then the output will be shown as '789'. After that there will only be 2 iterations left to go. I figured that when we input some values separated by a space, the first value will be assigned to the variable and the second value will be assigned to the variable at the next iteration of the loop and then the 3rd and so on. My question is how and where do these values get stored until they get assigned to the variable?

CodePudding user response:

A quick search shows the online code, for example the OpenJDK version is here.

And looking at that file shows:

public final class Scanner implements Iterator<String>, Closeable {

    // Internal buffer used to hold input
    private CharBuffer buf;

    // Size of internal character buffer
    private static final int BUFFER_SIZE = 1024; // change to 1024;

So: "in a buffer in the Scanner instance" is your answer. But it is surely just characters, not "values", since the Scanner cannot know what you're going to ask for next: could be an integer, string, rest of line, etc.

  •  Tags:  
  • java
  • Related