Java 如何在循环中使用此集合方法

Java 如何在循环中使用此集合方法,java,arrays,Java,Arrays,这是一个家庭作业的问题,所以我想写尽可能多的代码,只需要一个指针 我有一个名为“三明治”的类,它有一个方法来设置主要成分和其他一些东西- public class Sandwich { private String mainIngredient, bread; String getMainIngredient(){ return mainIngredient; } void setMainIngredient(String mainIng){ mainIngred

这是一个家庭作业的问题,所以我想写尽可能多的代码,只需要一个指针

我有一个名为“三明治”的类,它有一个方法来设置主要成分和其他一些东西-

public class Sandwich {

private String mainIngredient, bread;


String getMainIngredient(){
    return mainIngredient;
    }

void setMainIngredient(String mainIng){
    mainIngredient = mainIng;
}

 void setBread(String dough){
    bread = dough;
}


 void setPrice(double cost){
    price = cost;
}
现在在另一个类
TestSandwich
中,作为问题的一部分,我初始化了一个数组

Sandwich[] sandwiches = new Sandwich[5];
现在我需要做的是循环,每次都给主要配料和面包赋值。 我想我会按照这条思路做一些事情,但我真的不确定如何正确地做

for(int i = 0; i < 5; i++){

        System.out.println("Insert a main ingredient");
        String userInput = sc.next();

        sandwiches[i].setBread(userInput);

        System.out.println("Insert a bread");
        userInput = sc.next();

        sandwiches[i].setMainIngredient(userInput);


        System.out.println(sandwiches[i].getMainIngredient());
        System.out.println("");

}
for(int i=0;i<5;i++){
System.out.println(“插入主要成分”);
字符串userInput=sc.next();
三明治[i].setBread(用户输入);
System.out.println(“插入面包”);
userInput=sc.next();
三明治[i].SetMain配料(用户输入);
System.out.println(三明治[i].getMainComponent());
System.out.println(“”);
}
主要问题是-
sandwiches[i].setMainComponent(userInput)
我对这些数组和方法并没有真正的经验,所以任何关于正确语法的帮助都是非常好的


谢谢

三明治[]三明治=新三明治[5]
创建一个包含5个
null
引用的数组

您需要自己初始化每个元素;在循环中写入

sandwiches[i]=新三明治()

否则您将得到
NullPointerException
s。完成后,可以像当前一样调用设置方法。接下来,您可以声明一个以面包和主要成分为参数的双参数构造函数。这是一种更好的样式,因为(i)避免了setter,并且(ii)对象在构造和使用之间处于定义不清的状态

这将分配一个数组来容纳5个三明治,但它不会创建任何三明治。只是阵列。在循环中创建三明治是正确的

编写此循环时,最好使用
sandwiches.length
,而不是迭代到5,这样,如果您想要10而不是5个三明治,则可以在一个位置而不是2处更改数字。它将更安全,更不容易出错:

for (int i = 0; i < sandwiches.length; ++i) {
    // TODO: get the ingredients from user

    // ready to create the sandwich, yum yum
    Sandwich sandwich = new Sandwich();
    sandwich.setBread("...");
    sandwich.setMainIngredient("...");
    sandwiches[i] = sandwich;
}
for(int i=0;i
问题出在哪里?您是否尝试过执行代码?是的。忘了包括那个,对不起。在请求主成分后插入内容后,它在testsandwich.testsandwich.main(testsandwich.java:24)的线程“main”java.lang.NullPointerException中给我-
异常,java结果:1
第24行是
三明治[I].setBread(用户输入)谢谢,这很有帮助!我会的,听起来很有趣!
for (int i = 0; i < sandwiches.length; ++i) {
    // TODO: get the ingredients from user

    // ready to create the sandwich, yum yum
    Sandwich sandwich = new Sandwich();
    sandwich.setBread("...");
    sandwich.setMainIngredient("...");
    sandwiches[i] = sandwich;
}