我怎样才能得到这个输出?

时间:2015-02-17 22:45:03

标签: java

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);

	}

}
所以一切正常但我意识到如果输入一个负数,我不想要一个负数我只想输出正数,那么我需要另一个while循环吗?

1 个答案:

答案 0 :(得分:0)

只需添加一个if语句,检查n1和n2是否为正数,如果是,则只执行其余的代码。你不应该需要另一个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);
        }
    }