我写了一个程序来打印出所有素数达到极限。然后将这些素数放入ArrayList,将此ArrayList转换为数组,最后用它们的索引打印出数字。
注意:我无法打印带有for循环的ArrayList,只能使用数组,因此转换。
我的问题是:
无论如何都要在没有先将数字推入ArrayList的情况下进行,而是将它们立即放入长度为<的数组中。限制。
谢谢你的帮助! 在过去的两天里一直在浏览SO而且找不到任何东西
import java.util.Scanner;
import java.util.ArrayList;
public class test {
public static void main(String[] args){
//get input till which prime number to be printed
System.out.print("Enter the number till which prime number to be printed: ");
int limit = new Scanner(System.in).nextInt();
System.out.print("\n");
ArrayList<Integer> myArray = new ArrayList<Integer>();
//printing primer numbers till the limit ( 1 to 10)
System.out.println("Printing prime number from 1 to " + limit + "\n");
for(int number=2; number <= limit; number++){
if(isPrime.numberPrime(number)){
myArray.add(number);
}
}
System.out.println(myArray + "\n");
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
}
结果如下: 输入要打印的素数的数字:10
Printing prime number from 1 to 10
[2, 3, 5, 7]
There were 4 prime numbers
Index Value
1 2
2 3
3 5
4 7
答案 0 :(得分:1)
无需这样做
//Convert ArrayList into an Array
int[] newArray = new int[myArray.size()];
for(int i = 0; i < myArray.size(); i++) {
newArray[i] = myArray.get(i);
}
System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int counter = 0; counter<newArray.length; counter++){
System.out.println(counter+1 + "\t" + newArray[counter]);
}
代替这一点,只需写下
即可System.out.println("There were " + myArray.size() + " prime numbers");
System.out.println("Index\tValue");
for(int i=0;i<myArray.size();i++)
System.out.println(i+1 + "\t" + myArray.get(i));