【问题标题】:Populate ArrayList with Random numbers then Print Array用随机数填充 ArrayList,然后打印 Array
【发布时间】:2017-03-05 00:54:58
【问题描述】:

我想用随机数填充数组列表,然后打印数组。但是,执行程序时出现大量错误。任何帮助将不胜感激。

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)

我认为我的方法根本上是错误的。

【问题讨论】:

  • 了解您看到的错误会很有帮助。
  • 您不能将 ArrayList 格式化为 %4d。您的意思是 String.format("%4d", randomArray.get(i)); 格式化列表中的特定元素吗?

标签: java arrays arraylist


【解决方案1】:

您不能将randomArray(即java.util.ArrayList)传递给String.format()

您可能想改为传递randomArray.get(i)

【讨论】:

  • 我认为那是我一开始就做错了。我现在可以运行程序了!感谢您的帮助:)
【解决方案2】:

this.capacity = capacity; 添加到public methods() { 构造函数开始。您正在引用此变量,但从未设置它。

【讨论】:

  • 感谢您的帮助!我不再收到该错误:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-22
相关资源
最近更新 更多