2017-03-05 41 views
0

我想用隨機數填充arrayList然後打印數組。但是,在執行程序時,我會遇到大量的錯誤。任何幫助,將不勝感激。用隨機數填充ArrayList然後打印數組

public class methods { 
//variables 
int capacity; 
private static ArrayList<Double> randomArray; 



public methods(int capacity) { 
    //default constructor to initalize variables and call populateArray to 
    //populate ArrayList with random numbers 
    randomArray = new ArrayList<>(capacity); 
    populateArray(); 
} 

//Method that populates Array with random numbers 
private void populateArray() 
{ 

    Random rand = new Random(); 

    for (int i=0; i<= capacity; i++) 
    { 
     double r = rand.nextInt() % 256; 

     randomArray.add(i,r); 

    } 

} 
//Get Array adds numbers to the string that is called in my main class and printed 
public String getArray() { 
String result = ""; 
for (int i=0; i<= capacity; i++) 
    { 
     result += String.format("%4d", randomArray); 

    } 
return result; 

} 

} 

//main 
public class Benchmarking { 


public static void main (String args[]){ 

Scanner scanner = new Scanner(System.in); 

    System.out.println("What is the capacity of your Array?"); 
    int capacity = scanner.nextInt(); 

    methods array1 = new methods(capacity); 
    System.out.println(array1.getArray()); 
} 

當我運行該程序並輸入它的容量崩潰。我只需要創建一個arrayList填充隨機數字並打印它。這裏是我收到的錯誤列表:

Exception in thread "main" java.util.IllegalFormatConversionException: d != java.util.ArrayList 
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302) 
at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793) 
at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747) 
at java.util.Formatter.format(Formatter.java:2520) 
at java.util.Formatter.format(Formatter.java:2455) 
at java.lang.String.format(String.java:2927) 
at Benchmarking.methods.getArray(methods.java:68) 
at Benchmarking.Benchmarking.main(Benchmarking.java:27) 

我想我正在做一些根本上錯誤的方法。

+1

這將有助於瞭解您所看到的錯誤。 – Jeremy

+0

您不能將ArrayList格式化爲%4d。你是不是指'String.format(「%4d」,randomArray.get(i));'格式化列表中的某個特定元素? –

回答

0

你不可錯過randomArray(這是一個java.util.ArrayList)到String.format()

您可能想改爲通過randomArray.get(i)

+0

我認爲這是我做錯了開始。我得到了程序現在運行!謝謝您的幫助 :) – Art

0

this.capacity = capacity;添加到public methods() {構造函數開始。您正在引用此變量,但從未設置它。

+0

非常感謝幫助!我不再得到那個錯誤:) – Art