正在跳过扫描仪nextLine [英] Scanner nextLine is being skipped
问题描述
所以这是我正在使用的代码:
So this is the code I am using:
System.out.println("Create a name.");
name = input.nextLine();
System.out.println("Create a password.");
password = input.nextLine();
但是当它达到这一点时,它只是说创建一个名字。和创建密码。两个在同一时间然后我必须输入一些东西。所以它基本上是跳过我需要键入字符串的Scanner部分。在创建一个名字之后。和创建密码。是打印出来然后输入,名称和密码都改为我输入的内容。如何解决这个问题?
But when it reaches this point it just says "Create a name." and "Create a password." both at the same time and then I have to type something. So it's basically skipping the Scanner parts where I need to type a String. After "Create a name." and "Create a password." is outprinted and I type then, both name and password are changing to what I typed in. How do I fix this?
这是完整的课程。我只是测试所以它实际上不是一个程序:
This is the full class. I am just testing so it isn't actually going to be a program:
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;
}
}
抱歉我的语法不好。我不是英文,所以我很难解释这一点。
And sorry for my bad grammar. I am not English so it is kinda hard for me to explain this.
推荐答案
nextInt()吃了输入数字但没有EOLN:
The nextInt() ate the input number but not the EOLN:
Create your account.
What is your age?
123 <- Here's actually another '\n'
所以第一次打电话到创建名称后的nextLine()接受它作为输入。
so the first call to nextLine() after create name accept that as an input.
System.out.println("Create a name.");
name = input.nextLine(); <- This just gives you "\n"
User Integer.parseInt(input.nextLine( ))或在读取数字后添加另一个input.nextLine()将解决此问题:
User Integer.parseInt(input.nextLine()) or add another input.nextLine() after reading the number will solve this:
int age = Integer.parseInt(input.nextLine());
或
int age = input.nextInt();
input.nextLine()
另见此处。
这篇关于正在跳过扫描仪nextLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!