0

I have an array list:

ArrayList<String> allText = new ArrayList<String>();

its content is like this:

[Alabama - Montgomery, Alaska - Juneau, Arizona - Phoenix, Arkansas - Little Rock, California - Sacramento, Colorado - Denver]

How can i split it into 2 array list such as:

List<String> states = new ArrayList<>(); : [Alabama, Alaska, Arizona, Arkansas]

List<String> capitals = new ArrayList<>(); : [Montgomery, Juneau, Phoenix, Little Rock]

I have this but it doesn't work, it gives me an error on allText (Scanner scanner = new Scanner(allText);) it wants a string and not an arraylist :

 Scanner scanner = new Scanner(allText);

    List<String> states = new ArrayList<>();
    List<String> capitals = new ArrayList<>();

    while (scanner.hasNextLine()) {
        String[] parts = scanner.nextLine().split(" - ");
        states.add(parts[0]);
        capitals.add(parts[1]);
    }
john
  • 65
  • 3

3 Answers3

1

it gives me an error on allText (Scanner scanner = new Scanner(allText);) it wants a string and not an arraylist

Since you are passing ArrayList object to Scanner. But there no such constructor.

Scanner

    for(String str:allText)
    {
    String[] parts = str.split(" - ");
    states.add(parts[0]);
    capitals.add(parts[1]);
    }

Need for loop to to iterate allText. Since its a List.

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
0

You are trying to use a Scanner to go through all the elements in a List. A Scanner only works on a single String, not a list of them since that has a type of List<String> and not String. What you want to do is loop over the elements in the list:

for(String stateAndCapital : allText){
    String[] parts = stateAndCapital.split(" - ");
    states.add(parts[0]);
    capitals.add(parts[1]);
}
0

I would use String.split(String) (where the argument is a regular expression, \\s+ is one or more whitespace. If it should be optional whitespace you could use \\s*). Then add the capital and state to it's respective list. Then I would display both with formatted IO. And with Java 7+ you can use the diamond operator. Something like

List<String> allText = Arrays.asList("Alabama - Montgomery",
        "Alaska - Juneau", "Arizona - Phoenix",
        "Arkansas - Little Rock", "California - Sacramento",
        "Colorado - Denver");
List<String> states = new ArrayList<>();
List<String> capitals = new ArrayList<>();
for (String both : allText) {
    String[] arr = both.split("\\s+-\\s+");
    states.add(arr[0]);
    capitals.add(arr[1]);
}
for (int i = 0; i < states.size(); i++) {
    String state = states.get(i);
    String capital = capitals.get(i);
    System.out.printf("The capital of %s is %s%n", state, capital);
}
Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249