Java 代码错误:非静态内部类调用静态方法
该代码不能运行的原因是因为在 Solution 类中定义了一个内部类 StringReplacement,但是在 main 方法中却直接调用了 StringReplacement 类的静态方法 replacePlaceholders()。由于 StringReplacement 是 Solution 的内部类,而不是静态内部类,所以不能直接调用静态方法。
解决该问题的方法是将 StringReplacement 类定义为静态内部类,或者将 replacePlaceholders 方法定义为静态方法。以下是修改后的代码:
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param str string字符串 原串
* @param arg char字符型一维数组 需替换数组
* @return string字符串
*/
public static class StringReplacement {
public static String replacePlaceholders(String input, String[] params) {
int paramIndex = 0; // 参数索引
int placeholderIndex = input.indexOf('%s'); // 占位符索引
StringBuilder result = new StringBuilder();
while (placeholderIndex != -1) {
// 将占位符之前的部分添加到结果字符串中
result.append(input.substring(0, placeholderIndex));
// 将参数添加到结果字符串中
result.append(params[paramIndex]);
// 更新索引和参数
input = input.substring(placeholderIndex + 2);
paramIndex++;
placeholderIndex = input.indexOf('%s');
}
result.append(input);
return result.toString();
}
}
public static void main(String[] args) {
String input = "A%sC%sE";
String[] params = { "B", "D" };
String result = StringReplacement.replacePlaceholders(input, params);
System.out.println(result);
}
}
现在代码可以成功运行并输出结果'A%sCB%sDE'。
原文地址: https://www.cveoy.top/t/topic/pbFJ 著作权归作者所有。请勿转载和采集!