0
public class P7 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int range=scanner.nextInt();
        for(int i=1;i<=range;i++){
            String stringInput =scanner.nextLine();
            String[] total =stringInput.split("\\s");
            int length=total.length;
            System.out.println(length);
        } 
    }
}

If you input range as 3 it will print its length as 1. But first iteration should print the length after getting stringInput. Moreover when you input range as a String, you will get InputMismatchException. Which is correct. So where is the problem? Thanks.

  • 3
    Possible duplicate of [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Jacob G. Jul 19 '18 at 13:22
  • So.. what is your exact input ? – Morta Jul 19 '18 at 13:23

1 Answers1

1

Scanner.nextInt() only consumes up to the number that you input and leaves the "\n" in the Scanner buffer. You can clear that buffer by using Scanner.next() right after you call Scanner.nextInt().

import java.util.Scanner;

public class StackOverflow {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int range=scanner.nextInt();
        scanner.next();

        for(int i=1;i<=range;i++){
            String stringInput =scanner.nextLine();
            String[] total =stringInput.split("\\s");
            int length=total.length;
            System.out.println(length);
        }

        scanner.close();
    }
}

Result:

3
The asdfj
2
asldkja sfaslkj asdfljk
3
asdfjk asdfjlkasdf alksjdf asdflkj
4
Shar1er80
  • 8,751
  • 2
  • 16
  • 25