Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/369.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何打印布尔数组的索引?_Java_Arrays_Boolean - Fatal编程技术网

Java 如何打印布尔数组的索引?

Java 如何打印布尔数组的索引?,java,arrays,boolean,Java,Arrays,Boolean,我试图将布尔数组的所有索引打印出来,其中元素为true。最终目标是能够找到索引的素数,我将数组中每个非素数的索引数更改为false,然后只打印出数组中索引的素数的剩余部分 我只是想做的第一步是至少打印出一些整数索引,但似乎什么都不起作用,我不知道出了什么问题 public class PriNum{ private boolean[] array; public PriNum(int max){ if (max > 2){ //I don't have a

我试图将布尔数组的所有索引打印出来,其中元素为true。最终目标是能够找到索引的素数,我将数组中每个非素数的索引数更改为false,然后只打印出数组中索引的素数的剩余部分

我只是想做的第一步是至少打印出一些整数索引,但似乎什么都不起作用,我不知道出了什么问题

public class PriNum{
    private boolean[] array;

    public PriNum(int max){
        if (max > 2){ //I don't have any problems with this if statement
            throw new IllegalArgumentException();
        }
        else{
            array = new boolean[max];

            for(int i = 0; i < max; i++){
                if(i == 0 || i == 1){ //Automatically makes 0 and 1 false 
                                      //because they are not prime
                    array[i] = false;
                }
                else{
                    array[i] = true;
                }
            }
            toString(); //I know for sure the code gets to here 
                        //because it prints out a string I have
                        // there, but not the index
        }
    }

    public String toString(){
        String s = "test"; //this only prints test so I can see if 
                           //the code gets here, otherwise it would just be ""

        for (int i = 0; i < array.length; i++){
            if(array[i] == true){
                s = s + i; //Initially I tried to have the indexes returned
                         //to be printed and separated by a comma,
                         //but nothing comes out at all, save for "test"
             }
         }

        return s;
    }
}

数字初始化时不声明,数组被声明但未在代码中的任何地方初始化。在array[i]=true之后,您还有一个语法错误,应该是大括号…

我尝试运行此命令,需要做的第一个更改是设置此参数:

if(max < 2)
您甚至可以直接输出到屏幕,如下所示:

if(array[i])
 System.out.print( i );

私有布尔[]数组;永远不会被初始化。什么是数字?我认为这段代码甚至不会编译。最大值是多少,您希望哪个索引是真的。我注意到,在第一个循环中,您在其他人之前丢失了一个输入错误}。还有,你怎么打印这个?调用toString而对结果不做任何处理并没有多大效果。@ElliottFrisch max应该是数组的最大大小,并且它是由这个类之外的驱动程序类打印的,如果有必要的话,我还可以包括这个类,感谢您捕获了输入错误;已经修好了now@ScaryWombat哎呀,这些数字对我来说是个错误,我应该用数组来告诉你我到底在用什么。读了你的代码后,我想如果max<2,你会想。。。如果最大值>2,则不会抛出,是吗?那是我的错误;数字应该是数组。现在它和语法错误一起被修复了!我想你的代码总是会抛出IllegalArgumentException,因为参数总是超过250,这意味着toString根本没有被调用,或者我遗漏了什么?
if(array[i] == true){
    s = s + " " + i;
}
if(array[i])
 System.out.print( i );