java中next与nextLine的用法

来源:百度知道 编辑:UC知道 时间:2024/07/06 15:33:03
import java.util.*;

public class Retirement2
{
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);

在java中,next()方法是不接收空格的,在接收到有效数据前,所有的空格或者tab键等输入被忽略,若有有效数据,则遇到这些键退出。
而nextLine()可以接收空格或者tab键,其输入应该以enter键结束。
当next()和nextLine()连用时,nextLine()会自动接收next()函数的结束符,所以为了避免数据接收有误,要避免二个函数连用。

in.nextLine();返回的是一个长度为0的空字符串:
可以在input = in.nextLine(); 后加
System.out.prinln("前"+input+"后,字符长度="+input.length());
你就能看到

next()要得到有效标记才能返回值,而nextLine()则不管这个,只要有当前行就能返回,当前行的剩余字符是0个照样返回。
修改方法有两种:
1、在每次in.nextDouble();后加一句in.nextLine();就不会出现这个问题了。
因为nextDouble没有义务处理换行,要用nextLine来处理换行,这样后面的input = in.nextLine(); 时没有新行,就会等待输入。

2、把while判断改为while(!input.equals("Y"));或者while (input.equals("N")&&(input.length()!=0));