【问题标题】:Program won't run when using java.util.Arrays -- what might be going wrong?使用 java.util.Arrays 时程序无法运行——可能出了什么问题?
【发布时间】:2016-01-19 18:06:51
【问题描述】:

当“clearPets”方法中的代码没有被注释掉时,我得到了一堆错误。只要我删除该代码,程序就会以其他方式运行。

如何解决这些问题?我最近才了解创建和调用方法,这是我第一次使用java.util.Arrays

控制台中的错误是:

Exception in thread "main" java.lang.ArrayStoreException: java.lang.Boolean
at java.util.Arrays.fill(Unknown Source)
at rf.uhh.clearPets(uhh.java:34)
at rf.uhh.optionOne(uhh.java:39)
at rf.uhh.main(uhh.java:20)

这是我的代码:

public class uhh {

    public static void main(String[] args){

        System.out.println("Select a number");
        System.out.println("1");
        System.out.println("2");
        System.out.print("Choice: ");

        Scanner scnr = new Scanner(System.in);      
        String numberChoice = scnr.nextLine();

        if( "1".equals(numberChoice) ) {
            System.out.println("You chose 1");
            optionOne(new boolean[][] { {false}, {true} });
        }

        scnr.close();
    }   

    public static boolean[][] adoptPets( int cats, int dogs) {      
        boolean[][] pets = new boolean[cats][dogs];

        return pets ;
    }

    public static void clearPets( boolean[][]pets) {
        Arrays.fill(pets, false);
    }   

    public static void optionOne(boolean[][] center) {
        clearPets(center);

        boolean[][] dogFaceMan = adoptPets(10, 10);
        dogFaceMan[1][1] = true;                                        
    }
}

【问题讨论】:

    标签: java arrays boolean


    【解决方案1】:

    您将二维数组传递给需要一维数组的方法 (Arrays.fill)。

    试试这个:

    public static void clearPets( boolean[][]pets) {
        for(int i = 0; i < pets.length; i++) {
            Arrays.fill(pets[i], false);
        } 
    } 
    

    【讨论】:

    • 谢谢。这很有效,而且很有意义!我会尽快接受这个作为答案(stackoverflow 时间限制)。
    • @Neo 没问题,很乐意提供帮助。
    猜你喜欢
    • 2010-10-01
    • 2016-10-31
    • 2017-02-19
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 2022-01-20
    • 2021-10-08
    • 1970-01-01
    相关资源
    最近更新 更多