2015-07-28 45 views
1

下面是两个脚本,它们只是用户输入的顺序不同。脚本#1工作,而脚本#2不能按预期工作。 在脚本#1中我首先问name问题,然后问age问题。 在Script#2中,我首先询问age问题,然后问name问题。用户输入`nextLine`和`nextInt`命令

脚本#1(作品):

import java.util.Scanner; 

public class Example2 { 
    public static void main(String[] args) { 
     // Initiate a new Scanner 
     Scanner userInputScanner = new Scanner(System.in); 

     // Name Question 
     System.out.print("\nWhat is your name? "); 
     String name = userInputScanner.nextLine(); 

     // Age Question 
     System.out.print("How old are you?"); 
     int age = userInputScanner.nextInt(); 

     System.out.println("\nHello " + name + ". You are " + age 
       + " years old"); 
    } 
} 

脚本#2(不工作):

在脚本#2
import java.util.Scanner; 

public class Example2 { 
    public static void main(String[] args) { 
     // Initiate a new Scanner 
     Scanner userInputScanner = new Scanner(System.in); 

     // Age Question 
     System.out.print("How old are you?"); 
     int age = userInputScanner.nextInt(); 

     // Name Question 
     System.out.print("\nWhat is your name? "); 
     String name = userInputScanner.nextLine(); 


     System.out.println("\nHello " + name + ". You are " + age 
       + " years old"); 
    } 
} 

,用户输入age后,他/她得到下面印到控制台上:

What is your name? 
Hello . You are 28 years old 

然后脚本结束,不允许他/她输入name

我的问题: 为什么脚本#2不工作? 我能做些什么让脚本#2工作(同时保持输入顺序)

+0

你说的不工作呢?任何错误? – Haris

回答

4

当您读取一行时,它会读取整行直到最后。

当您读取一个数字时,它只是读取数字,例如它不会读取该行的结尾,除非再次调用nextInt(),在这种情况下,它会将新行读取为空白。

总之,如果你希望输入忽略号码后话,写

int age = userInputScanner.nextInt(); 
userInputScanner.nextLine(); // ignore the rest of the line. 

在你的情况,你的nextLine()将读取数字或空字符串后的文字,如果你没有进入任何东西。

4

你必须消耗EOL(行尾)读岁以后:

System.out.print("How old are you?"); 
    int age = userInputScanner.nextInt(); 
    userInputScanner.nextLine(); 


    // Name Question 
    System.out.print("\nWhat is your name? "); 
    String name = userInputScanner.nextLine(); 

如果你不这样做做到这一点,EOL符号将消耗在String name = userInputScanner.nextLine();,这就是为什么你不能输入它。

2

nextInt()方法不会消耗输入流中的回车。你需要自己消耗它。

import java.util.Scanner; 

public class Example2 { 
    public static void main(String[] args) { 
     // Initiate a new Scanner 
     Scanner userInputScanner = new Scanner(System.in); 

     // Age Question 
     System.out.print("How old are you?"); 
     int age = userInputScanner.nextInt(); 

     // consume carriage return 
     userInputScanner.nextLine(); 

     // Name Question 
     System.out.print("\nWhat is your name? "); 
     String name = userInputScanner.nextLine(); 


     System.out.println("\nHello " + name + ". You are " + age 
       + " years old"); 
    } 
} 
1

如果用户输入一个数字(可以说是21),那么输入实际上是:“21 \ n”。

您需要跳过“\ n”与nextLine额外的呼叫:

// Age Question 
System.out.print("How old are you?"); 
int age = userInputScanner.nextInt(); 
userInputScanner.nextLine(); // skip "\n" 
相关问题