错误:不兼容的字符串类型:意外的返回值-这是我返回字符串时代码的错误

时间:2019-03-19 02:25:36

标签: java

您好,我在弄清楚如何调试此代码中的错误时遇到了麻烦。有人请帮忙。 return语句返回不兼容类型的错误。我该如何解决?谢谢!

public class Ex7_19 {
  public static void isSorted(int[] list) {
    String s = "The list is sorted";
    String nS = "The list is not sorted.";
    System.out.print("The list has ");
    System.out.print(list.length);
    System.out.print(" integers ");
    for (int i = 0; i < list.length; i++) {
      System.out.print(list[i] + " ");
    }

    for (int i = 0; i < (list.length - 1); i++) {
      if (list[i] > list[i + 1]) {
        return nS;
      }
    }
    return s;
  }

  public static void main(String[] args) {
    System.out.println("#1");
    isSorted(new int[]{4,7, 19, 21, 44, 98, 101});

    System.out.println("\n#2");
    isSorted(new int[]{4,7, 54, 15, 19, 21, 44, 98, 101});

    System.out.println("\n#3");
    isSorted(new int[]{-2, 0, 3});
  }
}

3 个答案:

答案 0 :(得分:1)

您的方法:

public static void isSorted(int[] list) {

...返回void(无),但是您尝试返回String。

在其余代码中,您似乎打算打印字符串并退出该方法。例如:

public static void isSorted(int[] list) {
    String s = "The list is sorted";
    String nS = "The list is not sorted.";
    System.out.print("The list has ");
    System.out.print(list.length);
    System.out.print(" integers ");
    for (int i = 0; i < list.length; i++) {
        System.out.print(list[i] + " ");
    }

    for (int i = 0; i < (list.length - 1); i++) {
        if (list[i] > list[i + 1]) {
            System.out.println(nS);    // changed here
            return;
        }
    }
    System.out.println(s);             // and changed here
    // no return required here
}

答案 1 :(得分:0)

您的方法无法返回任何内容,因为其返回类型为空。

将void更改为String以返回值。

public static String isSorted(int[] list) {
....
}

答案 2 :(得分:0)

  1. isSorted 方法的返回类型更改为 String
  2. 并在您的main方法中打印返回类型。

检查以下代码

public class Ex7_19 {
      public static String isSorted(int[] list) {
        String s = "The list is sorted";
        String nS = "The list is not sorted.";
        System.out.print("The list has ");
        System.out.print(list.length);
        System.out.print(" integers ");
        for (int i = 0; i < list.length; i++) {
          System.out.print(list[i] + " ");
        }

        for (int i = 0; i < (list.length - 1); i++) {
          if (list[i] > list[i + 1]) {
            return nS;
          }
        }
        return s;
      }

      public static void main(String[] args) {
        System.out.println("#1");
        System.out.println(isSorted(new int[]{4,7, 19, 21, 44, 98, 101}));

        System.out.println("\n#2");
        System.out.println(isSorted(new int[]{4,7, 54, 15, 19, 21, 44, 98, 101}));

        System.out.println("\n#3");
        System.out.println(isSorted(new int[]{-2, 0, 3}));
      }
    }