关于Arraylist的问!!!
写了个输入个数 输出素数的东西....可是Arraylist总是提示类型转换错误...
希望高手指点一下...实在无奈啊
参考算法
prime numbers:
Set the first element of a to the lowest prime number (2).
For each odd number, test, starting at 3:
For each element, p, in a:
Compute the remainder of test/p.
If the remainder was non-zero for every p:
Append test to a.
If the length of a equals n:
break
程序
import java.util.*;
public class Prime{
static int sum;
public static void main(String []args){
ArrayList <Integer> PrimeNumbers=new ArrayList <Integer> ();
PrimeNumbers.add(new Integer(2));//先将素数2加入
Scanner in=new Scanner(System.in);
System.out.println( "Please input a number(n> 0): ");
sum=in.nextInt();
for(int test=3;;test+=2){
for(int order=0,p=((Integer)(PrimeNumbers[order])).intValue();;order <PrimeNumbers.size();order++)
if(test%p==0){
PrimeNumbers.add(new Integer(test));
break;
}
if(PrimeNumbers.size()==sum)
break;
}
System.out.println(PrimeNumbers);
}
}
错误多多 大家指点!!!
------解决方案--------------------PrimeNumbers[order] == 是不是应该改成 : (Integer)PrimeNumbers.get(order)
------解决方案--------------------读成了ascii值了
------解决方案-------------------- import java.util.*;
public class Prime{
static int sum;
public static void main(String []args){
ArrayList PrimeNumbers=new ArrayList();
PrimeNumbers.add(new String( "2 "));//先将素数2加入
Scanner in=new Scanner(System.in);
System.out.println((String)PrimeNumbers.get(0)+ "Please input a number(n> 0): ");
sum=in.nextInt();
for(int test=3;;test+=2){
for(int order=0,p=Integer.parseInt((String)PrimeNumbers.get(order));order <PrimeNumbers.size();order++)
if(test%p==0){
PrimeNumbers.add(new Integer(test));
break;
}