gpt4 book ai didi

java - 不记得第一个用户输入

转载 作者:行者123 更新时间:2023-12-01 19:13:55 24 4
gpt4 key购买 nike

我正在尝试获取员工姓名的用户输入,但扫描仪要么不接受名字,要么不记得名字。主要方法

import java.util.Scanner;

public class ToyShop {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.println("Please select from the following options");
System.out.println("1. Add new employee");
System.out.println("2. Add new customer");
System.out.println("3. Add new product");
System.out.println("4. Edit employee");
System.out.println("5. Edit customer");
System.out.println("6. Edit product");
System.out.println("7. Add new transaction");
System.out.println("8. Display all transactions");
System.out.println("9. Exit");

int pick = in.nextInt();

if(pick == 1) {
//first name input
System.out.println("What is the employees first name: ");
String eFirst = in.nextLine();
Employee e1 = new Employee();
e1.setFirst(eFirst);
in.hasNext();
//last name input
System.out.println("What is their last name: ");
String eLast = in.nextLine();
e1.setLast(eLast);
in.hasNext();

System.out.println(e1.toString() + eFirst);
}

}

}

employee class
public class Employee extends Person {

private static int id;
private String depart;

public Employee() {
this.id = 1000;
this.depart = "";
Employee.super.setFirst("");
Employee.super.setLast("");
}

public Employee(int id, String depart, String first, String last) {
super(first, last);
this.id = id += 1;
this.depart = depart;
}

/**
* @return the id
*/
public int getId() {
return id += 1;
}

/**
* @return the depart (department)
*/
public String getDepart() {
return depart;
}

/**
* @param depart the department to set
*/
public void setDepart(String depart) {
this.depart = depart;
}

@Override
public String toString() {
return "[" + id + "] " + getFirst() + " " + getLast() + ", " + depart;
}
}

当它打印 e1(员工对象 1)toString 时,它只会打印出名字,如果我删除两行 in.hasNext() ,它将跳过用户输入名字

最佳答案

您的问题是方法 nextInt() 无法像方法 nextLine() 那样正确检测换行符(想象一下用户按下 Enter 按钮)。因此,您需要在其后添加 nextLine() 才能检测换行符输入。方法 hasNext() 不是必需的,因为它仅根据扫描仪 token 的状态返回一个 boolean 值。

int pick = in.nextInt();
in.nextLine(); //this is what's needed to detect the newline

if(pick == 1) {
//first name input
System.out.println("What is the employees first name: ");
String eFirst = in.nextLine();
e1.setFirst(eFirst);
//in.hasNext(); (you don't need this)
//last name input
System.out.println("What is their last name: ");
String eLast = in.nextLine();
e1.setLast(eLast);
//in.hasNext(); (you don't need this)

System.out.println(e1.toString() + eFirst);
}

这将成功检测数字选择、名字和姓氏的输入。

关于java - 不记得第一个用户输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59439640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com