Search code examples
javaarraysif-statementcontains

ArrayList with if statements


I am tasked with creating a simple Turing Test using ArrayLists. I know how to create the ArrayLists, but I'm having trouble connecting them to the if statements to respond properly to the user input. An example of this issue is below. When the user inputs Frank I want the first response, and any other input should result in the other response. However, whatever tweaks I make just make one or the other show up no matter what I input.

List<String> names = new ArrayList<>();

names.add( "Frank" );

System.out.print( "Hello, what is your name? ");
names.add(scanner.next());

if( names.contains( "Frank" )) {
    System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
}
else {
    System.out.printf( "What an interesting name. My name is John.\n");
}

**Having another issue. For the second question I'm trying to use an else if statement. However, when I respond with the else if response, it gives me the final else response of "I would have never guessed" every time.

System.out.print("Where are you from? ");
    states.add(scanner.next());

    if (states.contains("Florida") || states.contains("florida")) {
        System.out.println("So was I!\n");
    } else {
    if (states.contains("North Carolina") || states.contains("north carolina")) {
        System.out.println("I hear that's a nice place to live.\n");
    }
    else {
            System.out.println("I would have never guessed!");
        }
    }

Solution

  • Try the following:

    List<String> names = new ArrayList<>();
    
    System.out.print( "Hello, what is your name? ");
    names.add(scanner.next());
    
    if(names.contains( "Frank" )){
        System.out.printf( "Nice to meet you, Frank. My name is John.\n" );
    }else{
        System.out.printf( "What an interesting name. My name is John.\n");
    }
    

    I removed the part where you add Frank to the array. This way the results might be a little different depending on your input. I still find it a little strange that you are using an ArrayList. It seems like just saving a simple variable could do the same thing.

    With an ArrayList it is possible however that you could have previous answers affect other answers.