作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我制作了一个简单的程序,可以选择添加、投票和查看对 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/
我是一名优秀的程序员,十分优秀!