0

整数、文字列、および倍精度浮動小数点数の3つの入力を取得する必要があります。これが私がやろうと思った方法です[注:スペースを含む文字列]

record.setAccountNumber(input.nextInt());
record.setName(input.nextLine());
record.setBalance(input.nextDouble());

input.nextLine()を置き換えようとしました

record.setName(input.nextLine());

InputMisMatchExceptionが原因で、input input.next()を使用しますが、それでも問題は解決されません。おそらく改行値にdouble値が割り当てられているため、エラーがスローされます[これは私にはわかりません]スペースを含む文字列を取得し、入力する必要のある3つの入力を完了する方法があります。同時。ありがとう

注:これに関連する問題は見つかりませんでした。エラーが発生するメソッド全体を追加します。

public void addAccountRecords(){
    AccountRecord record = new AccountRecord();
    input = new Scanner (System.in);

    try {
        output = new Formatter("oldmast.txt");
    } catch (FileNotFoundException e) {
        System.err.println("Error creating or opening the file");
        e.printStackTrace();
        System.exit(1);
    } catch (SecurityException e){
        System.err.println("No write access to this file");
        e.printStackTrace();
        System.exit(1);
    }


    System.out.println("Enter respectively an account number\n"+
            "a name of owner\n"+"the balance");

        while ( input.hasNext()){
            try{
                record.setAccountNumber(input.nextInt());
                record.setName(input.nextLine());
                record.setBalance(input.nextDouble());

                if (record.getBalance() >0){
                    output.format("%d\t%s\t%,.2f%n",record.getAccountNumber(),
                            record.getName(),record.getBalance());
                    record.setCount((record.getCount()+1));
                }else
                    System.err.println("The balance should be greater than zero");

            }catch (NoSuchElementException e){
                System.err.println("Invalid input, please try again");
                e.printStackTrace();
                input.nextLine();

            }catch (FormatterClosedException e){
                System.err.println("Error writing to File");
                e.printStackTrace();
                return;
            }
            System.out.println("Enter respectively an account number\n"+
                    "a name of owner\n"+"the balance\n or End of file marker <ctrl> z");
        }//end while
        output.close();
        input.close();

}//end AddAccountRecords
4

1 に答える 1

1

nextLinedoubleを含め、文字列の最後まで残りのすべてのデータを読み取ります。next代わりに使用する必要があります。なぜあなたが得るのかわかりませんInputMisMatchException-これは例えば:

String s = "123 asd 123.2";
Scanner input = new Scanner(s);
System.out.println(input.nextInt());    //123
System.out.println(input.next());       //asd
System.out.println(input.nextDouble()); //123.2

したがって、問題はおそらく入力またはコードの他の場所にあります。

ノート:

  • 使用Scanner input = new Scanner(System.in);して入力すると123 asd 123.2、同じ結果が得られます。
  • 文字列(2番目のエントリ)にスペースが含まれている場合、2番目の単語はdoubleとして解析され、レポートでエラーが生成されます
于 2013-02-28T15:59:03.430 に答える