There seems to be something with my code. My code detects non-integers and keep asking the user to input a positive #, but when you insert a negative #, it just ask the user to input a positive just once. What is wrong? Something with my do-while loop for sure. I'm just focusing on the firstN, then I could do the secondN.
import java.util.Scanner;
public class scratch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int firstN = 0;
int secondN = 0;
boolean isNumber = false;
boolean isNumPos = false;
System.out.print("Enter a positive integer: ");
do {
if (input.hasNextInt()) {
firstN = input.nextInt();
isNumber = true;
}
if (firstN > 0) {
isNumPos = true;
isNumber = true;
break;
} else {
isNumPos = false;
isNumber = false;
System.out.print("Please enter a positive integer: ");
input.next();
continue;
}
} while (!(isNumber) || !(isNumPos));
System.out.print("Enter another positive integer: ");
do {
if (input.hasNextInt()) {
secondN = input.nextInt();
isNumber = true;
}
if (secondN > 0) {
isNumPos = true;
isNumber = true;
} else {
isNumPos = false;
isNumber = false;
System.out.print("Please enter a positive integer: ");
input.next();
}
} while (!(isNumber) || !(isNumPos));
System.out.println("The GCD of " + firstN + " and " + secondN + " is " + gCd(firstN, secondN));
}
public static int gCd(int firstN, int secondN) {
if (secondN == 0) {
return firstN;
} else
return gCd(secondN, firstN % secondN);
}
}
Aucun commentaire:
Enregistrer un commentaire