[英]How to avoid error like this “This method must return a result of type int”?
import java.util.*;
public class Main
{
public static int countInversions(String a)
{
int res = 0;
int n = a.length();
for (int i = 0; i < n; i++)
{
for (int j = i + 1; j < n; j++)
{
if(a.charAt(i) > a.charAt(j))
res++ ;
}
return res;
}
}
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int m = in.nextInt();
String[] dna = new String[m];
for(int i = 0; i < m; i++)
{
dna[i] = in.next();
}
Arrays.sort(dna, new Comparator<String>() {
@Override
// <0 if a < b, 0 if a == b, > 0 if a > b
public int compare(String a, String b)
{
return countInversions(a) - countInversions(b);
}
});
for (int i = 0; i < n; i++) {
System.out.println(dna[i]);
}
}
}
Just place the return
statement at the very end of the method: 只需将
return
语句放在方法的最后:
public static int countInversions(String a) {
int res = 0;
int n = a.length();
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (a.charAt(i) > a.charAt(j))
res++;
}
}
return res;
}
This will make sure res
is returned even if the string is empty. 这将确保即使字符串为空也返回
res
。
If a
is an empty String
, your method never reaches the return
statement, hence the error. 如果
a
为空String
,则您的方法将永远不会return
语句,因此会出现错误。
You must make sure that your method returns a value in all cases. 您必须确保在所有情况下您的方法都返回一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.