简体   繁体   中英

Taking user input and adding it an array

My program uses an array: collection[] to hold information on cars. user input is used to add a car to the array using the console. So the user would enter the car's name, year of make, etc. However when it gets added to the array it goes straight into collection[0] . So if there is anything already in collection[0] it will replace it.

I want the user input to be but into the the next null cell in the array to avoid this problem. I have tried to write code that goes through each cell of the array and once it finds a cell which is null it then adds the information into it. However it is not working.

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

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

Here is a shortened version of addCarInput :

Scanner sin = new Scanner(System.in);

System.out.print("Enter car make: ");
Cmake = sin.nextLine();

System.out.print("Enter car model : ");
Mname = sin.nextLine();

You can try something like this if you want more cars

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()
}

Why don't you use a LinkedList or an ArrayList object instead of an array? the add() method will add the elements at the end of the list & not replace the old values

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

https://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

http://examples.javacodegeeks.com/core-java/util/arraylist/arraylist-in-java-example-how-to-use-arraylist/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM