首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用随机数填充ArrayList,然后打印数组

用随机数填充ArrayList,然后打印数组
EN

Stack Overflow用户
提问于 2017-03-05 08:54:58
回答 2查看 852关注 0票数 0

我想用随机数填充一个arrayList,然后打印数组。然而,在执行程序时,我得到了大量的错误。任何帮助都将不胜感激。

代码语言:javascript
复制
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,用随机数填充它并打印它。以下是我收到的错误列表:

代码语言:javascript
复制
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)

我认为我的方法做了一些根本错误的事情。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-05 09:06:38

不能将randomArray (它是一个java.util.ArrayList)传递给String.format()

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

票数 0
EN

Stack Overflow用户

发布于 2017-03-05 09:06:12

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42603185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档