2016-10-25 9 views
-2

私はクラスで課題を持っていますが、教師のスケルトンコードを独自の方法で設計する代わりに使用する必要があります。コメントはメソッドの説明であり、メソッドはこれまでのものですが、どのように動作するのかまだ分かりません。私が混乱するのは、ユーザーが何をすべきかを知る前にオプションを表示する必要があるということです。入力を最初にせずにメソッドを実行するにはどうすればいいですか?メソッドを入力中に受け入れるにはどうすればよいですか?

/** 
* Prints the main menu (see output examples), allows the user to make a selection from available operations 
* 
* @param input the Scanner object you created at the beginning of the main 
* method. Any value other than the 4 valid selections should generate an 
* invalid value prompt. Print the list again and prompt user to select a 
* valid value from the list. 

* @return an integer from 1-4 inclusive representing the user’s selection. 

*/ 

public static int mainMenuOptionSelector(Scanner input){ 
    System.out.println("Please select an option from the list below:"); 
    System.out.println("1. Check the balance of your account"); 
    System.out.println("2. Make a deposit"); 
    System.out.println("3. Withdraw an amount in a specific currency"); 
    System.out.println("4. End your session (and withdraw all remaining currency in U.S. Dollars)"); 

    if(input.equals(1)) 
     return 1; 
    else if(input.equals(2)) 
     return 2; 
    else if(input.equals(3)) 
     return 3; 

    else if(input.equals(4)) 
     return 4; 
    else{ 
     System.out.println("Input falied validation."); 
     System.out.println("Please try again"); 
     return 0; 
    } 

} 
+0

'input.equals(1)'は意味をなさない。このコードは非常に壊れているようです。 – Carcigenicate

+1

[スキャナ#nextLine](https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html#nextLine--)が役立つ場合があります。つまり、あなたのコードでは、 'input.nextLine()'を呼び出します。 – GriffeyDog

答えて

0

あなたの方法(先生が悪い命名習慣になり、彼自身のスキャナを、ロールしていない限り)、入力としてjava.util.Scannerを取ります。スキャナは、キーボード(通常System.in)などのさまざまなソースからデータを読み込むためのメソッドを提供します。

これらの方法の1つはnextInt()です。これはスキャナの入力から次のintを読み込んで返します。

theSelection = input.nextInt(); 

をそして、あなたは他のあらゆるintとして新しい変数theSelectionを参照することができます:あなたはこのような何かを行うことができます。 nextIntメソッドは、実行時に例外をスローする可能性があり、正常にキャッチして処理する必要があることに注意してください。

関連する問題