我正在尝试使用扫描程序类的用户输入值firstname,middlename,lastname,age,但是下面的程序只接受firstname,middlename,lastname而不是age的值。
public void inputEmployeeDetails(){
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the firstname ");
firstname= scanner.nextLine();
System.out.println("Enter the middlename ");
middlename= scanner.nextLine();
System.out.println("Enter the lastname");
lastname= scanner.nextLine();
System.out.println("Enter the age");
age= scanner.nextInt();
}
我需要通过用户提示一个接一个地获取所有值。 根据输入的数据,我显示员工详细信息。有人能让我知道我错过了什么。
我还想从用户那里获取多个输入。如果我在下面,请告诉我
System.out.println("Do you like to fetch more records press "Yes" or "No");
String input=scanner.nextLine();
if(input="Yes")
inputEmployeeDetails();
答案 0 :(得分:0)
年龄变量采用您按下的下一个ENTER键,因此不存储任何内容。由于ENTER的数据类型与age变量的数据类型不同,因此您的代码正在获取InputMismatchException。您需要检查下一个值是否为int,然后将其分配给变量。请参考以下一次:
import java.util.Scanner;
public class Test{
public static void main(String []args){
String firstname, middlename, lastname;
int age;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the firstname ");
firstname= scanner.nextLine();
System.out.println("Enter the middlename ");
middlename= scanner.nextLine();
System.out.println("Enter the lastname");
lastname= scanner.nextLine();
System.out.println("Enter the age");
if(scanner.hasNextInt()) {
age= scanner.nextInt();
}else
age = 0;
System.out.println(firstname + " " + middlename + " " + lastname + " " + age);
}
}
答案 1 :(得分:0)
检查此程序:
String firstname,middlename,lastname,choice;
int age, flag;
Scanner scanner = new Scanner(System.in);
do{
choice=null;
System.out.println("Enter the firstname ");
firstname= scanner.nextLine();
System.out.println("Enter the middlename ");
middlename= scanner.nextLine();
System.out.println("Enter the lastname");
lastname= scanner.nextLine();
System.out.println("Enter the age");
flag=0;age=0;
while(flag==0){
try{
age= scanner.nextInt();
flag=1;
}
catch(Exception e){
scanner.nextLine();
System.out.println("Wrong entry, please enter digits only:");
}
}
System.out.println(firstname+" "+middlename+" "+lastname+" "+age);
System.out.println("Do you like to fetch more records press Yes or No");
scanner.nextLine();
choice=scanner.nextLine();
}while(choice.contains("Y")||choice.contains("y"));
System.out.println("Program terminated.");
scanner.close();
System.exit(0);