Results 1 to 5 of 5
Like Tree1Likes
  • 1 Post By Fubarable

Thread: Problem with scanner?

  1. #1
    Modulus is offline Member
    Join Date
    Feb 2013
    Posts
    11
    Rep Power
    0

    Default Problem with scanner?

    Hello all, I am new to these forums and this is my first post, probably won't be my last either so any help from you more advanced users would be much appreciated! I do have a little bit of a background in programming. I wrote a little bit when I was a kid in QBasic and for the past year have been teaching myself Python, but am new to Java and the concept of object-oriented programming. Now that my little introduction is done, here is my question... I am in the third week of my Java class and have to modify a payroll program to terminate when the user enters "stop". I just used a basic while loop to keep looping and a single-selection if statement to break out of the loop if "stop" is entered. The problem I am running into is the first time it loops it works great! Every time it loops after that the first two inputs show up together like this:

    Enter employee's name or stop to quit:
    What is the hourly pay rate:

    I do not know why this is happening, but imagine it has something to do with the scanner not clearing. Can someone explain to me why this is happening so I can understand this? I have looked for hours online and just found a bunch of links to the code for this payroll program, which I don't just want to copy... I need to understand this. Any help would be much appreciated. Here is my code:


    Java Code:
    import java.util.Scanner;
    
    public class Payroll2 
    {
    	public static void main (String[] args)
    	{
    	Scanner Input = new Scanner (System.in);
    	
    	double hoursWorked;
    	double hourlyPay;
    	double weeklyPay;
    	String empName;
    	
    	while (true)
    		{
    		System.out.println("Enter employee's name or stop to quit: ");
    		empName = Input.nextLine();
    		
    		if (empName.equalsIgnoreCase("stop"))
    			break;
    		
    		System.out.println("What is the hourly pay rate: ");
    		hourlyPay = Input.nextDouble();
    			
    		System.out.println("How many hours did the employee work: ");
    		hoursWorked = Input.nextDouble();
    			
    		weeklyPay = hourlyPay * hoursWorked;
    			
    		System.out.printf("%s's weekly pay is $%.2f\n\n",
    								empName, weeklyPay);
    		}
    	}
    }
    Also if there are any other improvements that can be made feel free to point those out too...

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Problem with scanner?

    The key point to understand is which Scanner methods handle the end of line (EOL) token, and you're finding that nextLine() does handle it while nextDouble() does not. Because of this, your nextLine() call will swallow the EOL token left over from your last call to nextDouble() and will short-circuit your program.

    One solution is to add a call to nextLine() after every call to nextDouble() (or nextInt() or similar calls) to handle the token. So instead of:

    Java Code:
    double myDouble = myScanner.nextDouble();
    System.out.println("myDouble is: " + myDouble);
    do this:

    Java Code:
    double myDouble = myScanner.nextDouble();
    myScanner.nextLine();  // call nextLine() to handle and discard the EOL token
    System.out.println("myDouble is: " + myDouble);
    Other suggestions:
    • All Java variable and method names should begin with a lower case letter and all class names with an upper case letter.
    • Enclose *all* code blocks in curly braces, namely the brake statement in your if block should be inside of a pair of these braces, { }. This will save you grief later, trust me.
    • Use %n and not \n for new lines inside of a printf(...) method call. I have forgotten why this matters, but do remember that it does.
    Last edited by Fubarable; 02-02-2013 at 10:48 PM.

  3. #3
    Modulus is offline Member
    Join Date
    Feb 2013
    Posts
    11
    Rep Power
    0

    Default Re: Problem with scanner?

    Thank you for the reply!

    I actually got it to work somehow by moving this line inside and at the start of the while loop.

    Java Code:
    Scanner Input = new Scanner (System.in);
    I will definitely change it back though and go with your suggestion as I am not sure if this is improper practice.

    Thank you for the other suggestions as well. If I understand correctly I only need the braces {} if there are multiple statements in the selection, but I suppose it will be good to get in the habit of doing it all the time.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,315
    Blog Entries
    1
    Rep Power
    26

    Default Re: Problem with scanner?

    Quote Originally Posted by Modulus View Post
    Thank you for the reply!

    I actually got it to work somehow by moving this line inside and at the start of the while loop.

    Java Code:
    Scanner Input = new Scanner (System.in);
    It's not a good habit to do that in this case, to create new Scanner objects repeatedly in the loop, particularly since you're not closing any Scanner instances and risk using up system resources (not with this program but perhaps with others if you do the same thing). Also, I believe that there is risk if you do in fact close a Scanner that uses System.in. Note that I sometimes do create Scanner objects inside of a loop, particularly if I want to extract tokens from a String newly obtained in the loop, but when doing so, I close it when I'm through with it.

    I will definitely change it back though and go with your suggestion as I am not sure if this is improper practice.
    In this situation, this is what I recommend you do.

    Thank you for the other suggestions as well. If I understand correctly I only need the braces {} if there are multiple statements in the selection, but I suppose it will be good to get in the habit of doing it all the time.
    You may need to burn yourself once to fully convince your inner self of the benefit to this.
    Modulus likes this.

  5. #5
    Modulus is offline Member
    Join Date
    Feb 2013
    Posts
    11
    Rep Power
    0

    Default Re: Problem with scanner?

    Here is my assignment after the modifications. I hope I understood you correctly about the scanner issue I was having and I changed my Input variable to input Everything seems to be working the way it should without a new scanner being created with each iteration.

    Java Code:
    //Payroll2.java
    
    import java.util.Scanner; //program uses scanner
    
    public class Payroll2 
    {
    	//main method begins program execution
    	public static void main (String[] args)
    	{
    	//create scanner to obtain input from command window
    	Scanner input = new Scanner (System.in);
    	
    	//defines the variables
    	double hoursWorked;
    	double hourlyPay;
    	double weeklyPay;
    	String empName;
    	
    	System.out.println("\nWelcome to the Payroll Program");
    	System.out.println("This program will calculate weekly pay\n");
    	
    	while (true)
    		{
    		//prompt employee name input
    		System.out.print("Enter employee's name or stop to quit: ");
    		empName = input.nextLine();
    		// breaks the loop if stop is entered
    		if (empName.equalsIgnoreCase("stop"))
    		{
    			break;
    		}
    		//prompt hourly pay rate
    		System.out.printf("What is %s's hourly pay rate: ", empName);
    		hourlyPay = input.nextDouble();
    		input.nextLine();
    		//checks for positive number
    		//allowed 0 as input in case employee still needs to be kept on record
    		if (hourlyPay < 0)
    		{
    			System.out.println("You must enter a positive number");
    			System.out.printf("What is %s's hourly pay rate: ", empName);
    			hourlyPay = input.nextDouble();
    			input.nextLine();
    		}	
    		//prompt hours worked
    		System.out.printf("How many hours did %s work: ", empName);
    		hoursWorked = input.nextDouble();
    		input.nextLine();
    		//checks for positive number
    		//allowed 0 as input in case employee still needs to be kept on record
    		if (hoursWorked < 0)
    		{
    			System.out.println("You must enter a positive number");
    			System.out.printf("How many hours did %s work: ", empName);
    			hoursWorked = input.nextDouble();
    			input.nextLine();
    		}	
    		//performs calculation	
    		weeklyPay = hourlyPay * hoursWorked;
    		//outputs results
    		System.out.printf("%s's weekly pay is $%.2f%n%n",
    								empName, weeklyPay);
    		}//end while
    	}//end main
    }//end class Payroll2
    Really appreciate all the info! I know these are probably pretty noobish questions I have, but hopefully someday soon I can look back and wonder how I could have struggled with something so simple
    Last edited by Modulus; 02-03-2013 at 05:24 AM.

Similar Threads

  1. problem with scanner
    By fiction in forum New To Java
    Replies: 3
    Last Post: 02-03-2013, 01:32 AM
  2. max and min scanner problem
    By jwl in forum New To Java
    Replies: 2
    Last Post: 10-28-2012, 08:57 PM
  3. Problem with the Scanner
    By Maretaga in forum New To Java
    Replies: 6
    Last Post: 07-14-2011, 10:14 AM
  4. Problem with scanner
    By JavaJ in forum New To Java
    Replies: 6
    Last Post: 03-16-2010, 09:51 PM
  5. Problem with scanner
    By Kangaroo128 in forum New To Java
    Replies: 11
    Last Post: 09-01-2009, 09:07 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •