I have just started studying Computer Science, and we have just started our first Java project. It is a information system that should keep tracks of our friends.
I have made an arraylist where I can put in some interests that our friends have. The problem is that I can easily enter blank spaces and just press enter to insert an "empty" element into the array list. I have tried using different methods to remove them from the array list, and haven't come to an answer. Under here is the code that I am stuck with.
I have set the program to exit when I enter "exit", and that works perfectly fine. At the start when I typed in "exit", then the program would include the "exit" into the array, but after I added the checklist()
method, I was able to keep "exit" out of the array list. I just can't seem to make it work with spaces and Enters.
package testing;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
ArrayList<String> interests = new ArrayList<String>();
String interest;
String quit = "exit";
do {
Scanner userInput = new Scanner(System.in);
System.out.println("Write interest: ");
interest = userInput.nextLine();
if (interest.isEmpty()) { // Makes sure you cant press ENTER.
System.out.println("You just entered SPACE, please write an interest: ");
interest = userInput.nextLine();
} else if (interest.isBlank()) { // Makes sure you cant enter a plain space.
System.out.println("You just entered a plain space, please write an interest: ");
interest = userInput.nextLine();
}
interests.add(interest);
} while (!interest.equals(quit));
checkList(interests);
System.out.println(interests);
}
public static void checkList(ArrayList<String> interests) {
String quit = "exit";
for (int i = 0; i < interests.size(); i++) {
if(interests.get(i).isBlank()) {
interests.remove(i);
System.out.println("Position: " + i + " is a blank space");
System.out.println("Removed blank space: " + interests.get(i));
} else if (interests.get(i).isEmpty()) {
interests.remove(i);
System.out.println("Position: " + i + " is a ENTER");
System.out.println("Removed ENTER: " + interests.get(i));
} else if (interests.get(i).equals(quit)) {
interests.remove(i);
}
}
}
}