簡體   English   中英

Java異常處理-除以零並除以文本方法

[英]java exception handling - divide by zero and divide by text method

我已經從事Java 4個月了,所以我還是一個業余愛好者。 只是想完成一些任務。 似乎找不到正確的技巧來使我的分母通過拒絕文本數據和零而又保持與錯誤消息的循環來正常工作。 另一個問題是,無論我的分子/分母是多少,我的商都是0.0。 很多問題,任何建議都值得贊賞。 指示如下:

-該程序接受用戶輸入的(int)分子和(int)分母,然后計算並顯示(double)商。

-如果用戶輸入文本而不是分子的數字,則顯示一條錯誤消息以說明該問題,並使用戶處於循環狀態,直到輸入正確的數據為止。

-如果用戶輸入文本或分母而不是數字,則輸入零,則顯示一條錯誤消息以說明問題,並使用戶保持循環狀態,直到輸入正確的數據為止。

-有關問題的消息應具有描述性。

public static void main(String[] args) throws Exception {
    Scanner console = new Scanner(System.in);
    int n1 = 0; //number 1
    int n2 = 1; //number 2..
    double r = (double) n1 / n2; //quotient
    String n1Str = "Please enter a real number for the numerator";
    String n2Str = "Please enter a real number greater than zero for the denominator";
    String errMsg = "Please enter a real number.";
    String notZero = "Denominator cannot equal zero.";      // not all string msgs are used, just there in case i need them.

    try {
        n1 = getInteger(n1Str); // validates against alphabet
        if (hasNextInt()) {     // working
            n1 = console.nextInt();
        }
    } catch (InputMismatchException ime) {
    }

    try {
        n2 = getInteger2(n2Str); // trying to validate against alphabet & zero
        if (hasNextInt()) {     //  not working though... 
            n2 = console.nextInt();
        }
    } catch (InputMismatchException ime) {
    }
    System.out.println("Fraction result is " + r);
}   

public static int getInteger(String message) {
    Scanner console = new Scanner(System.in);
    int count = 0;
    boolean isValidInteger = false;
    do {
        System.out.println(message);
        if (console.hasNextInt()) {
            isValidInteger = true;
            count = console.nextInt();
        } else {
            console.nextLine();
        }
    } while (!isValidInteger);
    return count;
}

public static int getInteger2(String message) {
    Scanner console = new Scanner(System.in);
    int count = 0;
    boolean isValidInteger = false;

    do {
        System.out.println(message);
        if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but 
            isValidInteger = true;              // can't get it to validate against text.
            count = console.nextInt();  //tried switching statements and using && but get thrown into endless loop
        }
    } while (!isValidInteger);
    return count;
}

private static boolean hasNextInt() {
    return false;
}
}

商“ r”始終為0.0的事實是因為您將n1初始化為0且n2 = 1。 您應該只聲​​明變量,然后在代碼中將其初始化。 即,當您想從用戶那里獲取值時。

您的代碼有很多問題。

對於初學者,您應該只有一個Scanner ,它將在應用程序的整個生命周期中都存在。 無需實例化多個掃描儀。

public class SomeClass {

    private static Scanner console;

    public static void main(String[] args) throws Exception {

        console = new Scanner(System.in);

        (...)

        console.close();
    }
}

現在,讓我們看一下有問題的getInteger2方法。

如果輸入是整數,則應該像對getInteger方法一樣簡單地進行驗證。 如果是,則進行處理。 否則,您要使用next() (而不是nextLine() )跳過它,因為您想跳過此掃描器的下一個完整令牌。

public static int getInteger2(String message) {
    int count = -1;

    boolean isValidInteger = false;

    do {
        System.out.println(message);

        if (console.hasNextInt()) {
            count = console.nextInt();

            if (count != 0) {
                isValidInteger = true;
            } else {
                System.out.println("Denominator cannot equal zero.");
            }
        } else {
            console.next();
        }
    } while (!isValidInteger);

    return count;
}

最后,您的商總是被打印為0.0因為您在輸出它之前不會更新它的值:

r = (double) n1 / n2;
System.out.println("Fraction result is " + r);

看來您的代碼/邏輯中有兩個“主要”問題。

問題1)獲取輸入后,您沒有計算r (商)。

因此,這些行: } catch (InputMismatchException ime) { } System.out.println("Fraction result is " + r); 可以更改為以下形式: } catch (InputMismatchException ime) { } r = (double) n1 / n2; //calculate the quotient System.out.println("Fraction result is " + r); } catch (InputMismatchException ime) { } r = (double) n1 / n2; //calculate the quotient System.out.println("Fraction result is " + r);

問題2)您的代碼: do { System.out.println(message); if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but isValidInteger = true; // can't get it to validate against text. count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop } } while (!isValidInteger); return count; do { System.out.println(message); if (console.nextInt() != 0 || console.hasNextInt()) { // validates against zero but isValidInteger = true; // can't get it to validate against text. count = console.nextInt(); //tried switching statements and using && but get thrown into endless loop } } while (!isValidInteger); return count; 如果您不想在代碼中進行太多更改,可以將其更改為以下內容: do { System.out.println(message); try { if ((count = console.nextInt()) != 0) { isValidInteger = true; } } catch (InputMismatchException ime) { return getInteger2(message); } } while (!isValidInteger); return count; do { System.out.println(message); try { if ((count = console.nextInt()) != 0) { isValidInteger = true; } } catch (InputMismatchException ime) { return getInteger2(message); } } while (!isValidInteger); return count; 因此,僅當console的輸入為int ,才使用nextInt()讀取它並將其存儲在count 在您的代碼中,您將使用nextInt()讀取int ,如果是int ,則可以使用nextInt()再次讀取int ,這將導致用戶寫入2個int以及您在檢查之前讀取int問題它是一個導致引發InputMismatchExceptionint 在我發送給您的代碼中,如果讀取的數字是int而不是0 ,則返回該數字,如果它是0 ,則您的循環再次運行,如果它根本不是int ,則再次簡單地調用該方法(請參閱遞歸) )。 希望這可以幫助您了解問題。 但是,最好的方法可能是重新設計代碼。

暫無
暫無

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

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