簡體   English   中英

僅檢查正整數。 沒有負整數,沒有非數字字符串

[英]check for positive integers only. no negative integer, no non-numeric strings

我必須編寫一個Java程序來計算兩個正整數的最大公約數。 程序只需要檢查正整數。 我的問題是,當我輸入一個負整數然后輸入一個非數字字符串時,我的程序停止運行。 貝婁是我的代碼:

import java.util.Scanner;
class GCD {
    public static void main (String[] args){
        Scanner sc = new Scanner(System.in);
        int a, b, m, n, remainder;
        System.out.print("Enter a positive integer: ");
        while (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
        }
        a = sc.nextInt();
        while (a <= 0){
            System.out.print("Please enter a positive integer: ");
            a = sc.nextInt();
        }


        System.out.print("Enter another positive integer: ");
        while (!sc.hasNextInt()){
            System.out.print("Please enter a positive integer: ");
            sc.next();
        }
        b = sc.nextInt();
        while (b <=0){
            System.out.print("Please enter a positive integer: ");
            b = sc.nextInt();
        }

        m = a;
        n = b;
        while (n != 0){
            remainder = m%n;
            m = n;
            n = remainder;
        }
        System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
    }
}

嘗試這個:

import java.util.Scanner;
public class A {
    public static void main (String[] args){
        int a, b, m, n, remainder;
        a = validInput();
        b = validInput();
        m = a;
        n = b;
        while (n != 0){
            remainder = m%n;
            m = n;
            n = remainder;
        }
        System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
    }

    static int validInput() {
        Scanner sc = new Scanner(System.in);
        while(true){
            System.out.print("Please enter a positive integer: ");
            String tmp = sc.next();
            if (tmp.matches("^\\d+$")) {
                return Integer.parseInt(tmp);
            }
        }
    }
}

我建議您使程序更具模塊化,因為您可以在這樣的簡單程序中看到它的好處。

/* prompt a */
String a = sc.next();

/* prompt b */
String b = sc.next();

if (isValid(a) && isValid(b)) {
    int ia = Integer.parseInt(a);
    int ia = Integer.parseInt(b);

    /* calculations and such */
}

boolean isValid(String num) {
    try {
        int i = Integer.parseInt(num);
        if (i < 0) {
            return false;
        }
    } catch (NumberFormatException e) {
        return false;
    }
    return true;
}

在您第一次調用next()時,但是在第二次您使用nextInt()。 如果您第一次輸入負整數,則使用nextInt()進入下一個。 因此,如果用戶輸入的字符串不是數字,則您將獲得異常,因為掃描程序無法獲取鍵或其他值。 一個更聰明的方法是捕獲異常並無限期地使用它,如下所示:

while(true)
   System.out.print("Please enter a positive Number: ");
   try{
      a = sc.nextInt();
      if(a>-1){
         break;
      }
   }catch(Exception ignore){
   }
}

該代碼將一直運行,直到用戶輸入一個正數。 如果他輸入的不是數字,則異常將出現並且將被忽略,而while將繼續,如果數字不是正數(在這種情況下大於-1),while將不會中斷。

即使我不嘗試,它也無法正常工作。 當您在編碼方面看起來很新時,我只有2條建議:-在編寫代碼時,請嘗試使用函數。 通常,您永遠不要復制/粘貼。 -嘗試在變量中加上全名,特別是如果您在論壇上共享代碼時,人們可以更輕松地了解您所做的事情,並為您提供幫助:)

     import java.util.regex.Pattern;
     import java.util.Scanner;
     class GCD {
        public static void main (String[] args){
          Scanner sc = new Scanner(System.in);
          int a, b, m, n, remainder;
          a=askInt();
          b=askInt();
          m = a;
          n = b;
          while (n != 0){
          remainder = m%n;
          m = n;
          n = remainder;
          }
          System.out.println("The GCD of " +a+ " and " +b+ " is " +m);
       }

     private int askInt(){
          System.out.print("Enter a positive integer: ");
          String tampon = sc.nextLine();
          while(!Pattern.matches("\p{Digit}",tampon)){
              System.out.print("Please enter a positive integer: ");
              String tampon = sc.nextLine();
          }
          return Integer.valueOf(tampon);
     }
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM