输入以将值赋值给double变量

时间:2015-09-17 23:39:56

标签: java

我试图在用户为预定值输入1或2的地方获取它。然后用它来计算最终成本。

实施例: 你想要红色或橙色的盒子吗? 1表示红色,2表示橙色

红色售价10美元,橙色售价12美元。

如何将输入1和2连接到10美元和12美元?我是否使用开关或if?

1 个答案:

答案 0 :(得分:0)

两种选择都有效。我个人更喜欢使用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");

    }

}