简体   繁体   English

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

[英]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); } } 
so everything works but I realized that I do not want a neg number if a negative number is entered I want the output POSITIVE NUMBERS ONLY so would I need another while loop? 所以一切正常,但我意识到如果输入一个负数,我不想要一个负数我只想输出正数,那么我需要另一个while循环吗?

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM