-2

I have heard that nextInt() reads only the integers and ignores the \n at the end. So why does the following code runs successfully?

Why there is no error after we enter value of a since \n must remain in the buffer , so use of nextInt() at b should give an error but it doesn't . Why?

 import java.util.Scanner;

    public class useofScanner {
    public static void main(String[] args) {
        Scanner scanner =new Scanner(System.in);
        int a = scanner.nextInt();
        int b=scanner.nextInt();
        System.out.println(a+b);
    }
    }
Sajit Gupta
  • 98
  • 1
  • 6

1 Answers1

1

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For example, this code allows a user to read a number from System.in:

 Scanner sc = new Scanner(System.in);
 int i = sc.nextInt();

As another example, this code allows long types to be assigned from entries in a file myNumbers:

  Scanner sc = new Scanner(new File("myNumbers"));
  while (sc.hasNextLong()) {
      long aLong = sc.nextLong();
  }

The scanner can also use delimiters other than whitespace. This example reads several items in from a string:

 String input = "1 fish 2 fish red fish blue fish";
 Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
 System.out.println(s.nextInt());
 System.out.println(s.nextInt());
 System.out.println(s.next());
 System.out.println(s.next());
 s.close(); 

prints the following output:

 1
 2
 red
 blue
l4nd0
  • 67
  • 1
  • 6