如何从Java控制台应用程序中的扫描程序读取字符串? [英] How to read strings from a Scanner in a Java console application?
本文介绍了如何从Java控制台应用程序中的扫描程序读取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.util.Scanner;
class MyClass
{
public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
System.out.println("Enter employee name:");
name = scanner.next();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();
}
}
我在尝试输入名字和姓氏时遇到了此异常.
I got this exception while trying to enter a first name and last name.
Enter employee ID:
101
Enter employee name:
firstname lastname
Enter supervisor ID:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at com.controller.Menu.<init>(Menu.java:61)
at com.tests.Employeetest.main(Employeetest.java:17)
但是如果我只输入名字,它会起作用.
but its working on if I only enter the first name.
Enter employee ID:
105
Enter employee name:
name
Enter supervisor ID:
501
我想要的是读取完整的字符串,无论它是以name
还是firstname lastname
的形式给出的.这是什么问题?
What I want is to read the full string whether it is given as name
or as firstname lastname
. What's the problem here?
推荐答案
Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();
呼叫nextInt()
是一个问题,因为它没有接听新行(当您按下Enter键时).因此,在此之后调用scanner.nextLine()
即可完成工作.
Calling nextInt()
was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine()
after that does the work.
这篇关于如何从Java控制台应用程序中的扫描程序读取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文