Prashant G
Prashant G

Reputation: 4900

Why cant I read whole line along with double using Scanner(System.in)?

What actually happens here ? Why can't I store a String with spaces in between as name ? I tried the delimiter thing, but didn't worked. Is there a way that will produce the desired output ? I know .next() works but we might need to store a string with space. Just curious ...

  Scanner input=new Scanner(System.in);
  System.out.print("Enter number of Students:");    
  double [] scores = new double[input.nextInt()];   
  String [] names=new String[scores.length];

      for(int i=0;i<names.length;i++){
          System.out.println("Enter the students name: ");
          names[i] = input.nextLine();

          System.out.println("Enter the student scores : ");
          scores[i]=input.nextDouble();
      }

Upvotes: 1

Views: 239

Answers (3)

Prashant G
Prashant G

Reputation: 4900

This is how it works ! Thanks for concern guys! :)

  for(int i=0;i<names.length;i++){
      if(input.nextLine().equals("")){
          System.out.println("Enter students name : ");
          names[i] = input.nextLine();
      }
      System.out.println("Enter the student scores : ");
      scores[i]=input.nextDouble();
  }

Upvotes: 0

vandale
vandale

Reputation: 3650

when you call input.nextInt(), it doesn't consume the new line character on that line, so the following call to input.nextLine(); will consume the newline, and return the empty string. nextDouble() will function properly.

one way to fix this is to call input.nextLine(); immediately before the for loop to consume the extra new line character

Edit:

String [] names=new String[scores.length];
input.nextLine(); //literally add the call right here
      for(int i=0;i<names.length;i++){

Upvotes: 3

Orposuser
Orposuser

Reputation: 329

According to the Javadoc:

A simple text scanner which can parse primitive types and strings using regular expressions. 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.

What if you replace the default delimiter with "\n" like this:

Scanner s = new Scanner(input).useDelimiter("\\\\n");

Upvotes: 0

Related Questions