You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java报错:方法中无法找到String?如何修正提供的代码?

Fixing the "Java cannot find the String method" Error in Your Code

Hey there! That error is happening because of a case-sensitive typo in your code—Java takes method names very seriously when it comes to uppercase and lowercase letters.

The Exact Issue

On line 12 of your Solution.java file, you wrote:

String sub=s.subString(0,2);

But the correct method name for extracting a substring from a String in Java is substring (with a lowercase s), not subString. Since Java can't find a method named subString on the String class, it throws the "cannot find method" error.

Corrected Code

Here's the fixed version of your class, with the typo corrected:

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class Solution {
    static String timeConversion(String s) {
        // Fixed: subString → substring
        String sub = s.substring(0,2);
        System.out.println(sub);
        return "test";
    }

    private static final Scanner scan = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
        String s = scan.nextLine();
        String result = timeConversion(s);
        bw.write(result);
        bw.newLine();
        bw.close();
    }
}

Bonus: Implementing Actual Time Conversion (If Needed)

Since your method is named timeConversion, I assume you're trying to convert a 12-hour time format (like "07:05:45PM") to 24-hour format. If that's the case, here's a complete implementation you can use instead of returning "test":

static String timeConversion(String s) {
    String period = s.substring(8);
    String timeWithoutPeriod = s.substring(0, 8);
    String[] timeParts = timeWithoutPeriod.split(":");
    int hour = Integer.parseInt(timeParts[0]);

    if (period.equals("PM") && hour != 12) {
        hour += 12;
    } else if (period.equals("AM") && hour == 12) {
        hour = 0;
    }

    return String.format("%02d:%s:%s", hour, timeParts[1], timeParts[2]);
}

内容的提问来源于stack exchange,提问作者Chanaka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:13:54