gpt4 book ai didi

java - 打印2次不知道为什么

转载 作者:行者123 更新时间:2023-12-02 05:28:35 25 4
gpt4 key购买 nike

当我从删除部分中退出时遇到问题,代码打印主菜单选项两次

代码没有错误,运行正常,但为什么打印两次而不是一次?

 public void mainloop() {
for (int i = 0; i < 100; i++) {

String x;

System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");

x = input.nextLine();

if (x.equalsIgnoreCase("0")) {
System.out.println("Thank you!");
break;
}
if (x.equalsIgnoreCase("1")) {
String Name;
String Number;

System.out.println("Please Enter your Name below");
Name = input.nextLine();
System.out.println("Please Enter your Number below");
Number = input.nextLine();
System.out.println("");
System.out.println("Your Name " + Name + " and Number " + Number + " has been saved!\n");

objectclass objectclassObject = new objectclass(Name, Number);
Test.add(objectclassObject);
}
if (x.equalsIgnoreCase("2")) {

System.out.println("-------ALL NAME AND NUMBERS-------");
System.out.println("");

for (int j = 0; j < Test.size();) {
objectclass p = Test.get(j++);
System.out.println(j + ". Name: " + p.getName() + " - " + p.getNumber());
}
for (int j = 0; j < Test.size(); j++) {
System.out.println("");
System.out.println("Enter Index number to remove Contact from Phonebook!");
int v = input.nextInt();
int temp = (v - 1);
if (v >= 1 && v <= Test.size()) {
System.out.println("Name: " + Test.get(temp).getName() + " And Number: " + Test.get(temp).getNumber() + " has been removed!!");
System.out.println("");
Test.remove(temp);
} else {
System.out.println("Please enter number properly!!");
}
break;
}
}
if (x.equalsIgnoreCase("3")) {
String y;
System.out.println("*** Enter your Name below for search ***");
y = input.nextLine();

for (objectclass p : Test) {
String z = p.getName();
if (z.equalsIgnoreCase(y)) {
System.out.println("Your Name is: " + p.getName() + "\nYour Number is: " + p.getNumber());
System.out.println("");
}
if (!z.equalsIgnoreCase(y)) {
System.out.println("Contact not found!!!");
}
}
}
}
}

}

System.out.println("Please Select your option");
System.out.println("............................");
System.out.println("1 ADD NAME AND NUMBER \n2 REMOVE NAME AND NUMBER \n3 SEARCH NAME AND NUMBER \n0 EXIT");
System.out.println("............................");

这会打印两次:/~

最佳答案

如果打印两次,则说明您执行了两次循环。读取变量“x”后尝试显示它。我敢打赌,您的合法输入之间有额外的空字符串。

发生的情况是 nextInt() 不消耗换行符。因此,下次读取 x 时,您将读取值 v 之后的行尾。

关于java - 打印2次不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25769742/

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