2

I am doing a TextReader() class in Java for an assignment, and I am trying to separate a String by any whitespaces, like so:

 String[] splitString;

 while (readLine != null) {
   //assign each word to an array

   splitString = splitString.split("\\s+");

}

however, I get the error "cannot find symbol split()" i've looked at some previous questions and nothing has worked.

Stefan Freitag
  • 3,578
  • 3
  • 26
  • 33
Megan Sime
  • 1,257
  • 2
  • 16
  • 25

4 Answers4

9

Your splitString should be a String object to use split. Be sure that you have that declaration of it

String splittString = readLine.toString();
String[] splittedStringsArray = splittString.split('\\s+');

String split reference.

RMachnik
  • 3,598
  • 1
  • 34
  • 51
2

The problem is that your splitString variable should be a String which you could split, but you have declared it as a String[]. Assuming you are using a Scanner object scanner (wild guess since you're reading using a while loop), what you probably want to do is:

ArrayList<String> splitString = new ArrayList<String>();
while (scanner.hasNextLine()) {
    for (String s : scanner.nextLine().split("\\s+")) {
        splitString.add(s);
    }
}
Vlad Schnakovszki
  • 8,434
  • 6
  • 80
  • 114
1

split() is a method that belongs to the String class. Your splitString is an array o Strings, therefore it cannot as a whole use the split() method. For that to work you would have to use something like splitString = splitString[0].split("\\s")

1

This is the same happen to me just now. I start a new Kafka stream app with the maven. The command is here,

$ mvn archetype:generate \
    -DarchetypeGroupId=org.apache.kafka \
    -DarchetypeArtifactId=streams-quickstart-java \
    -DarchetypeVersion=2.0.0 \
    -DgroupId=streams.examples \
    -DartifactId=streams.examples \
    -Dversion=0.1 \
    -Dpackage=myapps

I get a code snippet like this auto-generated,

builder.stream("streams-plaintext-input")
                .flatMapValues(value -> Arrays.asList(value.split("\\W+")))
                .to("streams-linesplit-output");

This shows an error Cannot Resolve Method split(java.lang.String). Obviously, the split method belongs to the String class and hence, I had it to chnage as following,

builder.stream("streams-plaintext-input")
                .flatMapValues(value -> Arrays.asList(value.toString().split("\\W+")))
                .to("streams-linesplit-output");

I'm curious why the maven archetypes provide a wrong code snippet. I'm talking about the Java 8

Arefe
  • 11,321
  • 18
  • 114
  • 168