我是编程(学习Java)的初学者。我正在尝试编写一个程序,其中列出了四个不同的选项供用户选择。
以下是其中的一部分:
import java.util.*;
public class fight {
public static int upgrade1 = 0;
public static int upgrade2 = 0;
public static int upgrade3 = 0;
public static int upgrade4 = 0;
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your name:");
String player = scan.next();
System.out.println("You have earned 2 upgrade points. Which of the following traits would you like to boost by 2 points?\n"
+ " 1. upgrade1\n 2. upgrade2\n 3. upgrade3\n"
+ " 4. upgrade4");
if (scan.nextInt() == 1) {
upgrade1 = upgrade1 + 2;
System.out.println("Your upgrade1 level is now: " + upgrade1);
}
else if (scan.nextInt() == 2) {
upgrade2 = upgrade2 + 2;
System.out.println("Your upgrade2 level is now: " + upgrade2);
}
else if (scan.nextInt() == 3) {
upgrade3 = upgrade3 + 2;
System.out.println("Your upgrade3 level is now: " + upgrade3);
}
else if (scan.nextInt() == 4) {
upgrade4 = upgrade4 + 2;
System.out.println("Your upgrade4 level is now: " + upgrade4);
}
}
}
问题是:当用户输入他们想要选择的选项时,他们必须输入数字(x是他们选择的数字)x次。例如,用户想要选择选项3.他们必须在控制台中输入数字3三次才能理解并完成下一行。
这是运行程序后的控制台:
请输入您的姓名: 干草堆 你好,里克。您已获得2个升级积分。您希望将以下哪些特征提升2点? 升级1 升级2 3.升级3 4.升级4 3 3 3 您的升级3级现在是:2
我希望这是有道理的,并且非常感谢任何帮助(我假设我只是犯了一个愚蠢的菜鸟错误)。此外,如果您对其结构方式有任何建设性的批评,请不要犹豫。谢谢!
答案 0 :(得分:2)
您无法重复调用scan.nextInt()。当然,除非您希望读取多个不同的整数。
相反:
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your name:");
String player = scan.next();
int ichoice = scan.nextInt();
switch (ichoice) {
case 1:
...
答案 1 :(得分:1)
每次在if语句中调用scan.nextInt
时,它会读取另一个int。改为:
int userChoice = scan.nextInt();
if (userChoice == 1)
{
...
}
else if (userChoice == 2)
...
至于建设性的批评,选择你喜欢的风格并使用它。你的缩进遍布各地;这使得代码更难以阅读。如果它是一种常用的风格并不重要,并且无关紧要其他人的想法,只要确保你喜欢它并坚持下去。
Eclipse可以为您自动格式化代码,这种行为是可自定义的(您可以使用它来调整它以匹配您的样式)。
答案 2 :(得分:0)
每次调用nextInt()
时,都会从输入中读取另一个int。因此,您只想打电话一次!
int choice = scan.nextInt();
if (choice == 1) ...
if (choice == 2) ...
答案 3 :(得分:0)
这是因为您在每个if / else if语句中调用scan.nextInt()。你想要做的是存储他们输入的值,然后检查if / else if语句中的值,否则你基本上会提示用户输入多次。
int input = scan.nextInt();
if (input == 1) {
upgrade1 = upgrade1 + 2;
System.out.println("Your upgrade1 level is now: " + upgrade1);
}
else if (input == 2) {
upgrade2 = upgrade2 + 2;
System.out.println("Your upgrade2 level is now: " + upgrade2);
}
else if (input == 3) {
upgrade3 = upgrade3 + 2;
System.out.println("Your upgrade3 level is now: " + upgrade3);
}
else if (input == 4) {
upgrade4 = upgrade4 + 2;
System.out.println("Your upgrade4 level is now: " + upgrade4);
}