有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我的方法打印null而不是数组?

此代码中可能有什么错误?练习的测试系统抛出以下错误

call to the getIntegers () method printed a value of" null ", but" [1,2,3,4,5, 6] "expected. Tip: Check your spaces and / or spelling.

它可能是private static scanner scanner = new scanner (System.in);吗,因为我在main中使用它,但是系统不允许添加main,因为它默认会带来它

import java.util.Scanner;

import java.util.Arrays;

public class formato {
    

    public static int[] getIntegers(int capacity) {
        static Scanner scanner = new Scanner(System.in);
        int[] array = new int[capacity];
        System.out.println("Enter "+capacity+" integer values:\r");
        for(int i = 0; i<array.length ; i++){
        array[i] = scanner.nextInt();
        }
        return array;
    
    }

    public static void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.println("Element " + i + " contents " + array[i]);
        }
    }

    public static int[] sortIntegers(int[] array) {
        // int[] sortedArray = new int[array.length];
        // for(int i=0; i<array.length; i++) {
        // sortedArray[i] = array[i];
        int[] sortedArray = Arrays.copyOf(array, array.length);
        // }
        boolean flag = true;
        int temp;
        while (flag) {
            flag = false;
            for (int i = 0; i < sortedArray.length - 1; i++) {
                if (sortedArray[i] < sortedArray[i + 1]) {
                    temp = sortedArray[i];
                    sortedArray[i] = sortedArray[i + 1];
                    sortedArray[i + 1] = temp;
                    flag = true;
                }
            }
        }
        return sortedArray;
    }
}

共 (1) 个答案

  1. # 1 楼答案

    定义类常量:

    public static final Scanner scanner = new Scanner(System.in);

    这对你有帮助

    或者只使用Scanner scanner = new Scanner(System.in);