My While loop doesn't end even when the condition is met - java

So as an assignment I am trying to build a Collatz Conjecture program. My program works as expected, but the only problem is that it doesn't end when it reaches 1. Instead, the code loops and the program seem to start from the beginning in its own loop. Below attached is my code. Any help is much appreciated. Thank You!
while (n!=1){
if ((n % 2) == 0) {
n/=2;
System.out.println(n);
}
if ((n % 2) > 0) {
n*=3;
n++;
System.out.println(n);
}
n = n;
}

You are running both conditions in each iteration, so even if the first condition updates n to 1, the following condition immediately changes its value to becomes larger than 1 again.
You should only run the second condition's body if the first condition is false, which means you can transform the second condition to an else clause:
if ((n % 2) == 0) {
n/=2;
System.out.println(n);
} else {
n*=3;
n++;
System.out.println(n);
}
Example:
Suppose n==2 - the first condition is true, and it modifies n from 2 to 1. Now, in the same iteration, the second condition becomes true, and n is multiplied by 3 and incremented by 1, so the loop doesn't end.

You should do it like this,the problem occurs because you updated your n in every condition and loop continue to run and that is why your program is not running.
int m=0;
while (n!=1){
if ((n % 2) == 0) {
m=n/2;
System.out.println(m);
}
if ((n % 2) > 0) {
m=n*3;
m++;
System.out.println(m);
}
n = m;
}

Related

How to find this checksum using Java

To find this particular checksum, we need to sum the digits of the input and multiply by 2. Simple enough by finding the remainder using a loop.
If the result is less than 10, that is the number's checksum. If it is 10 or higher, we need to do it again until the result is less than 10.
If it gets caught in an infinite loop, such as with the input of 18, return -1.
This is what I have so far:
public int getChecksum(int input, int previous) {
int sum = 0;
while (input > 0) {
sum += input % 10;
input /= 10;
}
if (sum * 2 < 10) {
return sum * 2;
} else if (sum * 2 >= 10 && previous != sum) {
previous = sum;
return getChecksum(sum * 2, previous);
} else if (previous == sum) {
return -1;
}
return sum * 2;
}
I really wanted to know if there was a way to do this without doing it recursively as I am doing here.
A rather simple recursive algorithm like this can also be implemented iteratively. Usually you would go about this turning the recursive call into a loop with the recursive termination condition as the loop termination condition.

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

An issue in using while loop with multiple conditions

I have the following Java while loop:
boolean finish = false;
int ii = 0;
int counter = 0;
while((!finish) || (counter <= 10)) {
ii++;
if(ii<30) {
System.out.println(ii + " -- " + counter);
}else {
finish=true;
}
counter++;
}
I want the loop to add one to ii until it reaches 30 or the counter reaches 10. Running this code ignores the condition of counter and continues until ii reaches 30. I expect it to stop when counter reaches 10.
How can I fix that?
It should be &&, not ||, since you want the loop to loop as long as both ii<30 AND counter<=10.
change while((!finish) || (counter <= 10))
to
while((!finish) && (counter <= 10))
and it will work as you expect.

Java For Loop Confusion (iteration) "Don't know why it still went through!" [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 5 years ago.
So I was trying to figure out if the the first iteration in a for loop does not go through the termination condition.
Since when I called it in the main method with an input of 4 IsPrime(4) the for loop still went through. I was expecting it to not go through since i = 2 and n/2 = 4/2 = 2 which will be 2 == 2 which will meet the condition to terminate but it went through and I got the right output but I don't get why it did not fail.
Please help.
public static boolean isPrime(int n){
if(n <= 1){
return false;
}
for(int i = 2; i <= n/2; i++){
if(n % i == 0){
return false;
}
}
return true;
}
Your for loop condition says continue while i <= n/2.
If you start with n == 4 then n/2 == 2. On the first iteration i == 2 so the for loop condition 2 <= 2 is true and it will iterate once.
Then i++ is executed so now i == 3 and fails the condition so there is no second iteration.
You seem to have a confusion around how for loop works. Let's see the operation on a per-iteration basis :
Iteration 1 :
i = 2
i <= 2 ? --> True
n % i == 0 ? --> 2 % 2 == 0? True
return false
End of function
Now let's assume your for loop looked something like this :
for(int i = 2; i <= n/2; i++){
if(n % i == 0){
System.out.println("Remainder is 0");
}
}
Then the following will the iteration sequence :
Iteration 1
i = 2
i <= 2 ? --> True
n % i == 0 ? --> 2 % 2 == 0? True
print --> Remainder is 0
i++ --> i = 3 now
Iteration 2
i = 3
i <= 3 ? --> False
Cannot proceed further. For loop condition failed.
End of function

Supposed variable cannot be resolved as variable?

I'm doing a basic Java tutorial and below is the question.
Write a method that prints the numbers from 1 to 100. But for multiples of three print ÒFizzÓ instead of the number,and for the multiples of five print ÒBuzzÓ. For numbers which are multiples of both three and five print ÒFizzBuzzÓ."
My code is below
public static void fizzBuzz(){
for(int i = 0; i < 101; i= i +1 )
System.out.println(i);
if (i%3 == 0){
System.out.println("ÒFizzÓ");
}else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}else if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
}
}
Eclipse tells me that "i" cannot be resolved as a variable. This is confusing to me as I thought I already defined "i" as an integer in my for loop? Thanks for taking the time to solve this newbie question :)
Add braces or your loop body ends after the first statement. Also, for your approach you need to test 15 first because it's a multiple of 3 and 5
for(int i = 0; i < 101; i++) { // <-- i++ is short for i = i + 1
System.out.println(i);
if (i % 15 == 0) {
System.out.println("ÒFizzBuzzÓ");
} else if (i % 5 == 0) {
System.out.println("ÒBuzzÓ");
} else if (i % 3 == 0) {
System.out.println("ÒFizzÓ");
}
}
I know a funny story about Apple who lost a few million dollars because a developer updated a code with an if block but... the if statement had only one instruction and no curly brackets and he did not see it. Thus, the code he was willing to add when the condition was met were actually ALWAYS executed.
In your case, you won't lose money but you surely did the same mistake :
for(int i = 0; i < 101; i= i +1 ) {
System.out.println(i);
if (i % 15 == 0){
System.out.println("ÒFizzBuzzÓ");
} else if (i%3 == 0){
System.out.println("ÒFizzÓ");
} else if (i % 5 == 0){
System.out.println("ÒBuzzÓ");
}
}
When Java says something cannot be resolved as a variable, it is usually been used outside the scope it was declared or it was not declared at all.In your case, your braceless for-loop is causing the problem.

Categories

Resources