用户输入中的参考类变量

时间:2019-07-12 13:37:10

标签: java

我想知道如何从扫描仪获取用户输入并将其引用到我创建的类变量中。

尽管我有扫描器变量。(Class属性)还是可以的。例如,用户输入字符串“ Hotdog”,然后我可以执行hotdog.price以获取热狗的价格。

import java.util.Scanner;

public class Food {
    public int price;
    public String name;

    public Food (String name, int price) {
        this.price = price;     //Price of Product
        this.name = name;       //Name of Product
        }

        //Returns the price of the food.
        public int foodPrice() {
            return price;
        }

        //Returns the name of the food.
        public int foodName() {
            return Name;
        }

public static void main(String[] args) {

                           //Name      ,    Price   
    Food hotdog = new Food("Hotdog"    ,    $3);
    Food pizza  = new Food("Pizza"    ,     $5);

    system.out.println("Which food do you want to know the price of? Hotdog Or pizza?");

    Scanner sc = new Scanner(System.in);
    foodChoice = sc.nextLine();

    //Now, if the user says "Hotdog". Ok... How do I use that 
    //string to then use hotdog.price to tell the user the cost 
    //is $3. I would love to do foodChoice.price but that doesn't work.

0 个答案:

没有答案