[英]How would I get this output?
import java.util.Scanner; public class EuclidGCD { public static void main(String[] args) { Scanner kbd = new Scanner (System.in); System.out.print ("Enter First Number: "); int n1 = kbd.nextInt(); System.out.print ("Enter Second Number: "); int n2 = kbd.nextInt(); int gcd = 1; int k = 2; while (k <= n1 && k <= n2){ if (n1 % k == 0 && n2 % k == 0) gcd = k ; k ++; } System.out.println("The GCD of " + n1 + " and " + n2 + " is " + gcd); } }
Just add a if statement checking if n1 and n2 are positive, and only excuted the rest of your code if they are. 只需添加一个if语句,检查n1和n2是否为正数,如果是,则只执行其余的代码。 You shouldn't need another while loop
你不应该需要另一个while循环
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
System.out.print ("Enter First Number: ");
int n1 = kbd.nextInt();
System.out.print ("Enter Second Number: ");
int n2 = kbd.nextInt();
if(n1 < 0 || n2 < 0 ){
System.out.println("POSITIVE NUMBERS ONLY ");
}else{
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2){
if (n1 % k == 0 && n2 % k == 0)
gcd = k ;
k ++;
}
System.out.println("The GCD of " + n1 + " and " + n2 + " is " + gcd);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.