This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
Just curious, I had written a simple program for class that was illustrating constructors, set and get methods. I used the Scanner class to get user input for employee first and last name, and monthly salary. There were 2 employee objects that came from the class, both of which had the previously mentioned attributes.
Using the Scanner class, the user would for employee 1 enter first name, last name, then monthly salary. These were 3 separate steps using an object of the Scanner class called sc. It worked fine for the employee 1 object, but for employee 2 the user would not be given the opportunity to enter the first name, it would display the println string prompting the user to enter the first name for employee 2, but would jump to entering last name for employee 2 and allowing them to enter the last name. The salary for employee 2 could be entered as intended as well. The necessary code for entering the first name for employee 2 was present. Everything looked the way it should have.
The fix I came up with was forming a second Scanner class object for use with the second employee object. It no longer skipped the step to enter employee 2's first name and all is well. Why is this?
Sorry this is so long winded, I can attach the code if it would help.
Please forgive the simplicity of the assignment. I was just curious as to why the problem had occured. You will see object sc being used for getting info for the second employee object. When I included a second Scanner class is what resolved it. Please be gentle with how I went about coding this. We were specifically told not to use a GUI. Also, please forgive the formatting in the code section. That's how it pasted over.
Joined: Oct 13, 2005
Use sc.next() for a word rather than nextLine(). Then you can write "Brandt Charles" and have Brandt for 1st name and Charles for 2nd name. You can get 1234.56 on the same line as the salary.
You should be able to get away with one Scanner object only. Try
You have sc2 in, which you don't need. Apart from that, your programming seems to work.