我的程序将向用户显示一个框并为其提供多个选项。结果,他们将不得不输入一个整数来表示他们希望继续进行的步骤。我想知道如何输出他们在程序中选择的步骤。我需要为此使用for语句吗?
import java.util.Scanner;
public class testing {
public static void main (String []args){
Scanner input = new Scanner(System.in);
String coursename;
String option1 = "BTEC 90 Credit Diploma Grade";
String option2 = "BTEC Extended Diploma Grade";
String option3 = "Functional Skills";
String option4 = "Help"; //assigning text to variable
String option5 = "Exit"; //assigning text to variable
String outline = "+-----------------------------------------------+";
System.out.println(outline);
System.out.println("| |1| "+option1+ " |");
System.out.println("| |2| "+option2+ " |");
System.out.println("| |3| "+option3+ " |");
System.out.println("| |4| "+option4+ " |");
System.out.println("| |5| "+option5+ " |");
System.out.println(outline);
coursename = two.next();
System.out.println("Answer entered was " + ?); //? represents not sure what to put.
}
}
答案 0 :(得分:1)
Scanner#nextInt()可以解决问题。
要获得该号码,请执行以下操作:
int num = input.nextInt();
获得号码后即可使用
if (num == 1) { System.out.println(option1); }
选项一。继续您的所有选择。因为您知道与每个选项对应的数字,所以不需要循环。
答案 1 :(得分:0)
要么for
循环,要么将选项文本存储在按下的键的Map
中,以便选择它。
如果您将它们放入LinkedHashMap
,您也可以在for
循环中打印它们,而不是为每个选项手动执行此操作。
Map<Integer, String> options = new LinkedHashMap<>();
options.put(1, "BTEC 90 Credit Diploma Grade");
...
for (Entry<Integer, String> entry : options.entrySet()) {
System.out.println(
"| |" + entry.getKey().toString() + "| "
+ entry.getValue() + repeat(" ", 40 - entry.getValue().length())
+ "|"
);
}
...
Integer choice = input.nextInt();
System.out.println("Answer entered was " + options.get(choice));