【发布时间】:2020-07-13 18:15:27
【问题描述】:
我有一个挑选器课程,可以根据你外出的原因和当天的情况为你挑选衣服。
我正在尝试完成选择器方法,该方法决定在每个 ArrayList 索引处分配哪些衣服。 Clothing 是它自己的类,它具有字符串品牌、字符串颜色和布尔形式字段。
在选择器方法中,我正在尝试做
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);
}
我的 main 方法的开头是这样的
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;
修复它,但它仍然给出同样的错误。
【问题讨论】:
-
仅供参考: Java 类名以大写字母开头的命名约定,因此您的类应命名为
Picker和Clothing
标签: java methods constructor static