Megan Sime
Megan Sime

Reputation: 1267

.split() method in Java not found

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.

Upvotes: 2

Views: 8043

Answers (4)

Arefe
Arefe

Reputation: 12461

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

Upvotes: 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")

Upvotes: 1

Vlad Schnakovszki
Vlad Schnakovszki

Reputation: 8601

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);
    }
}

Upvotes: 2

RMachnik
RMachnik

Reputation: 3694

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.

Upvotes: 9

Related Questions