Smas - 9 months ago 58

Java Question

This is my first course in java. when I am writing this code it is just stop when it prints the gcd. I want the code to start again from the beginning and continue. Since I didn't take any complicated codes in the course, as I am not allowed to. The program is about a loop that subtract the smaller integer from the larger one and Continue looping until one of the integers becomes zero, so that it prints out the non-zero integer.

import java.util.Scanner;

public class JavaApplication8 {

`public static void main(String[] args) {`

Scanner in = new Scanner(System.in);

System.out.println("Enter the first integer: ");

while (in.hasNextInt() || in.hasNext()) {

while (in.hasNextInt() || in.hasNext()) {

int x = in.nextInt();

System.out.println("x = " + x);

System.out.println("Enter the second integer: ");

int y = in.nextInt();

System.out.println("y = " + y);

while (x != 0) {

while (x >= y) {

int a = Math.max(x, y);

int b = Math.min(x, y);

a = a - b;

x = a;

y = b;

}

while (x < y) {

int a = Math.min(x, y);

int b = Math.max(x, y);

b = b - a;

x = a;

y = b;

}

System.out.println("The gcd =" + y);

}

}

}

}

}

Answer Source

The problem with your code is you are using while loop incorrectly. Make sure to make effective use of if statements as well as classes (If you know how to use them).

```
Scanner in = new Scanner(System.in);
System.out.println("Enter the first integer: ");
int x = in.nextInt();
System.out.println("x = " + x);
System.out.println("Enter the second integer: ");
int y = in.nextInt();
System.out.println("y = " + y);
while (x != 0) {
if (x >= y) {
int a = Math.max(x, y);
int b = Math.min(x, y);
a = a - b;
x = a;
y = b;
}else if (x<y){
int a = Math.min(x, y);
int b = Math.max(x, y);
b = b - a;
x = a;
y = b;
}
}
System.out.println("The gcd =" + y);
}
}
```

Try this (should work fine).