Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 获取用户输入并将其添加到数组中_Java_Arrays - Fatal编程技术网

Java 获取用户输入并将其添加到数组中

Java 获取用户输入并将其添加到数组中,java,arrays,Java,Arrays,我的程序使用数组:collection[]来保存有关汽车的信息。用户输入用于使用控制台将汽车添加到阵列中。因此,用户将输入汽车的名称、制造年份等。然而,当它被添加到数组中时,它将直接进入集合[0]。因此,如果集合[0]中已有任何内容,它将替换它 我希望将用户输入保存到数组中的下一个空单元格中,以避免此问题。我尝试编写代码,遍历数组的每个单元格,一旦它找到一个空单元格,它就会将信息添加到其中。但是它不起作用 public void addCarInput1() { for (int i =

我的程序使用数组:collection[]来保存有关汽车的信息。用户输入用于使用控制台将汽车添加到阵列中。因此,用户将输入汽车的名称、制造年份等。然而,当它被添加到数组中时,它将直接进入集合[0]。因此,如果集合[0]中已有任何内容,它将替换它

我希望将用户输入保存到数组中的下一个空单元格中,以避免此问题。我尝试编写代码,遍历数组的每个单元格,一旦它找到一个空单元格,它就会将信息添加到其中。但是它不起作用

public void addCarInput1()
{
    for (int i = 0; i < 1; i++)

    if (this.collection[i] = null) 
    {
        this.collection[i].addCarInput();
    }
}

如果你想要更多的车,你可以试试这样的

String shouldContinue = null;
while(true) {
    if (shouldContinue.equals("no")) break;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter car make: ");
    String make = sc.nextLine();

    System.out.print("Enter car model : ");
    String model = sc.nextLine();

    //add car info
    addCarInput(make, model);

    System.out.print("Enter info for another car? : ");
    shouldContinue = sc.nextLine()
}

为什么不使用LinkedList或ArrayList对象而不是数组? add方法将在列表末尾添加元素&而不是替换旧值


集合是如何定义的?Cmake是如何定义的?Mname是如何定义的?同样在if语句ifcollection[i]=null中,我认为您希望使用==而不是=。同样作为惯例,实例名应该以小写字母开头,以防止与类名混淆。另外,在添加任何内容之前,请确保数组足够大。这看起来像是家庭作业,但通常更容易使用ArrayList。
String shouldContinue = null;
while(true) {
    if (shouldContinue.equals("no")) break;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter car make: ");
    String make = sc.nextLine();

    System.out.print("Enter car model : ");
    String model = sc.nextLine();

    //add car info
    addCarInput(make, model);

    System.out.print("Enter info for another car? : ");
    shouldContinue = sc.nextLine()
}