基本上我需要在做出选择时传递价格并且不知道如何。
int selection;
String[] snacks = { " (1): Chewing Gum", " (2): Kit Kat", " (3): Snickers", " (4): Pop Tarts" };
int[] price = { 40, 75, 80, 90 };
System.out.println("Java Vending Machine");
for (int index = 0; index < snacks.length; index++) {
System.out.println(snacks[index] + " -- " + price[index] + "¢");
}
Scanner keyboard = new Scanner(System.in);
selection = keyboard.nextInt();
return selection;
答案 0 :(得分:1)
如果我理解你的问题,你只需要
// return selection;
return (selection > 0 && selection <= price.length) ? price[selection-1] : 0;
另一个例子,
// That ternary could also be written as
if (selection > 0 && selection <= price.length) {
return price[selection-1];
}
return 0;