我有一个挑选课程,为你挑选衣服,这取决于你外出的原因和今天是什么样的一天。
我正在尝试完成选择器方法,该方法决定要在每个ArrayList索引上分配哪些服装。服装是它自己的一类,它有字符串品牌、字符串颜色和布尔形式字段。
在选择方法中,我想做的是
outfit.add(jeans);但是它给了我一个空指针异常,这是不应该的,因为我在构造函数中定义了牛仔裤,所以我尝试这样做。
outfit.add(picker.jeans);
并给出了“非静态字段‘牛仔裤’不能从静态上下文引用”的错误。
该方法使用静态布尔变量,因此我尝试通过旋转来修复它。
public class picker {
static boolean formalEvent;
static boolean niceWeather;
static boolean specialDay;
static boolean workingOut;转到
public class picker {
boolean formalEvent;
boolean niceWeather;
boolean specialDay;
boolean workingOut;但是它仍然不起作用,也许我一开始就不应该使用这些静态的,但是它让我的主要方法起作用了,我根据用户输入的扫描程序来定义它们,而我也把它变成了静态的。我的老师说,如果你不需要多次使用静态的话。我只需要一台扫描仪。
在我的代码开始到构造函数之前,我可能会让构造函数问用户有什么样的裤子、运动裤、衬衫等等,所以它并不总是一个定义好的衣柜。
import java.util.ArrayList;
import java.util.Scanner;
public class picker {
boolean formalEvent;
boolean niceWeather;
boolean specialDay;
boolean workingOut;
ArrayList<clothing> outfit = new ArrayList<>();
static Scanner scnr = new Scanner(System.in);
clothing khakis;
clothing jeans;
clothing shorts;
clothing sweatpants;
clothing sweatshirt;
clothing gymShirt;
clothing workShirt;
clothing designerShirt;
/**
* Picker constructor.
*/
public picker() {
clothing khakis = new clothing("Levi", "brown", true);
clothing jeans = new clothing("Mike Amiri", "blue", false);
clothing shorts = new clothing("Nike", "blue", false);
clothing sweatpants = new clothing("Adidas", "black", false);
clothing sweatshirt = new clothing("Old navy", "red", false);
clothing gymShirt = new clothing("Nike", "grey", false);
clothing graphicTee = new clothing("Mike's Paving Posse", "black", false);
clothing workShirt = new clothing("Polo", "yellow", true);
clothing designerShirt = new clothing("Supreme", "red", false);
}我主要方法的开始如下所示
public static void main(String[] args) {
picker todaysFit = new picker();
String response = "";
System.out.println("Are you going to a formal event?");
response = scnr.next();
if (response.equalsIgnoreCase("yes")) {
formalEvent = true;而现在
formalEvent = true;在formalEvent获取一个错误,指出“不能从静态上下文引用非静态字段'formalEvent‘”。我试着做了
picker.formalEvent = true;来修复它,但仍然会产生相同的错误。
发布于 2020-04-01 21:15:33
您已经在构造函数中声明和初始化了局部变量,隐藏了数据成员。删除类型声明以实际初始化成员:
public picker() {
khakis = new clothing("Levi", "brown", true);
jeans = new clothing("Mike Amiri", "blue", false);
shorts = new clothing("Nike", "blue", false);
sweatpants = new clothing("Adidas", "black", false);
sweatshirt = new clothing("Old navy", "red", false);
gymShirt = new clothing("Nike", "grey", false);
graphicTee = new clothing("Mike's Paving Posse", "black", false);
workShirt = new clothing("Polo", "yellow", true);
designerShirt = new clothing("Supreme", "red", false);
}发布于 2020-04-01 21:15:59
您需要在构造函数中将变量声明为静态变量。但是要遵循良好的实践,您应该在构造函数中创建一个方法来修改值,例如:
public changeShirt(clothing newShirt){
this.shirt = newShirt
}您将在todaysFit对象上调用此方法
https://stackoverflow.com/questions/60980337
复制相似问题