3

を使用してコンソール入力からcharを解析しようとしてin.nextLine()いますcharAt(0)。私の問題は、onを実行するために文字列を入力するようにユーザーに求めた後in.nextLine()、入力をスキップし、null文字列の最初の文字を取得しようとしたためにエラーが発生することです。

System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
String temp = in.nextLine();
char tempOperator = temp.charAt(0);

エラーは

java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)

完全なプログラムはここから入手できます

一般的なコメントや提案はいつでも歓迎します。前もって感謝します。

4

4 に答える 4

4

を実行cValue = in.nextDouble();すると、次のトークン(完全な値)を読み取り、それを解析してdoubleにします。この時点でリターンキーが押された場合は\n、バッファ内で次に読み取るトークンです。

次のように実行すると、前のEnterのバッファからをString temp = in.nextLine();読み取り、empty( "")文字列のみを読み取ったため失敗します。\ncharAt(0)

この問題を解決するには、追加を追加して前のバッファーをスキップするか、以下のようにスキップパターンとして追加します(これはとして定義されたパターンin.nextLine()です)。\n \rScanner.classLINE_SEPARATOR_PATTERN

 in.skip("\r\n|[\n\r\u2028\u2029\u0085]");

または、以下のように小さなwhileループを配置します。

   String temp = "";
   while((temp.length() < 0){
      temp = in.nextLine();
   }
于 2012-10-31T16:10:26.957 に答える
1

あなたが考えるかもしれない1つのことはこれをする代わりです:

String temp = in.nextLine();

これを行う:

String temp = in.next();

もちろん、これは、ユーザー入力から1文字だけが必要であると想定しているため、ユーザーに要求しているのはそれだけのようです。これにより、受け取っている例外が取り除かれます。ただし、ユーザーが複数の文字を入力したときにエラーをスローしたい場合は、最初に行全体を読んで長さを確認することをお勧めします。

于 2012-10-31T16:10:06.817 に答える
1

さて、問題は行にありin.nextDouble()ます。

Scanner#nextDoubleユーザーから次のトークンをdoubleとして読み取ります。したがって、4.5入力として値を渡すとnextDouble、はトークンを読み取り、そのユーザーが入力し4.5た後の入力をスキップします。linefeedこれで、この改行(これは新しい行であるため)は、次の入力と見なされますScanner.nextLine。したがって、あなたのin.nextLine後は前のによって残ったものをin.nextDouble読んでいます。newlinein.nextDouble

したがって、回避策は@tjg184が彼の回答で指摘したものと同じです。in.nextLineその後に空を追加すると、残ったin.nextDoubleものが読み取らnewlineれます。だから、あなたの来るin.nextLineものが実際に渡された入力を読むように。

cValue = in.nextDouble();
in.nextLine();  // Add this before your `while` which will read your `newline`

while (true) {
    //continue;
}

一方、Scanner.nextLine改行まで完全な入力を読み取ります。newlineしたがって、次にユーザーが読み取るときに読み取られるものは残りません。

この答えは必要ありませんでしたが、@tjg184's答えは同じです。正確に何が起こっているのかをよりよく説明するために追加しました。

于 2012-10-31T16:10:41.820 に答える
0

あなたのプログラムを見ると、それはのせいですString temp = in.nextLine();。ユーザーが「Enter」キーを押すと、ユーザーが「Enter」を押すと入力したため、基本的にこのステートメントはスキップされます。次のことを試してください。注:次の行のみを追加しましたString enter = in.nextLine();

import java.util.Scanner;

public class Calculator
{    
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        char operator = 'z'; //initialize operator
        double cValue; //current value
        double rhValue; //right hand value
        boolean cont = true;

        System.out.print("Enter starting value: ");
        cValue = in.nextDouble();

        // disregard the "Enter" key
        String enter = in.nextLine();

        while(true)
        {
            System.out.print("Select an operator (+, -, *, /), 'c' or 'C' to clear, or 'q' to quit: ");
            String temp = in.nextLine();
            char tempOperator = temp.charAt(0);

            if (tempOperator == 'c' || tempOperator == 'C')
            {
                cValue = 0.0;
                System.out.println("Current value is: " + cValue);
                System.out.println();
            }
            else if(tempOperator == 'q')
            {
                System.out.println("Final result: " + cValue);
                System.exit(1);
            }
            else if(tempOperator == '+' || tempOperator == '-' || tempOperator == '*' || tempOperator == '/')
            {
                operator = tempOperator;
                break;
            }
            else
                throw new IllegalArgumentException("operator not valid");
        }


        System.out.println("Enter a right hand value (type double): ");
        rhValue = in.nextDouble();

        System.out.println("Math expression: answer " + operator + "= " + rhValue);
        switch(operator)
        {
            case '+': cValue =+ rhValue;
                      break;
            case '-': cValue =- rhValue;
                      break;
            case '*': cValue = cValue * rhValue;
                      break;
            case '/': cValue = cValue / rhValue;
                      break;
        }

        System.out.println("Current value is: " + cValue);
    }
}
于 2012-10-31T15:58:33.653 に答える