【发布时间】:2021-06-27 00:57:38
【问题描述】:
我正在制作我创建的“项目”类型的 ArrayList。该类有一个名为name 的变量来描述该项目。这些项目存储在一个 ArrayList 中。
我不知道如何引用 name 变量,因为它在编译器中产生了一个错误,上面写着 cannot find symbol - variable name. 具体来说,我这样引用它:
for (int i=0; i < theMenu.size(); i++) {
Item temp = theMenu.get(i);
if(temp.name == keyword)
System.out.println("test");
}
我也试过这样引用它:
for (int i=0; i < theMenu.size(); i++) {
if(theMenu.get(i).name == keyword)
System.out.println("test");
}
它会产生同样的错误。请帮忙!以下是相关代码:
import java.util.ArrayList;
import java.util.Scanner;
public class Doms {
public static class Item {
public Item(int itemID, String itemName, double itemPrice, double itemSalePrice, String itemSaleBeginDate, String itemSaleEndDate, ArrayList<Integer> itemReviews, ArrayList<String> itemComments) {
int id = itemID;
String name = itemName;
double price = itemPrice;
double salePrice = itemSalePrice;
String SaleBeginDate = itemSaleBeginDate;
String SaleEndDate = itemSaleEndDate;
ArrayList<Integer> reviews = itemReviews;
ArrayList<String> comments = itemComments;
}
}
public static void main(String[] args) {
// A list containing each Item and all of its contents
ArrayList<Item> items = new ArrayList<Item>();
// Create Item elements
ArrayList<Integer> reviews2 = new ArrayList<Integer>();
ArrayList<String> comments2 = new ArrayList<String>();
Item item2 = new Item(2, "Sour Cream Donut", 1.29, 1.29, "", "", reviews2, comments2);
items.add(item2);
//This part doesn't work
for (int i=0; i < theMenu.size(); i++) {
Item temp = theMenu.get(i);
if(temp.name == keyword)
System.out.println("test");
}
}
}
【问题讨论】:
-
类
Item没有任何字段(成员变量)。您的构造函数只是将所有参数分配给 局部变量,一旦构造函数返回,这些参数将不再存在。重新阅读您的 Java 学习指南,了解如何在构造函数中声明 字段 并分配给它们。参见例如The Java™ Tutorials - Declaring Member Variables 的一个类的示例,其中的字段在构造函数中分配。 -
如果你在比较字符串,你需要使用equals()而不是==。
标签: java variables arraylist types reference