'How can I fix the startsWith() error of java
I cannot figure out the startsWith(str) in the while loop below have the error The method startsWith(String) is undefined for the type InfoProcessor.
I want to get the String that follows the line that starts with the given String (str).
It is great pleasure to have your help.
import java.util.*;
public class InfoProcessor {
private ArrayList<String> lines = new ArrayList<String>();
public InfoProcessor(ArrayList<String> lines) {
this.lines = lines;
}
String getNextStringStartsWith(String str) {
for (int i = 0 ; i < lines.size(); i++){
Scanner scanner = new Scanner(lines.get(i));
while (startsWith(str)){
String hobby = scanner.nextLine();
String[] tokens = hobby.split("\\s+");
return tokens[1];
}
}
return null;
}
Solution 1:[1]
You are trying to invoke a String method but you are not invoking it on a String. Therefore, the compiler interprets your attempt as invoking the method on this class. This class does not implement that method so the method is undefined. In your case, you want to invoke that method on an individual line to see if it contains the prefix.
public String findWordAfterPrefix(String prefix) {
for (String line : lines) { // iterate over the lines
if (line.startsWith(prefix)) { // does the line start with the prefix?
/// find the next word and return it - that is a separate issue! ;)
}
}
return null; // return null if we never found the prefix
}
p.s. You may find some other String method useful as you pull out the next word (e.g. trim(), substring(int).
Solution 2:[2]
The error means exactly what it says: there is no startsWith() method in your InfoProcessor class.
You may have intended str.startsWith(...) instead of startsWith(str).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vsfDawg |
| Solution 2 | jsheeran |
