【发布时间】:2017-11-13 15:18:37
【问题描述】:
我正在尝试将数字显示为我创建的 ArrayList 的输出。我问用户他们想要在 ArrayList 中有多少个数字,然后使用 for 循环生成 1-100 之间的随机数,并且无论用户想要多少次,它们都会被扔到 ArrayList 中。我只是无法显示,这是我的代码:
KNW_MyList 类:
public class KNW_MyList<T extends Number>
{
//Create the array list object of type T
ArrayList<T> al = new ArrayList<T>();
/**
* The adds method, add a number of type T to
* array list.
* @param number, the number to be added.
* */
public void add( T number)
{
al.add(number);
}
/**
* The largest method, returns the largest value in the
* array list.
* */
public T largest()
{
T large = al.get(0);
//For-loop to find the largest value
for(int x = 0; x < al.size(); x++)
{
if(al.get(x).toString().compareTo(large.toString()) > 0)
{
large = al.get(0);
}
}
return large;
}
/**
* The smallest method, returns the smallest value in the
* array list.
* */
public T smallest()
{
T small = al.get(0);
//For-loop to find the largest value
for(int x = 0; x < al.size(); x++)
{
if(al.get(x).toString().compareTo(small.toString()) < 0)
{
small = al.get(0);
}
}
return small;
}
/**
* The show method, wil show the elements in the array
* list.
* */
public void show()
{
System.out.println(al);
}
}
演示:
import java.util.*;
import java.lang.Math;
public class KNW_MyListDemo
{
public static void main(String args[])
{
//Create random class
Random rand = new Random();
int numbers;
Scanner scan = new Scanner(System.in);
//Create ArrayList object
KNW_MyList<Number> numList = new KNW_MyList<Number>();
//Ask the user how many numbers they want in the array
System.out.println("How many numbers do you want?: ");
numbers = scan.nextInt();
if(numbers <= 0)
{
System.out.println("Not Valid!");
}
else
{
for(int x = 1; x >= numbers; x++)
{
int num = rand.nextInt(100) + 1;
numList.add(num);
x++;
}
//Call the show method
System.out.println("Numbers in the array: ");
numList.show();
}
}
}
我的 ArrayList 或 forloop 有问题吗?我不太确定,对数组列表有点新,所以这可能会或可能不会有任何影响?我只想让随机数显示“x”次,“x”是用户想要的次数。
【问题讨论】:
-
您没有显示类
KNW_MyList的代码。请阅读minimal reproducible example -
KNW_MyList是什么?
标签: java for-loop arraylist random