今天,Java作业要求程序中输入多个变量,用到了nextDouble、nextLine方法。奇怪的是,当nextDouble方法后面接nextLine方法时,程序运行后会出现输入double类型数据后下一个nextLine不执行的问题。
public class FlightTest {
public static void main(String[] args)
{
Scanner scan1 = new Scanner(System.in) ;
Flight flight1 = new Flight ("MJ1",1,"ZP","SD");
System.out.println("Please enter the alrline name");
flight1.setalname(scan1.nextLine());
System.out.println("Please enter the flight number");
flight1.setfln(scan1.nextInt());
System.out.println("Please enter the origin");
flight1.setori(scan1.nextLine());
System.out.println("Please enter the destination");
flight1.setdes(scan1.nextLine());
System.out.println("The airline name is :"+flight1.airlinename+".The flight number is:"+flight1.flightnumber+",the origin is:"+flight1.origin+"the destination is:"+flight1.destination);
}
}
一开始,我以为是自己的代码出了问题,调试了很久都没有解决。最后想到可能是Java语言自身的问题,刚要在CSDN上提问,发现已经有人问过这个问题
http://blog.csdn.net/yuzhi829/article/details/40867807
http://blog.csdn.net/homedjy/article/details/8733270
这样看来,nextLine方法会将上一个方法中输入的回车符读入。
解决方法:
如果改为next方法则不会出现这种问题,因为next方法是从第一个非空字符开始读入,会自动舍去非空字符前面的空字符,也会舍去后面的空字符。
CSDN大法好!