Sig.1855
Sig.1855

Reputation: 23

Arraylist User input

I would greatly appreciate some help with my java code. I am using ArrayLists to store the users favorite type of vehicles. So they will input vehicles until they type "Exit" to get out of the loop. It will then print the array list. Right now, it is only reading every other input. Depending on how many inputs there are, the user might have to type "Exit" twice before it prints the results out. Any help would be greatly appreciated, thank you!

package bacaCCh6Sec8;
import java.util.ArrayList;
import java.util.Scanner;
public class BacaCCh6Sec8 {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    ArrayList<String> vehicles = new ArrayList<>();
    boolean done = false; 
    final String EXIT = "Exit";
    System.out.printf("Enter your favorite vehicles.\n");
    System.out.printf("Type Exit after you have input all your vehicles.\n");
    do {
        String input = in.next();
        if (!input.equals(EXIT)) {
            vehicles.add(in.next());
        } else {
            done = true;
        } // end If
    } while (!done); // End Do While
    System.out.printf("Your favorite vehicles are %s.\n" , vehicles);

    } // End Main
} // End Class

Upvotes: 0

Views: 151

Answers (3)

Ousmane D.
Ousmane D.

Reputation: 56423

the user might have to type "Exit" twice before it prints the results out

the issue is that you're calling next() method twice hence the user must enter a value twice. the solution is to simply use the value you've got from the first next() method rather than discarding it.

String input = in.next();
if (!input.equals(EXIT)) {
     vehicles.add(input); // <--- we're using the input variable
} else {
      done = true;
} // end If

Upvotes: 1

Yussef
Yussef

Reputation: 610

    public static void main(String[] args) {
            Scanner in = new Scanner(System.in);
            ArrayList<String> vehicles = new ArrayList<>();
            boolean done = false; 
            final String EXIT = "Exit";
            System.out.printf("Enter your favorite vehicles.\n");
            System.out.printf("Type Exit after you have input all your vehicles.\n");
            do {
                String word = in.next();
                if(word.equalsIgnoreCase("exit")) break;

                vehicles.add(word);

            } while (!done); // End Do While
            System.out.printf("Your favorite vehicles are %s.\n" , vehicles);
     }
}

Well not my best code but it helped

Enter your favorite vehicles.
Type Exit after you have input all your vehicles.
hola
mundo
exit
Your favorite vehicles are [hola, mundo].

Upvotes: 0

opensam
opensam

Reputation: 368

Each call of .next() actually reads the input. So if you call .next() twice, it'll read two lines. To rectify change vehicles.add(in.next()); to vehicles.add(input);

Upvotes: 0

Related Questions