本文介绍了如何从控制台应用程序JAVA中的扫描仪读取字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
import java.util.Scanner;
class MyClass
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int eid,sid;
String ename;
System.out.println("Enter Employeeid:");
eid=(scanner.nextInt());
System.out.println("Enter EmployeeName:");
ename=(scanner.next());
System.out.println("Enter SupervisiorId:");
sid=(scanner.nextInt());
}
}
我在输入时尝试输入
Enter Employeeid:
101
Enter EmployeeName:
firstname lastname
Enter SupervisiorId:
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)
但是在此工作
Enter Employeeid:
105
Enter EmployeeName:
name
Enter SupervisiorId:
501
我想要的是我必须阅读完整的字符串是否它以 name
或 firstname lastname
给出。例如: - ( john
- >是由scanner.next()接受;但是scan.next()不接受 john carter
; )
What I want is that i must read the full string whether it is given as name
or as firstname lastname
..Eg:-(john
--> is accepted by scanner.next(); but john carter
is not accepted by scanner.next(); )
推荐答案
import java.util.Scanner;
class MyClass
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
int eid,sid;
String ename;
System.out.println("Enter Employeeid:");
eid=scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter EmployeeName:");
ename=scanner.nextLine();
System.out.println("Enter SupervisiorId:");
sid=(scanner.nextInt());
}
}
调用nextInt()是一个问题,因为它没有'拿起新线(当你按下回车键)。因此,在此之后调用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中的扫描仪读取字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!