For Loop Doesn't Work Right - java

Why doesn't this for loop count the right number of times? If I set the variable runs to 3, the loops runs 4 times. (One extra case.)
Thanks in advance!
for (int i = runs; i >= 0; i--)
{
System.out.println("Input Duration of Trip");
Scanner timeCalc = new Scanner(System.in);
System.out.print("Hours ==> ");
int hour = timeCalc.nextInt();
System.out.print("Minutes ==> ");
int minute = timeCalc.nextInt();
System.out.println("You entered: " + hour + " hour(s) and " + minute + " minutes");
System.out.println();
time = convertHoursMinutesToDouble(hour, minute);
totalTime += time;
}

The loop runs for values:
3
2
1
0
That's 4 times.
If you want it to run for values 3, 2 and 1, you can change your for loop to:
for (int i = runs; i > 0; i--)
or
for (int i = runs; i >= 1; i--)

Your mistake is in
i>=0
What the code is doing is going "Ok, i is going to be equal to three. Now, let's see, ok, back up again, subtract one, i =2... subtract one i=1... Now tricky tricky it SKIPS the termination part of the code because it looks at it first BEFORE substracting one so i=0, ok WAIT i=0 so STOP."
Solution?
for (int i = runs; **i >= 1**; i--)
This mistake always messes me up.
Hope the whole "through the mind of the computer thing" doesn't bother you. That's how I tend to think.
Happy coding!

i == 3
i >= 0
println
i--
i == 2
i >= 0
println
i--
i == 1
i >= 0
println
i--
i == 0
i >= 0
println
That was 4 times. You need your condition to be: i > 0

Because you have set greater than or equal to...
So starts at 3 and goes, 2,1,0.

Related

what does x % 2 > 0 mean in java?

I'm currently learning java in my online classes and I'm learning about loops (specifically continue and break statements). The example given to me was:
int j = 0
while (true){
System.out.println();
j++;
System.out.print(j);
if (j%2 > 0) continue
System.out.print(" is divisible by 2");
if (j >= 10) break;
}
I don't understand why its (j%2 > 0) and not (j%2 == 0) because what if 'j' is 5 for example and you do 5%2. Wouldnt the number you get be 1? Or am I missing something? Can someone please explain this to me?
(sorry is I'm not my question is a little confusing. I've never used this site before and I'm pretty young)
Let me explain to you. See the comments next to each line.
int j = 0
while (true){
System.out.println();
j++; //increases the value of j on the next line by 1.
System.out.print(j); //prints 1, the first time because of above, 0 + 1.
if (j%2 > 0) continue //using modulus operator(%) we are doing 1 % 2, answer is 1
//since 1 % 2(if 1 is divisible by 2) > 0 we are
//continue statement breaks the iteration in the
//loop, so anything below this line won't be
//executed.
System.out.print(" is divisible by 2");//this line will only be executed
//if j is divisible by 2. that is
//j is divisible by 2 (j%2 == 0)
if (j >= 10) break; //when j is equal or greater than
//0 we are stopping the while loop.
}
Continue means "go to the top of the loop, skipping the rest of the loop's code" not "continue with the code". So since 5%2 is 1, and 1 > 0, the continue will execute, going directly to the top of the loop and skipping the rest of the body.
Why do they use > 0 instead of != 0? There isn't any technical reason, its a style difference. I personally would have used the latter as its more clear in my mind. But either works.
int j = 0;
while (true){
System.out.println();
j++;
System.out.print(j);
// in this case you won't print any message and you
// are sure that the next number is even (j will be incremented by "continue;").
if (j%2 > 0) continue;
System.out.print(" is divisible by 2");
if (j >= 10) break;
}
X % 2 means the remainder when is x is divided by 2. So if the remainder of x/2 is more than 0, it means that x is an odd number. When x%2 == 0, then x is a positive number

Why wont console print values of i under 2 in FOR loop if it can print values over 2?

Basically what my title says. Here's a piece of code
for (int i = 9; i >= 2; i--) {
system.out.println(i + " ");
}
this prints all values until 2, hence suggesting that starting from 9 and provided it doesn't go lower than 2, i should be printed. which it does.
now this one doesn't
for (int i = 9; i <= 2; i--) {
system.out.println(i + " ");
}
what i figure is it should count down to 2 without printing anything, then print 2 and 1, since the criteria is for all values equal or under 2, print i. However nothing shows on the console.
my understanding of the FOR loop might be wrong and i'm really trying to perfect my knowledge of basic concepts so id appreciate your help.
The basic concept is :
first loop => i=9, check if 9 >=2 = true , print 9 , i = i - 1
second loop => i=8, check if 8 >=2 = true , print 8 , i = i - 1
.
.
.
last loop=> i=1, check if 1 >=2 = false , end
in your second example
first loop => i=9, check if 9 <=2 = false , end
Hope i help you understand the for loop
Loop is only executed if the condition is true. If it is false, then loop will never be executed.
If you wanted to count down from 9 and only print 2 and 1, you'd have to write something like this:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
}
}
Of course, if all you wanted was to print 2 and 1, you'd normally just write:
for (int i = 2; i >= 2; --i) {
System.out.print(i + " ");
}
You wouldn't typically start the count at 9 unless you wanted to do something with the numbers 9 to 3 (other than ignore them, that is) as well as 2 and 1:
for (int i = 9; i >= 1; --i) {
if (i <= 2) {
System.out.print(i + " ");
} else {
System.out.println("We're not going to print " + i);
}
}

Make range with only first and last number? Java?

I have to get input for a certain number of days and a starting number. With that, the number of days gets split in half, in first half starting number decremented by 2. Last half incremented by 1. If days is uneven, last half has one more day. Heres what I have:
int days;
int num;
int 1half;
int 2half;
int new_num;
System.out.print("Enter number of days: ");
days = keyboard.nextInt();
System.out.print("Enter number of first day: ");
num = keyboard.nextInt();
int half = days/2;
if (days %2 == 0){
1half = (half);
2half = (half);
} else {
1half = (half);
2half = (half) + 1;
}
int first_half[] = {1,(half)};
int last_half[] = {((half)+1), days};
while (1half > 1 || 1half < half) {
new_temp = temp - 2;
System.out.println("Day \t Num");
System.out.println(new_num);
first_half--;
}
while(2half >= (half + 1) && (2half <= days)) {
new_temp = temp++;
System.out.println("Day \t Num");
System.out.println(new_num);
last_half--;
}
Im stuck now though.
If you see anything Id be happy to hear about it. I just need some help/advice. I'll clarify anything if this is hard to understand. Thank you in advance
Edit:
The final output should look something like this:
Day Num
1 -10
2 -12
3 -14
4 -16
5 -18
6 -17
7 -16
8 -15
9 -14
10 -13
11 -12
If this makes sense.
Heres my output:
Day Temperature
8
Day Temperature
8
Day Temperature
8
Day Temperature
continues forever
I don't know why do you need those arrays and other stuff, but you may have a look at my code. It produces exactly what you want.
int days = 11;
int num = -10;
int output = num + 2;
System.out.println("Day \t Num");
int half = days / 2;
for (int i = 1; i <= half; i++) {
output -= 2;
System.out.println(i + "\t" + output);
}
for (int i = half + 1; i <= days; i++) {
output++;
System.out.println(i + "\t" + output);
}
Your endless loop is caused by your condition statement of your while:
while (1half > 1 || 1half < half).
If 1half is set to be any number greater than 1 then this will loop forever. You probably want to use an && instead of an || as well. But don't see anything in the body of the loop that would affect things to make it get out of the loop.

Why does this while loop run after the condition is met?

When I do a regular while loop like this
int x = 0;
while (x < 2) {
System.out.println(x);
x = x + 1;
}
it prints
0
1
but this second while loop runs one more time after the condition is met.
class Hobbits {
String name;
public static void main(String [] args) {
Hobbits [] which = new Hobbits[3];
int number = -1;
while (number < 2) {
number = number + 1;
which[number] = new Hobbits();
which[number].name = "bilbo";
if (number == 1) {
which[number].name = "frodo";
}
if (number == 2) {
which[number].name = "sam";
}
System.out.print(which[number].name + " is a ");
System.out.println("good Hobbit name");
}
}
}
so the result is
bilbo is a good Hobbit name
frodo is a good Hobbit name
sam is a good Hobbit name
shouldn't it stop printing at "frodo is a good Hobbit name"
I set the condition for x < 2 so how does "sam" print if the while loop was supposed to stop at x == 1?
Edit: ohhh I get it now lol I was thinking like the increment was at the end of the code and the start was 0
Here's your test case more closely matching your code:
class Test {
public static void main(String[] args) {
int x = -1;
while (x < 2) {
x = x + 1;
System.out.println(x);
}
}
}
It does indeed print:
$ java Test
0
1
2
Your loop is not designed to stop when number is 2, it's designed to stop before the next iteration if the number is 2. Since you increment number early on in the loop, it will continue with that value until it's time to choose whether to iterate again.
Before the first iteration, number = -1 which is <2 so it should iterate.
Before the second iteration, number = 0, which is <2 so iterate.
Before the third iteration, number = 1, which is <2 so iterate.
Before the fourh iteration, number = 2, which is NOT <2 so stop.
You therefore get 3 iterations.
Your original test case had the right idea -- it's better to increment as the last step in the loop. That way, you start at 0 instead of -1, and you stop the loop based on the new value rather than the previous value.
I will try to trace through it for you.
First case this is what happens.
x = 0
is 0 < 2? yes
print 0
0 <- 0 + 1 // here it becomes 1
is 1 < 2? yes
print 1
1 <- 1 + 1 // here it becomes 2
is 2 < 2? no
exit program
second loop works a bit more like this
number = -1
is number < 2? yes
number <- -1 + 1 // here it becomes 0
make hobbit "bilbo" at index 0
0 does not equal either 1 or 2
print hobbit at index 0 who is "bilbo"
is 0 < 2? yes
0 <- 0 + 1 // here it becomes 1
number equals 1 so make "frodo" at index 1
print hobbit at index 1 who is "frodo"
is 1 < 2? yes
1 <- 1 + 1 // becomes 2
number equals 2 so make "sam" at index 2
print hobbit at index 2 who is "sam"
is 2 < 2? no
end program
There's nothing wrong in that behaviour. You set number = -1 and then you do a loop that will iterate while number < 2. So, -1, 0 and 1. Three iterations. What's the problem? Let's do a simple trace:
number = -1
(-1 < 2)? Yes. Execute code inside while.
number = number + 1 (0)
(0 < 2)? Yes. Execute code inside while.
number = number + 1 (1)
(1 < 2)? Yes. Execute code inside while.
number = number + 1 (2)
(2 < 2)? No. Continue with the next instruction after the while block.
you can solve this easily with replace
int number = -1;
to
int number = 0;
Because! -1 + 1 = 0;
Because you have 3 iterations that are true:
-1 < 2 == true
0 < 2 == true
1 < 2 == true
2 < 2 == false
Cheers

How do you subtract a value from a counter in Java?

Say that length=11 and that I want to subtract 2 from it on every cycle until it reaches 1. Is my code for the for method correct? And what would it be for a while loop?
for(int i =length ; i!=1; i-=2)
EDIT: This was the question. To solve it I made an if statement that if the length%2==1 I would use the for loop listed above. Then I am going to write an else stating modifying the code above to stop at 0. Does this make sense?
The sum of all digits at odd positions (right-to-left starting at 1 as the right-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 7 + 6 + 3 = 16.)
For is not a method. It's a language construct. Just a nitpick.
Almost. If i starts out even you'll never end. Use:
for(int i =length ; i>1; i-=2)
If the 1 is inclusive, you could try:
for(int i = length; i >= 1; i -= 2){ ... }
Or
for(int i = length; i > 0; i -= 2){ ... }
If the 1 is exclusive, you could try:
for(int i = length; i > 1; i -= 2){ ... }

Categories

Resources