Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 21 of 21

Thread: do-while error

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default do-while error

    do{
    			System.out.print("\nPlease enter employee name: ");
    			employeeName = console.nextLine();
    			System.out.print("");
    			System.out.print("\nGender(M/m or F/f): ");
    			gender = console.next();
    			genderAns = gender.charAt(0);
     
    			if(genderAns == 'M' || genderAns == 'm' || genderAns == 'F' || genderAns == 'f')
    			{
    				switch (genderAns)
    				{
    					case 'M': case 'm': title = "Mr. "; break;
    					case 'F': case 'f': title = "Ms. "; break;
    				}
     
    				System.out.print("Please enter the hourly rate: $ ");
    				hourlyRate = console.nextInt();
    				System.out.print("Please enter the hours worked: ");
    				hoursWorked = console.nextInt();
     
    				grossPay = hoursWorked * hourlyRate;
     
    				if (grossPay <= 300.00)
    				{
    					witholdingPercent = 0.1;
    				}
    				else if (grossPay >= 300.01)
    				{
    					witholdingPercent = 0.12;
    				}
     
    				witholdingTax = grossPay * witholdingPercent;
     
    				netPay = grossPay - witholdingTax;
     
    				System.out.println("\n\t\t- Payslip -\n");
     
    				System.out.println("Employee: " + title + employeeName);
    				System.out.println("Gross Pay: $ " + df.format(grossPay));
    				System.out.println("Withholding Tax: $ " + df.format(witholdingTax));
    				System.out.println("Net Pay: $ " + df.format(netPay));
    			}
    			else
    			{
    				System.out.println("\nYou have entered an incorrect gender.");
    			}
     
    			System.out.print("\nDo you want to input another set of values (Y- yes or No-any key)?: ");
    			setValue = console.next();
    			setValueAns = setValue.charAt(0);
    		} while (setValueAns == 'Y' || setValueAns == 'y');

    The program's fine at first. But, when the user entered YES in
    System.out.print("\nDo you want to input another set of values (Y- yes or No-any key)?: ");

    The user won't be able to enter the employee name.

    How am I suppose to fix it?


  2. #2
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: do-while error

    It is because of how you are comparing strings.

    == tests for reference equality.

    .equals() tests for value equality.

    Consequently, if you actually want to test whether two strings have the same value you should use .equals() (except in a few situations where you can guarantee that two strings with the same value will be represented by the same object eg: String interning).

    == is for testing whether two strings are the same object.

    // These two have the same value
    new String("test").equals("test") ==> true 
     
    // ... but they are not the same object
    new String("test") == "test" ==> false 
     
    // ... neither are these
    new String("test") == new String("test") ==> false 
     
    // ... but these are because literals are interned by 
    // the compiler and thus refer to the same object
    "test" == "test" ==> true 
     
    // concatenation of string literals happens at compile time resulting in same objects
    "test" == "te" + "st"  ==> true
     
    // but .substring() is invoked at runtime, generating distinct objects
    "test" == "!test".substring(1) ==> false
    It is important to note that == is much cheaper than equals() (a single pointer comparision instead of a loop), thus, in situations where it is applicable (i.e. you can guarantee that you are only dealing with interned strings) it can present an important performance improvement. However, these situations are rare.

    Answer taken from stackflow, i had the same problem long ago or at least it seems is the same problem i had. try with .equals()

    more info about comparison: http://www.ensta-paristech.fr/~diam/...reobjects.html

  3. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    How will I apply .equals() in the program?

  4. #4
    Member
    Join Date
    May 2011
    Location
    west palm beach, FL
    Posts
    189
    My Mood
    Tired
    Thanks
    41
    Thanked 11 Times in 10 Posts

    Default Re: do-while error

    example of using .equals

    check.equals("Yes")

    instead of

    check == "Yes"

  5. #5
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: do-while error

    Quote Originally Posted by Haiz View Post
    How will I apply .equals() in the program?
    like this
    Quote Originally Posted by derekxec
    check.equals("Yes")
    in your case: setValueAns.equals("Y") || setValueAns.equals("y")

    there is a simpler way to do it though: setValueAns.equalsIgnoreCase("y")

  6. #6
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: do-while error

    Hikaros,
    Before making your comments about string comparison you should have first asked Haiz to show the declarations of the variable used in the program.
    One the of the variables he is using is 'setValueAns'. If this variable is of char type then the comparison he is making is perfect.
    while (setValueAns == 'Y' || setValueAns == 'y');

    Haiz, can you plz post your entire code?

    Syed.

    Syed.

  7. #7
    Member Hikaros's Avatar
    Join Date
    Sep 2013
    Posts
    42
    My Mood
    Love
    Thanks
    10
    Thanked 2 Times in 2 Posts

    Default Re: do-while error

    Oh you are right, i could have swore it was string because of the " but when you said that i noticed it was a '
    i completely missed it, but using .equals() he is able to make that shorter to have

    System.out.print("\nDo you want to input another set of values (Y- yes or No-any key)?: ");
    			setValue = console.next();
     
    		} while (setValue.equalsIgnoreCase("Y"));

    instead of

    System.out.print("\nDo you want to input another set of values (Y- yes or No-any key)?: ");
    			setValue = console.next();
    			setValueAns = setValue.charAt(0);
    		} while (setValueAns == 'Y' || setValueAns == 'y');

    Either way after thinking about it for a while is not the comparison method the main problem (if i'm not wrong again lol) but that setValue is not actually saving the user input, for example, if the user types in "y", the setValue = console.next(); is actually not storing the right data.

    try this: change every console.nextInt(); to Integer.parseInt(input.nextLine());

    and leave the comparison as it is if you want (for your own testing purposes).

    Took the liberty to code this so you can see the scanner acts weird when you use scanner.nextInt() and then you use scanner.nextLine();

    import java.util.Scanner;
     
    public class Main {
        public static void main(String[] args){
            Scanner input = new Scanner(System.in);
            String s;
            Character c;
            int n;
     
            System.out.println("Integer: ");
            //n = input.nextInt();
            n = Integer.parseInt(input.nextLine());
            System.out.println("The integer is:"+n);
     
            System.out.println("String: ");
            s = input.nextLine();
            System.out.println("The string is: "+s);
     
            System.out.println("char: ");
            c = input.nextLine().charAt(0);
     
            if (s == "y"  || s == "Y")
                System.out.println("String Yes (using ==)");
            else
                System.out.println("String No (using ==)");
     
            if (s.equalsIgnoreCase("y"))
                System.out.println("String Yes (.equalsIgnoreCase())");
            else
                System.out.println("String No (.equalsIgnoreCase())");
     
     
            if (c == 'y' || c == 'Y')
                System.out.println("Char Yes");
            else
                System.out.println("Char NO");
        }
    }

    if you compile it as it is, there will be no problem because i am using Integer.parseInt(input.nextLine());
    but if you comment that out and take the slashes out of the one using input.nextInt(); it won't act how it should be.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: do-while error

    To add to Hikaros' explanation:

    Imagine keyboard input (System.in) as being stored in a buffer. Every key pressed by the user is added to the buffer, including the Return or linefeed. Most of Scanner's methods that begin with 'next' do not take the linefeed character from the keyboard buffer but use it as a separator between tokens or an indication that input has ended. The one notable exception to what I've described is the method nextLine(). nextLine() takes everything in the buffer up to the next linefeed, stores it in the designated variable, discarding the <linefeed>.

    Considering that, this is what is happening:

    The user is asked, "Input another set of values?"
    The user enters: Yes<linefeed>
    The Scanner.next() method takes "Yes" from the buffer and assigns it to the variable setValue
    Note that <linefeed> is left in the buffer

    Then at the top of the do loop:
    The user is asked: Employee name?
    The Scanner.nextLine() method sees the <linefeed> that was left in the keyboard buffer by the previous Scanner statement and accepts that as the user's input.

    The 'fix' is to not leave the <linefeed> in the buffer. Either flush the buffer with a throwaway call to Scanner.nextLine(), or in this case, as Hikaros pointed out, change the last Scanner statement in the do/while loop to Scanner.nextLine().

    Good luck.

  9. #9
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: do-while error

    Guys,
    I have executed the following piece of code:
         public static void main(String str[])  {
            try  {
                Scanner s=new Scanner(System.in);
                String text=s.next();
                String text1=s.next();
                String text2=s.next();
                String text3=s.next();
                System.out.println("<"+text+">,<"+text1+">,<"+text2+">,<"+text3+">");
            }catch(Exception e){e.printStackTrace();}
         }

    And here is the input/output for the program:
    run:
    a
    b
    c
    d
    <a>,<b>,<c>,<d>
    BUILD SUCCESSFUL (total time: 7 seconds)

    After entering every letter I hit the Enter key on the keyboard.

    Thanks,
    Syed.

  10. #10
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    I tried this one:
    while (setValue.equalsIgnoreCase("Y"))
    but instead of continuing the program because i entered "Yes", the program ends.

    and when I tried this one:
    while(setValueAns.equals('Y') || setValueAns.equals('y'))

    the output says:
    --------------------Configuration: <Default>--------------------
    C:\Documents and Settings\Administrator\My Documents\Downloads\NetPay.java:71: char cannot be dereferenced
    } while(setValueAns.equals('Y') || setValueAns.equals('y'));
    ^
    C:\Documents and Settings\Administrator\My Documents\Downloads\NetPay.java:71: char cannot be dereferenced
    } while(setValueAns.equals('Y') || setValueAns.equals('y'));
    ^
    2 errors

    Process completed.


    --- Update ---

    This is my entire code:

    import java.util.Scanner;
    import java.text.DecimalFormat;
     
    public class NetPay{
    	public static void main (String [] args){
    		Scanner console = new Scanner(System.in);
    		DecimalFormat df = new DecimalFormat("#,###.00");
     
    		String employeeName, gender, setValue, title = "";
    		char genderAns, setValueAns;
    		int hourlyRate, hoursWorked, grossPay;
    		double witholdingPercent = 0.0, witholdingTax, netPay;
     
    		System.out.println("================================================");
    		System.out.println("Programmer: ");
    		System.out.println("ID No.: ");
    		System.out.println("About: This program is a simple payroll application.");
    		System.out.println("================================================");
    		System.out.println("\n\t\t* PAYROLL *");
     
    		do{
    			System.out.print("\nPlease enter employee name: ");
    			employeeName = console.nextLine();
    			System.out.print("Gender(M/m or F/f): ");
    			gender = console.next();
    			genderAns = gender.charAt(0);
     
    			if(genderAns == 'M' || genderAns == 'm' || genderAns == 'F' || genderAns == 'f')
    			{
    				switch (genderAns)
    				{
    					case 'M': case 'm': title = "Mr. "; break;
    					case 'F': case 'f': title = "Ms. "; break;
    				}
     
    				System.out.print("Please enter the hourly rate: $ ");
    				hourlyRate = console.nextInt();
    				System.out.print("Please enter the hours worked: ");
    				hoursWorked = console.nextInt();
     
    				grossPay = hoursWorked * hourlyRate;
     
    				if (grossPay <= 300.00)
    				{
    					witholdingPercent = 0.1;
    				}
    				else if (grossPay >= 300.01)
    				{
    					witholdingPercent = 0.12;
    				}
     
    				witholdingTax = grossPay * witholdingPercent;
     
    				netPay = grossPay - witholdingTax;
     
    				System.out.println("\n\t\t- Payslip -\n");
     
    				System.out.println("Employee: " + title + employeeName);
    				System.out.println("Gross Pay: $ " + df.format(grossPay));
    				System.out.println("Withholding Tax: $ " + df.format(witholdingTax));
    				System.out.println("Net Pay: $ " + df.format(netPay));
    			}
    			else
    			{
    				System.out.println("\nYou have entered an incorrect gender.");
    			}
     
    			System.out.print("\nDo you want to input another set of values (Y- yes or No-any key)?: ");
    			setValue = console.next();
    			setValueAns = setValue.charAt(0);
    		} while (setValueAns == 'Y' || setValueAns == 'y');
     
    		System.out.println("\n================================================");
    		System.out.println("\t\t* END OF PROGRAM *");
    		System.out.println("================================================");
    	}
    }

  11. #11
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: do-while error

    Quote Originally Posted by Haiz View Post
    This is my entire code:
    Do you have a question about your entire code?

  12. #12
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    Syed asked me to post it.
    Quote Originally Posted by syedbhai View Post
    Haiz, can you plz post your entire code?
    Maybe it could help you, guys to determine what's wrong with my program.

  13. #13
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: do-while error

    Why don't you tell us whats wrong with it rather than make me guess.
    Sample run produced:
    ================================================
    Programmer:
    ID No.:
    About: This program is a simple payroll application.
    ================================================

    * PAYROLL *

    Please enter employee name: asdf
    Gender(M/m or F/f): f
    Please enter the hourly rate: $ 1
    Please enter the hours worked: 53

    - Payslip -

    Employee: Ms. asdf
    Gross Pay: $ 53.00
    Withholding Tax: $ 5.30
    Net Pay: $ 47.70

    Do you want to input another set of values (Y- yes or No-any key)?: y

    Please enter employee name: Gender(M/m or F/f): m
    Please enter the hourly rate: $ 24
    Please enter the hours worked: 14

    - Payslip -

    Employee: Mr.
    Gross Pay: $ 336.00
    Withholding Tax: $ 40.32
    Net Pay: $ 295.68

    Do you want to input another set of values (Y- yes or No-any key)?: n

    ================================================
    * END OF PROGRAM *
    ================================================

  14. #14
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    Quote Originally Posted by jps View Post
    Why don't you tell us whats wrong with it rather than make me guess.
    Sample run produced:
    Instead of continuing the program because I entered YES, it just stopped.
    ================================================
    Programmer: 
    ID No.: 
    About: This program is a simple payroll application.
    ================================================
     
    * PAYROLL *
     
    Please enter employee name: asdf
    Gender(M/m or F/f): f
    Please enter the hourly rate: $ 1
    Please enter the hours worked: 53
     
    - Payslip -
     
    Employee: Ms. asdf
    Gross Pay: $ 53.00
    Withholding Tax: $ 5.30
    Net Pay: $ 47.70
     
    Do you want to input another set of values (Y- yes or No-any key)?: YES
    ================================================
    * END OF PROGRAM *
    ================================================

  15. #15
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: do-while error

    Check your input against the loop condition. Of course it will stop.
    Improving the world one idiot at a time!

  16. #16
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: do-while error

    Junky,
    The loop condition is perfect. It will not stop because of YES.

    Haiz,
    I discovered the problem in your code. Scanner class object has one strange behavior. After invoking next() method if we invoke nextLine() there is a problem. The problem is stated below.
    Suppose next() method is invoked. We entered some text say "abc" and hit the enter key. the input "abc" will be consumed. If we immediately invoke nextLine() then the method nextLine() is consuming the new line character '\n' that was entered with "abc".
    Thats why in your code after you enter the last input which is yes/no (using next() at the end of loop) immediately nextLine() will be called at the beginning of the loop. Because of line feed entered with your yes/no, employee name is taken as "". It will straight-away jump to gender.
    So the fix is at the end of the loop just add console.nextLine() as the last statement.
    Note: I executed your program in NetBeans 7.3 with jdk 1.6.

    Syed.

  17. #17
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    Quote Originally Posted by syedbhai View Post
    Junky,
    So the fix is at the end of the loop just add console.nextLine() as the last statement.
    Note: I executed your program in NetBeans 7.3 with jdk 1.6.
    Sorry, I don't get it. Where exactly will I add console.nextLine() ?

  18. #18
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: do-while error

    Hi,
    After the statement setValueAns = setValue.charAt(0);

    Syed.

  19. #19
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: do-while error

    I doubt adding that line after the user response is read in will alter anything.

    Try adding a print statement to display what value setValueAns actually holds.
    Improving the world one idiot at a time!

  20. #20
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    Quote Originally Posted by syedbhai View Post
    Hi,
    After the statement setValueAns = setValue.charAt(0);

    Syed.
    What exact code should i put after that statement? Just console.nextLine(); ?

  21. #21
    Junior Member
    Join Date
    Sep 2013
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: do-while error

    Finally! I got it! Thanks, Syed!

Similar Threads

  1. Please! Help me to this error "ERROR CANNOT FIND SYMBOL"
    By mharck in forum Object Oriented Programming
    Replies: 8
    Last Post: July 3rd, 2012, 09:20 AM