简体   繁体   English

为双变量赋值的输入

[英]Input to assign value to double variable

I'm trying to get it where the user inputs a 1 or 2 for a predetermined values.我试图在用户为预定值输入 1 或 2 的地方得到它。 Then using that to calculate a final cost.然后使用它来计算最终成本。

Example: Would you like the red or orange box?示例:您想要红色还是橙色的盒子? 1 for red, 2 for orange 1 代表红色,2 代表橙色

The red would cost $10 and the orange $12.红色售价 10 美元,橙色售价 12 美元。

How do I connect the inputs 1 and 2 to $10 and $12?如何将输入 1 和 2 连接到 10 美元和 12 美元? Do I use switch or if?我是使用 switch 还是 if?

Both options work.这两个选项都有效。 I personally prefer using the switch statement as it makes the code a bit more readable.我个人更喜欢使用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");

    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM