2013-02-15 137 views
0

所以这是我使用的代码:“创建一个名为”扫描仪nextLine被跳过

System.out.println("Create a name."); 
name = input.nextLine(); 
System.out.println("Create a password."); 
password = input.nextLine(); 

但是,当它到达该点它只是说,和“创建密码”。在同一时间,然后我必须键入一些东西。所以它基本上是跳过扫描器部分,我需要输入一个字符串。在“创建名称”之后。和“创建密码”。是outprinted和我键入然后,名称和密码正在改变我输入英寸如何解决这个问题?

这是全班。我只是测试,所以它实际上并不是一个程序:

package just.testing; 

import java.util.Scanner; 
public class TestingJava 
{ 
    static int age; 
    static String name; 
    static String password; 
    static boolean makeid = true; 
    static boolean id = true; 

    public static void main(String[] args){ 
     makeid(null); 
     if(makeid == true){ 
      System.out.println("Yay."); 
     }else{ 

     } 
    } 
    public static void makeid(String[] args){ 
     System.out.println("Create your account."); 
     Scanner input = new Scanner(System.in); 
     System.out.println("What is your age?"); 
     int age = input.nextInt(); 
     if(age<12){ 
      System.out.println("You are too young to make an account."); 
      makeid = false; 
      return; 
     } 
     System.out.println("Create a name."); 
     name = input.nextLine(); 
     System.out.println("Create a password."); 
     password = input.nextLine(); 
     return; 
    } 
} 

对不起,我的坏语法。我不是英国人,所以我很难解释这一点。

+0

您是否正确声明并初始化了'扫描仪' – 2013-02-15 16:08:01

+0

是:“扫描仪输入=新扫描仪(System.in);” – 2013-02-15 16:09:50

+1

您需要确保使用System.in初始化扫描仪。编辑:啊,好的 – Nathan 2013-02-15 16:10:04

回答

10

的nextInt()吃了输入号码,但不是EOLN:

Create your account. 
What is your age? 
123 <- Here's actually another '\n' 

所以第一次调用nextLine()后,创建名接受为输入。

System.out.println("Create a name."); 
name = input.nextLine(); <- This just gives you "\n" 

用户的Integer.parseInt(input.nextLine())或读数将解决这个后添加另一input.nextLine():

int age = Integer.parseInt(input.nextLine()); 

int age = input.nextInt(); 
input.nextLine() 

另外请参阅here以获取重复问题。

+0

那么我该如何解决这个问题?编辑修改为 – 2013-02-15 16:17:46

+0

。 – 2013-02-15 16:20:27

+0

谢谢你的工作。我仍然不知道为什么国际会这样做,虽然... – 2013-02-15 16:22:16

1

这并不真正告诉你为什么行被跳过,但你捕捉名和密码,你可以使用控制台:

Console console = System.console(); 
String name = console.readLine("Create a name."); 
char[] password = console.readPassword("Create a password."); 
System.out.println(name + ":" + new String(password)); 
+0

不工作,因为我可能想稍后再使用该方法,然后已经创建了字符串密码... – 2013-02-15 16:20:28

0

您还可以使用下一个()而不是nextLine()。我在eclipse中测试过它。它的工作正常。

0

next()会工作,但它不会读取空格后的字符串。