Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The assignment requires me to make a simple 'thankyou email generator' where I enter a name and amount of money donated and it generates an email.. Here is the source code

    while (keepgoing)
        {
            
            
            
            out.println("What is the persons name?");
            
            String personname = keyboard.nextLine();
            
            out.println("How much did they donate?");
            
            int donation = keyboard.nextInt();
            
            out.println(" Dear " + personname + "");
            out.println("Thankyou for your donation of  $"   + donation + "\n");
            
           
            out.println("Regards, Will");

For the first run it works as needed, but on the second it skips the String input and goes straight to the Int.

What I have tried:

It works as needed if personname is an int variable, no matter how many times it loops but once I switch back to String it skips again..
Posted
Updated 20-Nov-17 18:40pm

Quote:
but on the second it skips the String input and goes straight to the Int.

No, it is not magically skip the string!
Simply when execution reach keyboard.nextLine(), it find all what it need in keyboard buffer and then process it without waiting.
as proof, input a donation as "123 456abc"
123<Space>456abc<Enter>

"456abc" will be your next "persons name".

You need to read documentation about keyboard input functions.
 
Share this answer
 
Comments
wilma2202 21-Nov-17 0:44am    
Ok, how do I fix this then? The course I am doing has never mentioned what a keyboard buffer is.. Can you recommend a video, or an article for me to read?
Patrice T 21-Nov-17 1:04am    
I see you already got an answer in solution 2.
As already suggested, it is a good idea to read the documentation.
Add a newline after every nextInt():
int donation = keyboard.nextInt();
keyboard.nextLine();
nextLine()[^] and nextInt()[^] behave differently.
+++++[More Elaboration]+++++
nextInt() only takes the next integer inputted, ignoring the newline, which is then taken in by
String personname = keyboard.nextLine()
in the next iteration, that explained why it was skipped without waiting for user's input. The standalone keyboard.nextLine() after the nextInt() is just a hack to absorb this left over newline before it go to String personname = keyboard.nextLine().
 
Share this answer
 
v5
Comments
wilma2202 21-Nov-17 0:54am    
Thanks so much!

Are you able to explain to me why this is?
Peter Leow 21-Nov-17 1:19am    
Added in my solution.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900