【发布时间】: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 < 2) throw...而不是if (max > 2) throw...,不是吗?