Ich möchte eine ArrayList mit Zufallszahlen füllen und dann array drucken. Allerdings bekomme ich eine große Anzahl von Fehlern bei der Ausführung des Programms. Jede Hilfe wäre willkommen.ArrayList mit Zufallszahlen füllen, dann Array drucken
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());
}
Nachdem ich das Programm ausführen und die Kapazität eingeben, stürzt es ab. Ich muss nur eine ArrayList erstellen, sie mit Zufallszahlen füllen und ausdrucken. Hier sind die Liste der Fehler, die ich erhalte:
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)
Ich denke, ich mache etwas grundsätzlich falsch mit meinen Methoden.
Es wäre hilfreich zu wissen, welche Fehler Sie sehen. – Jeremy
Sie können eine ArrayList nicht als% 4d formatieren. Meintest du 'String.format ("% 4d ", randomArray.get (i));' um ein bestimmtes Element der Liste zufällig zu formatieren? –