Home > database >  scanner skipping my nextline() statement in constructor
scanner skipping my nextline() statement in constructor

Time:10-23

ok so I know after nextInt() if we use nextLine() it will skip it, and to correct that we used extra nextLine() before it to correct it. That's is fine but the problem is i am scanning values in a constructor and i cannot add extra nextLine() in it cuz it gives me error.

product c2=new product(value.nextInt(),value.nextLine(),value.nextDouble());

CodePudding user response:

ok so I know after nextInt() if we use nextLine() it will skip it, and to correct that we used extra nextLine() before it to correct it.

This isn't true. Scanners split on any spaces, so if you enter "5" then press enter and then enter, say, "Hello", the above will work fine. But if the user enters "5", then hits space (yaknow, the biggest key on that keyboard!) and then types "Hello", your code will break.

The correct solution is instead to never use nextLine. instead, configure your scanner properly:

Scanner s = new Scanner(System.in);
s.useDelimiter("\\R");
String entireLine = s.next(); // this replaces nextLine
int aNumber = s.nextInt();

\\R is regexpese for: A single newline. Which is what you expected Scanner to do out of the box (out of the box, scanner has a weird default - 'any amount of whitespace'. Not what you want when handling command line input like this).

With a scanner configured properly, your constructor will work great.

If somehow this is flat out impossible, make utility methods that are marked static and pass your scanner to it; you can invoke them from inside the super() line of your constructor. But this is a very distant crappy second choice compared to just setting up the scanner properly.

CodePudding user response:

You can get data by scanner in others variable then pass it to the constructor it s better

  • Related