2

I have to create the following program:

Create a program that allows you to type names. The names that the user types and submits (with the enter key) should be stored in an arraylist. The names in the arraylist should then be printed on the screen.

My problem is that I've only been able to only store one name in my arraylist.

My code:

ArrayList <String> namen = new ArrayList <>();        
System.out.print("Enter a name: ");        
Scanner in = new Scanner(System.in);        
namen.add(in.next());        
for (String naam: namen) {
    System.out.println(naam);
}

The first problem is that after one name has been typed and submitted, you can't type anything, so I have to reset the input like with integer values:

if (varOne > varTwo) {
    System.out.println("Too high!");
    varOne = raadGetal.nextInt();
}

The varOne = raadGetal.nextInt(); line resets the input, so you can type again. But how do I achieve the same thing with the code above, with Strings and an arraylist?

7 Answers 7

1

You always declare ArrayList<String> namen = new ArrayList<>(); after that it is an empty list. Try something like this:

public class MyClass {
    private ArrayList<String> namen = new ArrayList<>();

    public void addName(){
        System.out.print("Enter a name: ");
        Scanner in = new Scanner(System.in);
        namen.add(in.next());

        for(String naam: namen){
            System.out.println(naam);
        }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

The ArrayList definition in the OP's program is correct. He's using the diamond operator (<>) on the right hand side which was introduced with Java 7.
But that list is empty afterwards, so it contains only one name and the OP want it to have more names in it.
0

Comparison operator > is not supported by String. Use compareTo method to compare String value.

if(varOne.compareTo(varTwo)>0) {
System.out.println("Too high!");
varOne = raadGetal.nextInt();
}

1 Comment

varOne is being read as int as the OP mentioned: varOne = raadGetal.nextInt(); in his question
0

The problem isn't your ArrayList, it's the Scanner usage. If you want to ask for multiple names, use a loop.

for(int i = 0; i < NUMBER_OF_NAMES_TO_GET; i++){
    namen.add(in.next());
}

4 Comments

Thank you very much! This snippet did the job! Only one little question, how can I let the user input unlimited names? As far as I know a while loop is for running code when you don't know when the loop should stop. Can you help me with something like that?
@user2793161 you are absolutely right about the usage of a while loop. You can say something like while (!namen.contains("exit")) instead of the for loop. This will quit once someone types "exit", keep in mind that you should then remove the exit name from the namen list.
Okay thanks a lot Ron! It works perfectly now. The assignment was that when a user enters an empty string, the loop should stop and the last inputted value before the empty string should be removed.
@user2793161 You're welcome, you should upvote/accept answers so others can find the best solution too!
0

You can ask the user first the number of names he wants to give

int noOfNames = in.nextInt();

and then based on this you can create a loop to store all the names

for(int i = 0; i <noOfNames ; i++){
    names.add(in.next());
}

Comments

0

Try calling it in the loop. Its just executing once. try the below:-

import java.util.ArrayList; import java.util.Scanner;

public class addName {

private void name() {
    ArrayList<String> namen = new ArrayList<String>();

    int count = 1;

while(count>0){
    System.out.print("Enter a name: ");
    Scanner in = new Scanner(System.in);
    String a = in.next();
    namen.add(a);
    if (a.equals("exit")) {
        System.out.println("Exiting");
        System.exit(0);
    }
    else{
        for (String naam : namen) {
                System.out.println(naam);
    }
    }
    count++;
}
}

public static void main(String[] args) {
    addName addNames = new addName();
    addNames.name();
}

}

Comments

0

Lutz, You can write/modify your code as follows:
please note that you should always use String.equals() method for checking the equality of two Strings.

import java.util.ArrayList;
import java.util.Scanner;

public class AddNames {

public static void main(String[] args) {

    ArrayList<String> namen = new ArrayList<String>();
    System.out.print("Enter a name(or write exit to close the program) : ");
    Scanner in = new Scanner(System.in);
    String name = in.next();
    while (!name.equals("exit")) {

        namen.add(name);
        name = in.next();
    }
    if (name.equals("exit")) {
        System.out
                .println("Exiting the program. The names you have entered are:");
        for (String naam : namen) {
            System.out.println(naam);
        }
    }
}
}

Comments

0

Modern Java

Let's use the features of modern Java.

For mere text, you do not need the parsing abilities of Scanner. Just use IO in Java 25+.

To loop indefinitely, use while loop. Wait for user to enter some special text such as "quit", then break.

If the user enters an invalid value, use continue to skip to the next loop.

Store results in a sequenced collection such as ArrayList.

Tell the forEach method to repeated call a method reference IO :: println.

SequencedCollection < String > names = new ArrayList <>();
String input = "";
while ( ! input.equals( "quit" ) )
{
    input = IO.readln( "Enter name or 'quit': " );
    if ( input.equalsIgnoreCase( "quit" ) ) break; // `break` exits` the loop entirely, jumping to the code immediately after the loop body.
    if ( input.isBlank() )
    {
        IO.println( "Invalid input." );
        continue; // `continue` skips` the remaining code in the current iteration and jumps back to the top of the loop for the next one. The loop doesn't end; it just advances.
    }
    names.add( input );
}
IO.println( "Names entered: " );
names.forEach( IO :: println );
IO.println( "Done." );

When run.

Enter name or 'quit': Alice
Enter name or 'quit': Bob
Enter name or 'quit':     
Invalid input.
Enter name or 'quit': Carol
Enter name or 'quit': quit
Names entered: 
Alice
Bob
Carol
Done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.