Java 为双变量赋值的输入
我试图在用户输入一个1或2作为预定值的地方得到它。然后用它来计算最终成本 例如: 你想要红色的还是橙色的盒子?1代表红色,2代表橙色 红色的10美元,橙色的12美元Java 为双变量赋值的输入,java,Java,我试图在用户输入一个1或2作为预定值的地方得到它。然后用它来计算最终成本 例如: 你想要红色的还是橙色的盒子?1代表红色,2代表橙色 红色的10美元,橙色的12美元 如何将输入1和2连接到$10和$12?我是使用开关还是if?这两个选项都有效。我个人更喜欢使用switch语句,因为它使代码更具可读性 import java.util.Scanner; public class Untitled { public static void main (String[]args) {
如何将输入1和2连接到$10和$12?我是使用开关还是if?这两个选项都有效。我个人更喜欢使用switch语句,因为它使代码更具可读性
import java.util.Scanner;
public class Untitled {
public static void main (String[]args) {
Scanner s = new Scanner(System.in);
// this is where you store your items - you would obviously have to create the class and its methods first
// ArrayList <Item> items = new ArrayList<>;
// items.Add(new Item(SomePrice, SomeName);
System.out.println("Item 1 or 2");
String input = s.nextLine();
// Option 1
switch(input) {
case ("1"): {
System.out.println("Cost is 1");
// some method to retreive an item from the list of Items carrying the name one
// get user Input
// update the item in the list
break;
}
case ("2"):{
System.out.println("Cost is 2");
break;
}
}
// Option 2
if (input.equalsIgnoreCase("1"))
System.out.println("Cost is 1");
else if (input.equalsIgnoreCase("2"))
System.out.println("Cost is 2");
}
}
两者都会起作用。通常情况下,像这样的菜单选项开关是首选的,但最终它真的没有什么区别。在每种情况下是否可以为变量赋值?我不太明白你的问题,但你可以创建一个ArrayList,然后调用该列表项上的一个方法来获取价格。我已经扩展了代码以给您一些提示。