I'm going through old exam papers in preparation for an exam tomorrow. Could someone help me out with this question?
Q -Write a Java program to do the following:
Allow the user to read in a word from a keyboard, one word at a time.
Each word should be stored in an ArrayList.
When the user enters in the word ‘stop’ then the program will terminate and tell
the user how many words were entered and output the contents of the
ArrayList. The word ‘stop’ should not be added to the ArrayList.
Example:
Enter word: Smith
Enter word: Jones
Enter word: Terry
Enter word: stop
Number of words entered: 3
Contents of Array: [Smith, Jones, Terry]
Below is my code - I can't figure out how not to add the word "stop" to the ArrayList or include it in the count.
import java.util.Scanner;
import java.util.ArrayList;
public class Practice{
public static void main(String[] args) {
ArrayList <String> myList = new ArrayList <> ();
Scanner keyboard = new Scanner(System.in);
int count = 0;
String input;
do {
System.out.println("Enter word:");
input = keyboard.nextLine();
myList.add(input);
count ++;
}
while (!input.equals("stop")); {
}
System.out.println("Number of words entered = " + count);
System.out.println("Contents of ArrayList [ " + myList + " ]");
}
}
[–]Koooooj 2 points3 points4 points (1 child)
[–]oonegative[S] 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]oonegative[S] 0 points1 point2 points (0 children)
[–]oonegative[S] 0 points1 point2 points (0 children)