I am trying to split a user inputed set, such as { 1 2 3 4 }, as a string, into an array list so that when I print out the array list it will read {1, 2, 3, 5}. Here is my code so far. I am not really sure how the Scanner.next() method works, but I am attempting to use it. This is for a small portion of my program. Actually it’s like the beginning.
import java.util.Scanner;
import java.util.ArrayList;
public class practice {
public static void main (String[]args){
Scanner stdIn = new Scanner (System.in);
String set;
String set2 = "";
System.out.print("Enter set:");
set = stdIn.nextLine();
if(set.charAt(0) == '{'){
for(int i =1; i<set.length(); i++){
set2 += set.charAt(i);
}
}
else if(set.charAt(1) == '{'){
for(int i = 2; i <set.length();i++){
set2 += set.charAt(i);
}
}
System.out.print(set2);
ArrayList<Integer> array = new ArrayList<Integer>();
while(stdIn.next() != "}"){
set2 = stdIn.next();
array.add(Integer.parseInt(set2));
}
System.out.print(array);
}
}
You should use the
String.split(String)andString.replaceAll(String, String)methods inStringin order to do a lot of what your code currently does.You can get the user input as you are currently doing it, with
stdIn.nextLine();, but afterward, you can do the string processing in an easier way.First, you should remove the unnecessary characters, and end up with just a sequence of numbers separated by spaces.
You can do this by simply calling the
replaceAllmethod, and provide the regular expression, which is really simple in this case.Then you can call the
String.splitmethod to find each element in the set.UPDATE
If you need to use a scanner, you can use a scanner for the String that has been filtered