System.out.println()和BufferedReader在控制台中混合输出

时间:2013-05-02 11:48:22

标签: java io bufferedreader

我目前正在开发一个程序,它使用BufferedReader来读取输入,使用System.out.println()来输出。

这是我的代码:

public void chooseMethod() throws IOException{
    int in = 0;
    while(true){

        System.out.println("What do you want to do? (0 to exit, 1 to read Bank         Account, 2 to write Bank Account, 3 to read Bill, 4 to write Bill): ");

        in = Integer.parseInt(cin.readLine());

        if(in == 0){
            break;
        }else if((in < 0) || (in > 4)){
            System.out.println("Invalid choice.");
        }else if(in == 1){
            showBankAccount();
        }else if(in == 2){
            insertBankAccount();
        }else if(in == 3){
            showBill();
        }else if(in == 4){
            insertBill();
        }

    }

    dbm.close();

}

public void insertBankAccount() throws IOException{
    int bankNr = 0;
    int sortCode = 0;
    int accountNumber = 0;
    int balance = 0;
    int interest = 0;
    String details;
    String name;

    while(true){
        System.out.println("Enter bankNr (0 to exit): ");
        bankNr = Integer.parseInt(cin.readLine());

        if(bankNr == 0){
            break;   

        }else if(bankNr <= maxBankNr){
            System.out.println("Invalid Number: already taken");
            break;
        }

        System.out.println("Enter Account Name: ");
        name = cin.readLine();

        System.out.println("Enter Sort Code: ");
        sortCode = Integer.parseInt(cin.readLine());

        System.out.println("Enter Account Number: ");
        accountNumber = Integer.parseInt(cin.readLine());

        System.out.println("Enter balance: ");
        balance = Integer.parseInt(cin.readLine());

        System.out.println("Enter Interest: ");
        interest = Integer.parseInt(cin.readLine());

        System.out.println("Enter Details: ");
        details = cin.readLine();

        bankAccountDAO.insertBankAccount(bankNr, sortCode, accountNumber, balance, interest, details, name);
        this.maxBankNr = bankAccountDAO.getMaxBankNr();


    }


}

现在,假设我输入“2”来“写入银行账户”,输出如下:

运行:

What do you want to do? (0 to exit, 1 to read Bank Account, 2 to write Bank Account, 3 to read Bill, 4 to write Bill):

Enter bankNr (0 to exit): 

2

输出中的这个“2”应该在“输入bankNr(0到退出)之前:”

我曾多次遇到此问题,包括ScannerBufferedReader,并且花了很长时间用谷歌搜索,但似乎无法找到任何答案。

还有其他人有这个问题吗?如果是这样,你是如何设法解决它的?

1 个答案:

答案 0 :(得分:-2)

在循环更改中的insertBankAccount()方法中:

System.out.println("Enter bankNr (0 to exit): ");
bankNr = Integer.parseInt(cin.readLine());

要:

bankNr = Integer.parseInt(cin.readLine());
System.out.println("Enter bankNr (0 to exit): ");