[英]How to print out the index of a boolean array?
I'm trying to get all of the indexes of a Boolean array to be printed out where its element is true. 我试图获取要打印出其元素为true的布尔数组的所有索引。 The end goal is to be able to find a prime number of the indexes (where I change each index number that isn't prime to false in the array) then print out only what is left of the prime numbers of the indexes of the array. 最终目标是能够找到索引的质数(在此,我将数组中不是素数的每个索引号都更改为false),然后仅打印出数组索引的质数剩余的数。
The very first step I'm just trying to do is at least to get some integer index to print out, but nothing seems to be working and I don't know what is wrong. 我要做的第一步是至少要打印一些整数索引 ,但是似乎没有任何效果,我也不知道这是什么错误。
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;
}
}
EDIT: Included is the driver class that's requesting the print of the class PriNum 编辑:包括请求类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);
}
}
I tried running this, and the first change that needs to happen is to set this argument: 我尝试运行此命令,需要进行的第一个更改是设置此参数:
if(max < 2)
Then, if I'm reading this correctly: 0 and 1 are false. 然后,如果我没看错:0和1为假。 Every index after that is true. 此后的每个索引都是正确的。 The output is fine as I see it. 如我所见,输出很好。 Just all the numbers crunched as a continuous list. 只是所有数字都是连续的。
To get a better output, put a space between indexes: 为了获得更好的输出,请在索引之间放置一个空格:
if(array[i] == true){
s = s + " " + i;
}
You may even just output to screen directly as 您甚至可以直接输出到屏幕
if(array[i])
System.out.print( i );
numbers is initialized without declaration, array is declared but not initialized anywhere in your code. 数字会初始化而不声明,数组会被声明但不会在代码中的任何地方初始化。 You have also a syntax error after array[i] = true, should be curly brace... 在array [i] = true之后,您也有语法错误,应该大括号...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.