【问题标题】:How to print out the index of a boolean array?如何打印出布尔数组的索引?
【发布时间】:2018-10-16 01:53:11
【问题描述】:

我正在尝试将布尔数组的所有索引打印出来,其中元素为真。最终目标是能够找到索引的素数(我将数组中每个非素数的索引号更改为假)然后仅打印出数组索引的素数的剩余部分.

我正在尝试做的第一步至少是让一些整数索引打印出来,但似乎没有任何效果,我不知道出了什么问题。

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

编辑:包括请求打印 PriNum 类的驱动程序类

class Driver{
    public static void main(String [] args){
        PriNum theprime = null;

        try{
            theprime = new PriNum(50);
        }
        catch (IllegalArgumentException oops){
            System.out.println("Max must be at least 2.");
        }

        System.out.println(theprime);
    }
}

【问题讨论】:

  • private boolean[] array; 永远不会被初始化。 numbers 是什么?我认为这段代码甚至不会编译。
  • max 是什么,您希望什么索引为真。我注意到你有一个错字(在第一个循环中你的else 之前缺少})。另外,你是怎么打印这个的?调用 toString() 并且对结果不做任何事情并没有多大效果。
  • @ElliottFrisch max 应该是数组的最大大小,并且它是由此类之外的驱动程序类打印的(如果有必要,我也可以包括在内),谢谢用于捕捉错字;现在修好了
  • 阅读您的代码后,我猜您想要 if (max &lt; 2) throw... 而不是 if (max &gt; 2) throw... ,不是吗?

标签: java arrays boolean


【解决方案1】:

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

if(max < 2)

那么,如果我没看错的话:0 和 1 是假的。之后的每个索引都是真的。正如我所见,输出很好。只是将所有数字压缩成一个连续的列表。

为了得到更好的输出,在索引之间放一个空格:

if(array[i] == true){
    s = s + " " + i;
}

你甚至可以直接输出到屏幕

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

【讨论】:

    【解决方案2】:

    numbers 在没有声明的情况下被初始化,数组被声明但没有在代码中的任何地方初始化。在 array[i] = true 之后还有语法错误,应该是大括号...

    【讨论】:

    • 这是我的错误; numbers 应该是 array。它现在与语法错误一起修复了!
    • 我认为你的代码总是会抛出 IllegalArgumentException cos 参数总是超过 2 (50),这意味着 toString() 根本没有被调用或者我错过了什么?
    猜你喜欢
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 1970-01-01
    • 2021-11-13
    • 2013-06-10
    • 1970-01-01
    • 2021-01-06
    相关资源
    最近更新 更多