简体   繁体   English

如何修复 java 的 startsWith() 错误

[英]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.我无法弄清楚下面的 while 循环中的 startsWith(str) 有错误 The method startsWith(String) is undefined for type InfoProcessor。

I want to get the String that follows the line that starts with the given String (str).我想获取以给定字符串(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;
    }

You are trying to invoke a String method but you are not invoking it on a String.您正在尝试调用 String 方法,但不是在 String 上调用它。 Therefore, the compiler interprets your attempt as invoking the method on this class.因此,编译器会将您的尝试解释为调用此 class 上的方法。 This class does not implement that method so the method is undefined.此 class 未实现该方法,因此该方法未定义。 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
}

ps You may find some other String method useful as you pull out the next word (eg trim(), substring(int). ps 当您提取下一个单词时,您可能会发现其他一些有用的 String 方法(例如 trim()、substring(int)。

The error means exactly what it says: there is no startsWith() method in your InfoProcessor class.该错误的含义正是它所说的: InfoProcessor class 中没有startsWith()方法。

You may have intended str.startsWith(...) instead of startsWith(str) .您可能打算str.startsWith(...)而不是startsWith(str)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM