3

ユーザーが入力した番号が Zeckendorf かどうかを確認しています。そうでない場合は例外を表示したいのですが、どうすればよいですか? また、Zeckondorf を 10 進数に変換するにはどうすればよいですか?

import java.util.Scanner;


public class IZeckendorfNumberConvertor {
static String number;
int zeckonderEquivalent;
static Scanner scanner = new Scanner(System.in);

public static void main(String[] args) {

    convertToZeckonderNumber();
    isTrueZeckonderNumber();
}

private static boolean isTrueZeckonderNumber() {
    System.out.println("Enter a Zeckonder Number:");
    number = scanner.nextLine();
    if (number.equals("10100")) 
    {
        return true; } 
    else if (number.equals("010011") || number.equals("010100")) 
    { 
        return false; }
    return false;
}

private static void convertToZeckonderNumber() {

}}
4

7 に答える 7

6

例外 (つまり、トレースなど) を表示しないことをお勧めします。これはユーザーにとって非常に不親切です。throw 構文を使用して、適切な例外をスローできます。

 throw new Exception("Given number is not a Zeckendorf number");

ただし、必ずキャッチして、きれいなメッセージを表示してください。

try {
   // Your input code goes here
} catch (Exception e) {
    System.out.println(e.getMessage());
}

もう 1 つの簡単なオプションは、メソッドの戻り値を確認し、それに応じて結果を出力することです。

後者のソリューションを使用することをお勧めします。例外は、プログラムで予期しない何か悪いことが発生し、それを適切に処理したい場合に使用されるからです。あなたの場合、動作は予想される(つまり、ユーザーが間違った番号を与える)ため、戻り値のチェックははるかにクリーンで簡単になります。

于 2013-11-04T12:07:02.883 に答える
4

例外をキャッチするには、try catch ブロックを使用します

            try {

            } catch (Exception e) {

                e.printStackTrace();
            }

また、throw を使用して新しい例外をスローします

ここに画像の説明を入力

于 2013-11-04T12:23:45.497 に答える
1

私の意見では、次のようなことを試すことができます

 public static void main(String[] args) {    
  if(!isTrueZeckonderNumber()){
      // your message should goes here
       System.out.println("Your message");
    }
 }

本当に例外をスローしたい場合は、次のようにします

 private static boolean isTrueZeckonderNumber() throws Exception{
    System.out.println("Enter a Zeckonder Number:");
    number = scanner.nextLine();
    if (number.equals("10100")) {
        return true;
    } else{
        throw new Exception("your message");
    }        
}
于 2013-11-04T12:08:37.667 に答える
1

シンプルなif.

if(yourCondition){
    // Happy scenario
    // Go shead
}else{
    // Error Scenario
    System.out.println("Error. Invalid Input.");
    // If you persist to throw an exception, then you can do something like this
    // throw new Exception("Exception Explanation"); // I've commented this, but you can uncomment it if needed
    // But the advice is to display an error message, than throw a exception.
}

変換に関しては、このように2進数を10進数に変換できます

int i = Integer.parseInt(binaryString, 2); // 2 indicates the radix here, since you want to convert from binary.
于 2013-11-04T12:06:51.863 に答える
1

このコード スニペットを使用すると、文字列を整数に変換できます。

int numberAsInt;
    try {
          numberAsInt = Integer.parseInt(number);
    } catch (NumberFormatException e) {
          //Will throw an Exception
    }

独自の Exception クラスを作成する場合は、ここに示すように作成するか、単に RuntimeException をスローします。

throw new RuntimeException("Your Message");
于 2013-11-04T12:07:52.190 に答える