aspose file tools*
The moose likes Beginning Java and the fly likes For or While Statement? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "For or While Statement?" Watch "For or While Statement?" New topic
Author

For or While Statement?

Avery Jerauld
Greenhorn

Joined: Aug 15, 2011
Posts: 28

Ugh, I'm having more troubles. Does it usually take this long to click, is it my teacher, or me that is getting in the way of me being able to do this?

Anyway, I need to make my own For or While Statement to show the numbers 1 through 10 being squared. I'm completely at a loss because the For and While Statements were not very well described to me. I know how a for and a while statement work, but I can't set it up in this code. All my teacher did was give me:



and then explained that the first part of the for statement is a statement, followed by condition, followed by the second statement, and then what to do is right under it. But the probably is I don't know how to set it up. I understand cntr = 0 and cntr is lesser than or equal to 10, but what's this cntr++ as a second statement? And what's total+=cntr mean? I need to know this so I can replace what I need to make sure that I square these numbers and not just add. Because obviously formulas don't go here. NetBeans says that variables go here but that doesn't help me know how to change what it's doing!

Thanks all!
Rameshwar Soni
Ranch Hand

Joined: Feb 03, 2011
Posts: 247
Avery Jerauld wrote:
for (cntr =0; cntr <=10; cntr++)
total+=cntr;
but what's this cntr++ as a second statement? And what's total+=cntr mean?
Thanks all!


cntr++ is nothing but incrementing the variable cntr i.e. cntr++ is equivalent to cntr=cntr+1
and as far as total+=cntr is concerned it is equal to total=total+cntr;
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10929
    
  12

Generally speaking...

If you know exactly how many iterations your loop needs, you would use a for-loop. If you don't know, you'd use a while-loop.

This is not an iron-clad rule, but more of a guideline or convention. There is no for-loop you can't write as a while loop, and no while-loop you can't write as a for loop, but people might look at you strange if you use the non-conventional one.

A for-loop has several components, but basically, they all look like this:


Note that the braces are only REQUIRED if you have more than one statement in your body, I would STRONGLY recommend you ALWAYS use them. You will save yourself MANY MANY MANY headaches if you do.

So..the three pieces inside the parens - each is optional. You must always have both semi-colons, but the parts can be empty.

Initialization: Here you can define and initialize a variable (or several variables). This variable is often used as a counter to control how many times the loop is executed, and additionally used inside the body. The initialization step is only run once, no matter how many times the loop runs.

Test condition: Just before each iteration of the loop starts, we run this test. If it is TRUE, the loop runs. If FALSE, the loop ends. It is possible the loop will run zero times. Note that if a variable used in the test condition doesn't change anywhere in the body (or the operation - see below), the loop can run forever.

Operation: After the body of the loop runs, this code is executed. Usually, a counter is incremented, but that is not required. you could call a method, or even do nothing. After this code runs, we would go back to the Test condition to see if we should execute the body again.

Your code looks more or less like this (I put in curly braces):



so, we initially set cntr to 0. we enter the loop. we add the value of cntr to total.
Since we have finished the loop body, we execute the cntr++, which adds 1 to the value of cntr, making it 1.
1 is <= 10, so we loop again.
we add the value of cntr to total, so we add 1 to 0, giving us total = 1.

Since we have finished the loop body, we execute the cntr++, which adds 1 to the value of cntr, making it 2.
2 is <= 10, so we loop again.
we add the value of cntr to total, so we add 2 to 1, giving us total = 3.

Since we have finished the loop body, we execute the cntr++, which adds 1 to the value of cntr, making it 3.
3 is <= 10, so we loop again.
we add the value of cntr to total, so we add 3 to 3, giving us total = 6.

we would then hit the System.out.println, and get "The Total is 55"


...and so on.

Eventually, cntr will be 10. We'll add 10 to total, giving total = 55 (i think).
Since we have finished the loop body, we execute the cntr++, which adds 1 to the value of cntr, making it 11.
11 is NOT <= 10, so we exit the loop.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36598
    
  16
fred rosenberger wrote: . . . Test condition: Just before each iteration of the loop starts, we run this test. If it is TRUE, the loop runs. If FALSE, the loop ends. . . .
But what is you miss out the test condition? The JVM will not see "false" anywhere and the loop will run forever. There is an example in the Java Tutorials. There is also discussion about the difference between the ordinary for loop and the enhanced for loop (which many people call for-each), here.

But that was a good post of Fred's
Avery Jerauld
Greenhorn

Joined: Aug 15, 2011
Posts: 28

Yes, thank you Fred! That did help. I still need to figure out some stuff to get it working in this code I'm on since I have to use more than one For statement and I don't now how I can make it detect an inputted word and do a process.

But, I do like how you started it with "Generally speaking". XD



Edit:

I can't figure out how I can do this while keeping the same format of what I was given.









All of that has to stay the same except for:





That's the only thing I can change around. I could change it to a While Statement if I wanted but that makes less sense to me. I just have to use a For or a While statement to put there. I know I can't use "Excellent", "Good", and "Poor" right there because that has to be entered in when prompted to. What can I do in exchange for this?
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10929
    
  12

ok...you have three loops there, that are completely un-related - by which I mean they aren't nested (one inside another). therefore, we can look at them one at a time. And since they all look pretty much the same, we'll just look at one...

Again, I want to emphasize you should really write it like this:

although the specific bracket placement can be in the style you prefer.
When we encounter this, we set raise to 0. we check to see if rating is "Excellent" (assuming we fix this part - it won't work quite like this). Let's assume that is true. So we set raise to 6.
There is no code in the third part of the loop (i.e. the part where you normally increment something), so we go back to our test condition. Since rating didn't change, it will still be equal to "Excellent", so we enter the body of the loop. We set raise to 6.
There is no code in the third part of the loop (i.e. the part where you normally increment something), so we go back to our test condition. Since rating didn't change, it will still be equal to "Excellent", so we enter the body of the loop. We set raise to 6.
There is no code in the third part of the loop (i.e. the part where you normally increment something), so we go back to our test condition. Since rating didn't change, it will still be equal to "Excellent", so we enter the body of the loop. We set raise to 6.
There is no code in the third part of the loop (i.e. the part where you normally increment something), so we go back to our test condition. Since rating didn't change, it will still be equal to "Excellent", so we enter the body of the loop. We set raise to 6.
There is no code in the third part of the loop (i.e. the part where you normally increment something), so we go back to our test condition. Since rating didn't change, it will still be equal to "Excellent", so we enter the body of the loop. We set raise to 6. There is no code in the third part of the loop...

Do you see a problem here?

The BEST way to approach this would be to write down, in english, exactly what you want to do. Don't say "I need to write a for-loop that...". But say "I need to check and see what input the user gave me, and then do something depending on what that is".

then you go back and refine that to something like

if the user gave me "Excellent", I need to set the raise to 6.
otherwise, if they gave me "Good", I need to...blah blah blah.

you keep going back and refining each step, getting more and more specific. Eventually, you get to the point where the java is obvious. To me, I can't see why you'd need a for loop at all...
Avery Jerauld
Greenhorn

Joined: Aug 15, 2011
Posts: 28

fred rosenberger wrote:
When we encounter this, we set raise to 0. we check to see if rating is "Excellent" (assuming we fix this part - it won't work quite like this). Let's assume that is true. So we set raise to 6.
There is no code in the third part of the loop (i.e. the part where you normally increment something), so we go back to our test condition. Since rating didn't change, it will still be equal to "Excellent", so we enter the body of the loop. We set raise to 6.


Ooooh. So for one, I should switch around those two that I have so the initial statement is rating=Excellent and that raise=0. Which would mean I'd need to add a third one. Or maybe since it will change raise to 6 after the first time it won't loop again so I have no need for the third part there?



fred rosenberger wrote:To me, I can't see why you'd need a for loop at all...


I know. I agree. I thought the same thing when I first heard the problem. I could easily do it another way. Or, you know, use a calculator since I'm having to enter in the salaries anyway. But whatever. The online teacher gets paid whether I pass or fail...
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10929
    
  12

Can you post the exact text of your assignment? I just can't see how or why you would use a for-loop at all here. I don't see the need for a loop AT ALL...

If all you are allowed to change is the code between lines 15-20, I think all you'd need would be an if-else statement.

And for when you get there, the proper way to compare Strings is with the equals() method...


I am not sure you need this yet, but it is looming on the horizon.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36598
    
  16
There is a very subtle reason, explained here, which I first learned about on the Ranch, why it is slightly better to write
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36598
    
  16
You can use a switch block, with case "Excellent": ... break; etc., but that format only works in Java7.
Avery Jerauld
Greenhorn

Joined: Aug 15, 2011
Posts: 28

I emailed my teacher about it and he said he made a typo. Oh my god.

Here's the assignment. Er, how it SHOULD be.

Lab 5 Project





Objective



Students will be able to Compute A Raise


Overview

The program below, Salary.java, inputs an employee's salary and a rating of the employee's performance and computes the raise for the employee. The three possible ratings are "Excellent", "Good", and "Poor". An employee who is rated excellent will receive a 6% raise, one rated good will receive a 4% raise, and one rated poor will receive a 1.5% raise.� Add the if... else... statements to program Salary to make it run as described above. Submit your code to the lab drop box

for this unit.







I've gotten it to this so far but for some reason it won't let me enter in the rating of Excellent, Good, or Poor. It tells me "Enter the performance rating (Excellent, Good, or Poor):" but then it just jumps straight to showing my the current salary I entered, a raise of 0.00, and the new salary (which is the same as the old one).

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Avery,

Please check in the docs http://download.oracle.com/javase/1,5.0/docs/api/java/util/Scanner.html for the difference between Scanner.nextLine() and Scanner.next() method. Can you change accordingly and try?
Avery Jerauld
Greenhorn

Joined: Aug 15, 2011
Posts: 28

That worked John. I just changed it to next instead of nextLine. Now the program works perfectly! Now I just have to go and finish the original problem with the for or while statement used to square all number up to 10. Ugh.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 10929
    
  12

we're happy to help with that one too, but please, if you do ask questions, start a new thread.

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: For or While Statement?
 
Similar Threads
loop problems
For or While Statement Part 2
Counting a Int
sum up numbers
trying to find union/intersection of arrays containing integers