日期:2014-05-20  浏览次数:20726 次

这为什么不能用nextLine()?
import   java.util.Scanner;

public   class   RunnianTester
{
public   static   void   main(String[]   args)
{
Scanner   scan   =new   Scanner(System.in);
String   another;

do
{
    System.out.print( "输入一个年份: ");
    int   year=scan.nextInt();

            if(year> =1582)
            {
                if((year%4==0&&year%100!=0)||(year%400==0&&year%100==0))
                      System.out.println( "这是闰年 ");
                else
                      System.out.println( "这不是闰年 ");
            }
            else
                System.out.println( "错误:1582年之前还未使用阳历!! ");    
         
          System.out.println();
          System.out.print( "测试另一个?(y/n):   ");
          another=scan.next();   //这里为什么不能用scan.nextLine()?
        }while(another.equalsIgnoreCase( "y "));
}
}

------解决方案--------------------

System.out.print( "输入一个年份: ");
int year=scan.nextInt();//此处输入一个数后按的回车被another=scan.nextLine();接收
所以只能用scan.next();来接收字符 或者 写两行another=scan.nextLine();

本人也是初学,有不对的地方大家帮指点哈。
------解决方案--------------------
scanner有个扫描器

nextLine方法是返回当前行的其余部分,当前位置移至下一行的行首。
这里说的是指扫描器

你的程序 int year=scan.nextInt(); 假如输入是 2000 现在扫描器停在了0的后面
下面你又掉用scan.nextLine()的时候因为2000后面没东西 所以他什么也没取到并且吧位置
移至到了下一行的行首 这时候你在调用scan.nextLine() 你就可以输入东西了