gpt4 book ai didi

java - 为什么在 while 循环中行会重复出现?

转载 作者:行者123 更新时间:2023-12-01 11:51:47 25 4
gpt4 key购买 nike

我制作了一个简单的程序,可以选择添加、投票和查看对 3 个不同候选人的投票。由于某种原因,第 18 行及其后面的第 72 行重复出现,例如,如果您开始按 1 创建候选者,输入名称并按 Enter 键,它将如下所示:

Add candidate (1) or vote (2) or view number of votes on each candidate (3): Incorrect number, please try again.

但随后又恢复正常...

Add candidate (1) or vote (2) or view number of votes on each candidate (3):

这是完整的代码(重复的行已注明):

package array;

import java.util.Scanner;

public class Array {

public static void main(String[] args) {
char[] Vote_Choice = {'A', 'B', 'C'};
String[] candidates = { "none", "none", "none"};
int[] votes = {0, 0, 0};


Scanner input = new Scanner(System.in);
boolean done = false;

while (!done) {
boolean done2 = false;
System.out.print("Add candidate (1) or vote (2) or view number of votes on each candidate (3): "); // here (line 18)

switch (input.nextLine()) {
case "1": System.out.print("Type new candidates name: ");
while (!done2) {
if (candidates[0].equals("none")) {
candidates[0] = input.next();
done2 = true;
}
else if (!candidates[0].equals("none") && candidates[1].equals("none")) {
candidates[1] = input.next();
done2 = true;

}
else if (!candidates[0].equals("none") && !candidates[1].equals("none") && candidates[2].equals("none")) {
candidates[2] = input.next();
done2 = true;
}
else if (!candidates[0].equals("none") && !candidates[1].equals("none") && !candidates[2].equals("none")) {
System.out.println("Sorry, all candidate slots are full.");
done2 = true;
}
}
break;
case "2":
System.out.println("Type letter corresponding to the candidate you wish to vote for: ");

System.out.print("Type A for candidate "+ candidates[0] +", type B for candidate "+candidates[1]+", type C for candidate "+candidates[2]+": ");
String choice = input.next();
if (choice.equals("A")) {
votes[0]++;
}
if (choice.equals("B")) {
votes[1]++;
}
if (choice.equals("C")) {
votes[2]++;
}


break;
case "3": if (!candidates[0].equals("none")) {
System.out.println("Candidate "+ candidates[0] +": "+votes[0]);
}
if (!candidates[1].equals("none")) {
System.out.println("Candidate "+ candidates[1] +": "+votes[1]);
}
if (!candidates[2].equals("none")) {
System.out.println("Candidate "+ candidates[2] +": "+votes[2]);
}
else {
System.out.println("Sorry, there are no current candidates.");
}
break;
default: System.out.println("Incorrect number, please try again."); // And here, line 72
}

}


}
}

最佳答案

这是因为您有 input.next() 而不是 input.nextLine() 。行尾“保留”在输入流中,当您调用它时,它返回该流中剩下的内容(通常是空字符串)。

关于java - 为什么在 while 循环中行会重复出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28753997/

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