aspose file tools*
The moose likes Beginning Java and the fly likes Sentinel-controlled loop with a String variable condition Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sentinel-controlled loop with a String variable condition" Watch "Sentinel-controlled loop with a String variable condition" New topic
Author

Sentinel-controlled loop with a String variable condition

Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
I'm pulling my hair out. I have a tiny, little Payroll program written. It asks for user input for name, hourly rate of pay, hours worked during week, calculates weekly pay, and displays all on the screen. It compiled and executed correctly.

Now, however, I have to modify it with a loop that will use "stop" in the variable name as a sentinel value. Until "stop" is input by the user in the name field, I need my little program to asks for and accept input in the fields name, hourlyRate, and weeklyHours. I have gone over and over the textbook sections that deal with loops, sentinel-controlled loops, while loops, do...while loops, for loops, if...else loops, nested loops. I even have the Java All-in-One Desk Reference for Dummies! All of the examples shown deal with integer control variables--Not String control variables. I found one thing--one--in my Java for Dummies that mentions that you cannot use (condition == "Yes") as a condition, because Java will not translate it literally as String equals "Yes". It goes on to instruct one to use condition.equalsIgnoreCase("Yes"). But it does Not tell one how to write the condition so the loop executes as long as the condition is Not met.

Here's my code so far: (Please be kind. I'm a total Java newbie.)


It compiles, and it executes. But it doesn't execute correctly. The loop executes correctly Once giving me the opportunity to enter name, rate of pay, hours, etc. one time. Then, the next iteration "Enter employee name: " and "Enter hourly rate of pay: " are back-to-back on the same line, and I am not given an opportunity to enter a new name.

Help? Please? I'm ready to cry, I'm so frustrated. This is due tomorrow, too.


Disclaimer: The author of this post makes no claims, implied or otherwise, as to her ability to understand anything but the simplest of answers. Further, the author of this post has no programming background whatsoever and has taken one Java Programming class which was 9 weeks long. She does want to learn, so please teach patiently.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

that you cannot use (condition == "Yes") as a condition

Strings act a bit differently in Java. When you want to check a String value, you would use the String#equals method. Like "stop".equals(name). This will return true if the name equals "stop". So you can now imagine how to loop while it is not equal to "stop". I'm surprised that none of your books talk about this. You must have missed it somewhere.


[My Blog]
All roads lead to JavaRanch
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Originally posted by Christophe Verre:

I'm surprised that none of your books talk about this. You must have missed it somewhere.


No, I assure you I haven't missed it. I definitely would have remembered seeing that. And, as I mentioned, I've been over and over the same material several times now. Of course, that doesn't mean that I won't find it later on in my textbook. <sigh> Could you please copy the line(s) of my code and show me exactly what I need to use to replace it with? I don't wish to be a nuisance, but I'm just about brain dead, at this point in time. Your response didn't entirely make sense to me. I'm sorry.
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14688
    
  16

I'd prefer to avoid copy/pasting the solution. You have at least two problems : the scanning method, and the loop condition. I was iving an hint about the loop condition only. You have :
.

This is not the correct way to compare Strings in Java. As I said in the previous post, you should use the equals() method of the String class. You can check the API to see what it does. You would write it like :

or


The equals() method returns a boolean. True if the things you compare are meaningfully equal. False otherwise. For example :


Try to figure out out to use the equals() method in your loop.
[ May 01, 2008: Message edited by: Christophe Verre ]
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Thank You!
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Since the name was 1. supposed to be a condition for the do...while loop and 2. the loop was to continue until "stop" was entered the correct statement was as follows:

while (!name.equals("stop"));
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
They obviously left out the ! because we don't like to give complete solutions, and they knew you would get the ! soon enough.

. . . and welcome to the Ranch.
[ May 08, 2008: Message edited by: Campbell Ritchie ]
C Bick
Greenhorn

Joined: Nov 18, 2008
Posts: 7
Sounds like she was taking the same class as I am now... I was able to follow along with the first part regarding the

while(!employeeName.equals("stop"))

line, but am still having troubles with the second problem she mentioned...on the second iteration of the loop, I am not given an opportunity to enter another employee's name, rather it skips straight to prompting for the employee's pay rate. If anyone can offer pointers, I would greatly appreciate it. Fortunately, this isn't due till friday so I have some time to play with it. My code is below:

// EmployeePay.java

//declare main class
import java.util.*; //imports scanner among others
import java.text.*; //Imports numberformat among others

public class EmployeePay
{
// declare variables
private String employeeName;
private Float totalPay;

public void displayWelcomeMessage()

{
System.out.println("Welcome to the Payroll Calculator 1.2!");

}

public void setEmployeeName( String name ) // takes variable from test objects and sets the name for output later
{
employeeName = name;
}

public void setTotalPay ( Float tpay ) // takes variable from test objects and sets the name for output later
{
totalPay = tpay;
}

public void calculatePay()
{
Scanner input = new Scanner( System.in );

//these three variables are used to calculate the weekly pay, but only total Pay is carried forward
float theRate;
float theHours;
float tPay;
String totalPay;
String employeeName;

//prompt for employee's name prior to first iteration of loop
System.out.println( "Please enter the employee name or 'stop' to quit:" );
employeeName = input.nextLine(); //read the input and set it to variable employeeName
System.out.println(); // print blank line

while(!employeeName.equals("stop"))
{

// prompt for employee's pay rate
System.out.println( "Please enter the rate of pay (as dollars per hour):" );
theRate = input.nextFloat(); // set user's entry to variable theRate
System.out.println(); // print blank line

// prompt for hours employee worked
System.out.println( "Please enter the hours worked:" );
theHours = input.nextFloat(); //set user's entry to variabl theHours
System.out.println(); // print blank line

//calculate employee's pay for the week
tPay = theRate * theHours;

//Sets string TotalPay equal to tPay only formatted as US currency
NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
totalPay = nf.format( tPay );

// output results
System.out.printf( "%s's pay for the week is %s", employeeName, totalPay );
System.out.println();

// prompt for employee name on second and subsequent iterations of loop
System.out.println( "Please enter the employee name or 'stop' to quit:" );
employeeName = input.nextLine(); //read the input and set it to variable employeeName
System.out.println(); // print blank line

}
}

}
C Bick
Greenhorn

Joined: Nov 18, 2008
Posts: 7
based on previous posts, I am guessing that the problem I am having now is caused by the scanning method...unfortunately that is the only method the book has introduced so far...I will try looking through some of the chapters for next week's assignments but am not sure if that will cover it...any help anyone can give would be greatly appreciated!
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 347
Originally posted by Robin Lane:
I'm pulling my hair out.


Big Moose Saloon... hmm.. it all makes sense now..

Bick,
Looks like the solution to your problem lies outside the loop..
Taariq San
Ranch Hand

Joined: Nov 20, 2007
Posts: 192
Originally posted by Gamini Sirisena:

Bick,
Looks like the solution to your problem lies outside the loop..


I've just run this code and at the end of the loop input.nextLine() which reassigns the employeeName does not cause the expected pause for input, yet input.nextAnythingElse() works fine.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
C Bick, welcome to JavaRanch

If memory serves me correctly, Robin didn't get her app to work in this thread; she came back several times and got it to work in another thread. So you are likely to pick up all sorts of errors by reading this thread.

We usually warn against reopening old threads (look at this dreadfully-named FAQ).

Please start a new thread describing your problem, and we'll see if we can get it cleared up
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Campbell, it's been so long ago that I don't even remember what the problem turned out to be. Something is niggling at the back of my mind regarding the version of Java I was using versus the version of Java the textbook was based on. Mine was the more recent version and my textbook gave a command for an earlier version--a command that had been changed slightly.

C Bick's suggestion that his problem was with the scanner was also my problem. It was something to do with the command for inputting the next name--I just can't remember the specifics and am not certain it truly matters. Moving on to other classes has cut out all of my Java time for a few months now.

[ November 19, 2008: Message edited by: Robin Lane ]
[ November 19, 2008: Message edited by: Robin Lane ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
Hello again

I always thought your main problem was that you got me helping you.
I don't think it was the Scanner that you had difficulties with; it was how to terminate the loop.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Originally posted by Campbell Ritchie:
Hello again

I always thought your main problem was that you got me helping you.
I don't think it was the Scanner that you had difficulties with; it was how to terminate the loop.


<cracks up laughing> Campbell, (brace yourself because I'm going to compliment/embarrass you!) you're one of the reasons I keep coming BACK! Honestly, my loop was garbage to begin with. I improved significantly when I ditched the do...while loop for a while repetition statement.

If, however, C Bick is using the same textbook I used, there IS a discrepancy involving the scanner method and the command used for entering Strings. An example in the textbook, if used exactly as shown, does not work with the most current version of Java. The Java API will put C Bick on the right track, if that is indeed his problem. It's where I finally found my answer. With so many different versions of Java apparently still in use, the discrepancy didn't "leap out" at other Ranchers.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3648
    
  15
I just read that old post and it seems the main reason you don't rememeber much about the actual problem was that the two of you spent most of the time flirting with each other

Once Campbell had worked out Robin was a girl that is (although it should have been fairly obvious from the disclaimer in her signature).
[ November 19, 2008: Message edited by: Joanne Neal ]

Joanne
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Originally posted by Joanne Neal:
I just read that old post and it seems the main reason you don't rememeber much about the actual problem was that the two of you spent most of the time flirting with each other [ November 19, 2008: Message edited by: Joanne Neal ]


Not flirting, Joanne. We were having laughs, yes. But not flirting. (Campbell will be horrified when he sees this!!) I apologize profusely if what I said came across as flirting. I admit I am an extrovert who truly likes people of both genders, and I express my gratitude. My gratitude may seem out of proportion to you <wry grin>, but I also choose to be deeply appreciative rather than take things for granted.

My problems stemmed from a Java class I was taking at the time with no Java experience behind me--none, nada, zip, zilch, zero. In addition, I have no other programming experience. Only one other class prepared me at all for the world of programming and it was Fundamentals of Programming with Algorithms and Logic. That said, I was grappling with an enormous handicap in even understanding the advice or help I was getting on here. I chose to handle it with humor, as I try to handle most challenges or hardships.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3648
    
  15
I was only teasing. Hence the
Guess the British sense of humour got lost in translation.
[ November 19, 2008: Message edited by: Joanne Neal ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
Originally posted by Joanne Neal:
I just read that old post and it seems the main reason you don't rememeber much about the actual problem was that the two of you spent most of the time flirting with each other

Once Campbell had worked out Robin was a girl that is (although it should have been fairly obvious from the disclaimer in her signature).


She didn't have that sig then, not as far as I can remember. No more than you had the handle. We were discussing whether to award you the handle and the consensus was that anybody who could be creatively rude to Campbell well deserved the "Rancher" handle.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
Yes, Robin, I remember your complaints about the class at the time. And thank you for that useful bit of information about the book.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Originally posted by Joanne Neal:
I was only teasing. Hence the
Guess the British sense of humour got lost in translation.

[ November 19, 2008: Message edited by: Joanne Neal ]


Sorry, Joanne! I usually wouldn't have gone into that 'explanation' but for the fact that Campbell is extraordinarily easy to embarrass. <drum roll> I live in fear that Campbell will one day feel so embarrassed he'll ignore me completely and leave me bereft! <falls out of her chair laughing>
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
Let's get this thread back to where it belongs, and remind C Bick that there was some problem with Scanner in Robin's book.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Yes, let's! I went to Sun's website and found the API for the most current version of Java. The following link will take C Bick to the API: http://java.sun.com/javase/6/docs/api/

By checking the API, C Bick can identify the discrepancy without anymore mindless rambling on my part. <wry grin>

C Bick, if you are a little disconcerted by the API (I know I was!), look in the upper left frame and scroll down until you locate the link for java.util. Click that. Then, in the frame immediately underneath the one you just clicked in, locate the link for Scanner and click that. This will bring up the section of the API that deals with the Scanner method and all related commands.
[ November 19, 2008: Message edited by: Robin Lane ]
C Bick
Greenhorn

Joined: Nov 18, 2008
Posts: 7
Well, I am glad that my post sparked so much debate, and I really appreciate the comments and pointers. I will be checking them out and will let you all know what I am able to find.

Thanks again!
C Bick
Greenhorn

Joined: Nov 18, 2008
Posts: 7
Thanks for the help guys! I got that part working using a do...while loop instead of just a while loop. I had tried that before, but was missing the if...exit statement for when the sentinel was entered. Now I get to try to figure out the input validations. I promise I will try first without looking at Robin's post for that subject. I really do want to learn this stuff, and am very glad that there is a group of people out here willing to help.

Thanks Again!
C Bick
Greenhorn

Joined: Nov 18, 2008
Posts: 7
You guys rock! I was able to figure out the input verification on my own, and my program is complete. Thanks a million for the tips and pointers, I am sure I will be back, but Campbell, I promise to post a new thread next time if I can't find one addressing my question already.

Peace!
Martijn Verburg
author
Bartender

Joined: Jun 24, 2003
Posts: 3274
    
    5

Originally posted by Joanne Neal:
I was only teasing. Hence the
Guess the British sense of humour got lost in translation.
[ November 19, 2008: Message edited by: Joanne Neal ]


Heh, I'm currently in the UK and I just struggle with most of the accents! My delusions that everyone walked around speaking the plum tones of the BBC was quickly shattered


Cheers, Martijn - Blog,
Twitter, PCGen, Ikasan, My The Well-Grounded Java Developer book!,
My start-up.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
The only place you will hear the "plum tones of the BBC" is in Holland
You need to get out of London to hear some good accents; round here they have a particularly incomprehensible version, but go 45 miles (70km) north to Newcastle and the speak a completely different language usually called Geordie.

And there is only one person on the Ranch allowed to tease me like that . . . Joanne Neal
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3648
    
  15
Originally posted by Campbell Ritchie:
round here they have a particularly incomprehensible version, but go 45 miles (70km) north to Newcastle and the speak a completely different language usually called Geordie.

And there is only one person on the Ranch allowed to tease me like that . . . Joanne Neal


I'm sorry, I didn't realise you were from up north. My teasing must have just added to your misery
Martijn Verburg
author
Bartender

Joined: Jun 24, 2003
Posts: 3274
    
    5

Originally posted by Campbell Ritchie:
The only place you will hear the "plum tones of the BBC" is in Holland


Ironically I'm Dutch born at that's how I was taught to speak English, as in "How now Brown Cow", but this thread has been derailed enough
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
Originally posted by Joanne Neal:


I'm sorry, I didn't realise you were from up north. My teasing must have just added to your misery


I didn't realise you were in the south; you must feel driven to tease to relieve the agony
[ November 21, 2008: Message edited by: Campbell Ritchie ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
At risk of having to send myself to MD, I am actually officially a Cockney, but have lived in Civilisation (ie north of Watford) for most of my life. Have been here in the north for a bit over 20 years, before that we lived at Leicester for 9 years.

And you Joanne, can tease me as much as you like.
Robin Lane
Ranch Hand

Joined: Apr 30, 2008
Posts: 76
Originally posted by Campbell Ritchie:
And you Joanne, can tease me as much as you like.


I'm wounded. <mock death scene ensues>

End of derailment!
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39408
    
  28
Originally posted by Robin Lane:


I'm wounded. <mock death scene ensues>

End of derailment!


I know what happens if you tease me! Or is it flirt?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Sentinel-controlled loop with a String variable condition