java – 正在跳过扫描程序nextLine
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – 正在跳过扫描程序nextLine,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1947字,纯文字阅读大概需要3分钟。
内容图文
参见英文答案 > Scanner is skipping nextLine() after using next() or nextFoo()? 15个
> How to use java.util.Scanner to correctly read user input from System.in and act on it? 1个
所以这是我使用的代码:
System.out.println("Create a name.");
name = input.nextLine();
System.out.println("Create a password.");
password = input.nextLine();
但是当它到达这一点时,它只是说“创建一个名字”.和“创建密码”.两个在同一时间然后我必须输入一些东西.所以它基本上是跳过我需要键入字符串的Scanner部分.在“创建一个名字”之后.和“创建密码”.是打印出来的,然后输入,名称和密码都改为我输入的内容.如何解决这个问题?
这是全班.我只是测试所以它实际上不是一个程序:
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;
}
}
抱歉我的语法不好.我不是英国人,所以我很难解释这一点.
解决方法:
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以获取重复的问题.
内容总结
以上是互联网集市为您收集整理的java – 正在跳过扫描程序nextLine全部内容,希望文章能够帮你解决java – 正在跳过扫描程序nextLine所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。