使用Scanner对象读取一系列输入

时间:2013-02-28 15:55:59

标签: java java.util.scanner

我必须检索三个输入,一个整数,一个字符串和一个double;这是我以为我会怎么做[注意:包含空格的字符串]

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

我试图替换

中的input.nextLine()
record.setName(input.nextLine());

输入input.next(),因为InputMisMatchException但仍然没有解决问题。抛出错误,因为可能会为一个新的行值分配一个double值[这是我认为不确定的]有没有办法检索包含空格的字符串并且能够完成我必须输入的三个输入同时。谢谢

注意:我找不到任何相关问题 我只想添加发生错误的整个方法

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

1 个答案:

答案 0 :(得分:1)

nextLine会将所有剩余数据读取到字符串的末尾,包括double。您需要使用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,我会得到相同的结果。
  • 如果字符串(第二个条目)包含空格,则第二个单词将被解析为double并将生成错误报告
相关问题