JAVA中nextLine()求解惑
如下程序:
import java.util.*;
public class TestInput1
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How much money will you contribute every year? ");
double payment = in.nextDouble();
System.out.print("Interest rate in %: ");
double interestRate = in.nextDouble();
double balance = 0;
int year = 0;
String input;
// update account balance while user isn't ready to retire
do
{
// add this year's payment and interest
balance += payment;
double interest = balance * interestRate / 100;
balance += interest;
year++;
// print current balance
System.out.printf("After year %d, your balance is %,.2f%n", year, balance);
// ask if ready to retire and get input
System.out.print("Ready to retire? (Y/N) ");
input = in.nextLine();
}
while (input.equalsIgnoreCase("N") || (input.length()==0));
}
}
运行后,为什么在第一个Ready to retire? (Y/N) 之后紧接着的是After year 2, your balance is 146,363.00,而不是空格呢?
How much money will you contribute every year? 70000
Interest rate in %: 3
After year 1, your balance is 72,100.00
Ready to retire? (Y/N) After year 2, your balance is 146,363.00
Ready to retire? (Y/N)