Java编译错误:类名与文件名不匹配
Java编译错误:类名与文件名不匹配
如果您遇到以下编译错误信息:
/judger/run/a105d5e78c304f9fb41faa872e67a852/Main.java:3: error: class Solution is public, should be declared in a file named Solution.java
public class Solution {
^
/judger/run/a105d5e78c304f9fb41faa872e67a852/Main.java:26: error: cannot find symbol
System.out.println(sl.func(s));
^
symbol: method func(String)
location: variable sl of type Solution
2 errors
这是因为您的代码中定义了一个名为 'Solution' 的公共类,但该代码保存在名为 'Main.java' 的文件中。根据 Java 的命名规范,公共类的名称必须与其所在的文件名完全一致。
解决方法
要解决此错误,您需要将代码保存在名为 'Solution.java' 的文件中。
以下是修改后的代码示例,请确保将其保存在名为 'Solution.java' 的文件中:
public class Solution {
public static int productionResult(int n) {
int res = 0;
int totalDays = 0;
int i = 1;
for (; totalDays + i <= n; i++) {
res = res + i * i;
totalDays += i;
}
res += i * (n - totalDays);
return res;
}
public static void main(String[] args) {
int result = productionResult(11);
System.out.println('总共可以量产的手机数量为:' + result);
}
}
保存文件后,再次尝试编译和运行您的代码,该错误应该就能得到解决。
原文地址: https://www.cveoy.top/t/topic/D4A 著作权归作者所有。请勿转载和采集!