gpt4 book ai didi

java - 如何避免像 "This method must return a result of type int"这样的错误?

转载 作者:行者123 更新时间:2023-11-30 03:39:17 25 4
gpt4 key购买 nike

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]);
}
}
}

最佳答案

只需将 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;
}

这将确保即使字符串为空,也会返回 res

关于java - 如何避免像 "This method must return a result of type int"这样的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27156158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com