[英]How to use multiple scanners of different types in java?
我有以下Java代码(在默认的Eclipse控制台上执行):
String name = "";
System.out.printf("Name of the Story Arc: ");
if(in.hasNext()) {
name = in.nextLine();
}
int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}
StoryArc a = new StoryArc(name, id, issues_nb + 1, l);
story_arcs.add(a);
我试图连续多次执行它,但是它的行为很奇怪:第一次执行可以正常工作,询问名称,然后询问长度。 第二次执行时,它询问名称,但不询问长度(设置为0)。 第三个执行要求长度,但是将名称设置为“”,并且这样循环,偶数执行为长度,奇数执行为名称。
这是我使用Java编写的第一个程序,因此我想我对扫描仪一无所知,但是经过长时间的研究我仍无法弄清,请帮忙。
编辑:谢谢大家! 在您的帮助下,我们设法使其成功!
l = in.nextInt()
将仅获取整数,但并不表示您已经完成输入该行,因此您必须告诉Scanner您自己。 有两种方法可以做到这一点:
您可以执行in.nextLine();
表示我们已经完成了包含整数的行:
更改l = in.nextInt();
至:
l = in.nextInt();
if(in.hasNext()){
// Ignore the rest of the line that contained the length integer-input:
in.nextLine();
}
另外,您可以对所有输入使用in.nextLine()
,然后将String自己转换为整数:
更改l = in.nextInt();
至:
String input = in.nextLine();
// Verify the entire line only contains the integer:
if(input.matches("\\d+")){
l = Integer.parseInt(input);
} else{
// TODO: Validation message: not a valid integer
}
您需要一个while
循环来获取有效的name
,并且
您需要使用try/catch
的while
循环来获取l
,因为用户可以输入无效值而不是有效整数:
String name = "";
while (name.trim().length() == 0) {
System.out.print("Name of the Story Arc: ");
name = in.nextLine();
}
int l = 0;
boolean valid = false;
while (!valid) {
try {
System.out.print("Length of the Story Arc: ");
l = in.nextInt();
valid = (l > 0);
} catch (Exception e) {
e.printStackTrace();
}
}
尝试一下。您的代码没有问题,但是可以运行之后可能会有所帮助
import java.util.*;
public class Answer {
public static void main(String[] args) {
String name = "";
System.out.printf("Name of the Story Arc: ");
Scanner in = new Scanner(System.in);
if(in.hasNext()) {
name = in.nextLine();
}
int l = 0;
System.out.printf("Length of the Story Arc: ");
if(in.hasNextInt()) {
l = in.nextInt();
}
System.out.println("Name of the Story Arc: "+name);
System.out.println("Length of the Story Arc: "+l);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.