![](/img/trans.png)
[英]When I want my threads to share an ArrayList, where do I instantiate the ArrayList, and how do I access it from the main method?
[英]How can I get my userinput to access my ArrayList when I pass it to a method
這是我到目前為止的代碼。 這是我在第58行得到的錯誤
要求的類型不兼容:找到ArrayList:
供應產品
(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;
}
}
}
}
vp = (VendProduct)vp.get(userInput-1);
vp
是VendProduct的ArrayList,但是您試圖將其設置為僅一個VendProduct。
您應該創建VendProduct
類型的變量,並使用它,如下所示:
VendProduct product = vp.get(userInput-1);
product.buyProduct();
您也可以執行vp.get(userInput-1).buyProduct();
直接在一行中。 隨你(由你決定。 通常使用兩行代碼會使代碼更清晰,更易於閱讀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.