Cant get this program to run correctly. It won\'t finish the loop when I hit ent
ID: 3571084 • Letter: C
Question
Cant get this program to run correctly. It won't finish the loop when I hit enter. Here is the assigment.
The following code creates a simple ArrayList:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader
(new InputStreamReader(System.in));
ArrayList myArr = new ArrayList();
myArr.add("Zero");
myArr.add("One");
myArr.add("Two");
myArr.add("Three");
}
}
Starting with this provided code, add the following functionality:
Add items to the ArrayList, one at a time, based on user typed input. The user will be prompted for the String to be stored in the ArrayList and then hit enter. The user will be able to continue to add items to the ArrayList until they just hit enter without typing anything.
Once the user does this (hits enter without typing anything), the program will display all of the elements of the ArrayList, both the index and String values, in a table. It will do this via a single loop.
Here is the code I have which won't end the loop and display all the array lists that were input.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
ArrayList myArr = new ArrayList();
System.out.println("Enter items to be saved in array list. Hit enter again to end program.");
while (true){
String s = userInput.readLine();
if (s == null)
break;
myArr.add(s);
}
System.out.println("Index" + " " + "Item");
for (int i = 0; i < myArr.size(); i++) {
System.out.println((i+1) + " " + myArr.get(i));
}
}
Thank you in advance.
Explanation / Answer
Replace the if condition with
if(s.equals(""))break;
//Ex01 class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
class Ex01 {
public static void main(String[] args) throws IOException {
BufferedReader userInput = new BufferedReader(new InputStreamReader(
System.in));
ArrayList myArr = new ArrayList();
System.out
.println("Enter items to be saved in array list. Hit enter again to end program.");
while (true) {
String s = userInput.readLine();
if (s.equals(""))
break;
myArr.add(s);
}
System.out.println("Index" + " " + "Item");
for (int i = 0; i < myArr.size(); i++) {
System.out.println((i + 1) + " " + myArr.get(i));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.