Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Scanner String input

Tags:

I'm writing a program that uses an Event class, which has in it an instance of a calendar, and a description of type String. The method to create an event uses a Scanner to take in a month, day, year, hour, minute, and a description. The problem I'm having is that the Scanner.next() method only returns the first word before a space. So if the input is "My Birthday", the description of that instance of an Event is simply "My".

I did some research and found that people used Scanner.nextLine() for this issue, but when I try this, it just skips past where the input should go. Here is what a section of my code looks like:

System.out.print("Please enter the event description: ");
String input = scan.nextLine();
e.setDescription(input);
System.out.println("Event description" + e.description);
e.time.set(year, month-1, day, hour, min);
addEvent(e);
System.out.println("Event: "+ e.time.getTime());    

And this is the output I get:

Please enter the event description: Event description
Event: Thu Mar 22 11:11:48 EDT 2012

It skips past the space to input the description String, and as a result, the description (which is initially set to a blank space - " "), is never changed.

How can I fix this?

like image 819
HolidayTrousers Avatar asked May 11 '11 15:05

HolidayTrousers


People also ask

What does nextLine () Do Java?

nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

Does Scanner nextLine return a string?

The nextLine() method of the java. util. Scanner class scans from the current position until it finds a line separator delimiter. The method returns the String from the current position to the end of the line.


2 Answers

When you read in the year month day hour minutes with something like nextInt() it leaves rest of the line in the parser/buffer (even if it is blank) so when you call nextLine() you are reading the rest of this first line.

I suggest you call scan.nextLine() before you print your next prompt to discard the rest of the line.

like image 187
Peter Lawrey Avatar answered Sep 22 '22 08:09

Peter Lawrey


    Scanner ss = new Scanner(System.in);
    System.out.print("Enter the your Name : ");
    // Below Statement used for getting String including sentence
    String s = ss.nextLine(); 
   // Below Statement used for return the first word in the sentence
    String s = ss.next();
like image 31
Logan M Avatar answered Sep 20 '22 08:09

Logan M