2

这是我到目前为止的代码。这是我在第 58 行得到的错误

需要不兼容的类型:找到 ArrayList:
VendProduct

(Alt-Enter 显示提示)

//一台自动售货机分配多种产品

package newvendingmachine;

import java.util.ArrayList;
import java.util.Scanner;

//Tony Moore 

public class NewVendingMachine{
    //Set class data
    static String[] product = {"Chips", "M&Ms", "Peanuts", "Popcorn", "Snickers"};
    static Float[] cost = {.50f, .75f, .75f, .75f, .90f};
    static Integer[] inventory = {20, 20, 20, 20, 20};

    /** 
    * @param args the command line arguments
    */
    public static void main(String[] args) {
        ArrayList<VendProduct> vp = new ArrayList<>();
        for (int idx=0; idx<product.length; idx++) {
            vp.add(new VendProduct());
        }

        //Accept user input
        Scanner input = new Scanner(System.in);   
        int userInput;

        while (true) {
            // Display menu graphics

            System.out.println(" Options: Press your selection then press enter ");
            System.out.println(" 1. "+product[0]+" ");
            System.out.println(" 2. "+product[1]+" ");
            System.out.println(" 3. "+product[2]+" ");
            System.out.println(" 4. "+product[3]+" ");
            System.out.println(" 5. "+product[4]+" ");
            System.out.println(" 6. Quit ");


            userInput = input.nextInt(); 

            if (userInput <1 || userInput >6) {
                System.out.println("Please make a vaild selection");    
            }

            if (userInput >=1 || userInput <=6) {
                vp = (VendProduct)vp.get(userInput-1);
                vp.buyProduct();         
            }

            if (userInput == 6) {
                System.out.println("Thanks, and come back soon");
                break;
            }
        }   
    }
}
4

1 回答 1

0

vp = (VendProduct)vp.get(userInput-1);

vp是 VendProduct 的 ArrayList,但您试图将其设置为仅一个 VendProduct...

您应该创建一个类型的变量VendProduct并使用它,如下所示:

 VendProduct product = vp.get(userInput-1);
 product.buyProduct();

您也可以vp.get(userInput-1).buyProduct();直接在一行中进行。这取决于你。使用两行代码通常会使代码更简洁、更易于阅读。

于 2012-12-02T22:24:36.123 回答