[英]How can I get my userinput to access my ArrayList when I pass it to a method
Here's the code I have so far. 这是我到目前为止的代码。 This is the error I get for line 58
这是我在第58行得到的错误
incompatible types required: ArrayList found:
要求的类型不兼容:找到ArrayList:
VendProduct供应产品
(Alt-Enter shows hints) (Alt-Enter显示提示)
//A vending machine to dispense multiple products //可分配多种产品的自动售货机
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
is an ArrayList of VendProduct, but you're trying to set it to just one VendProduct... vp
是VendProduct的ArrayList,但是您试图将其设置为仅一个VendProduct。
You should create a variable of the type VendProduct
and use that, like this: 您应该创建
VendProduct
类型的变量,并使用它,如下所示:
VendProduct product = vp.get(userInput-1);
product.buyProduct();
You could also do vp.get(userInput-1).buyProduct();
您也可以执行
vp.get(userInput-1).buyProduct();
directly in one line. 直接在一行中。 That's up to you.
随你(由你决定。 Using two lines usually makes the code a bit cleaner and easier to read.
通常使用两行代码会使代码更清晰,更易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.