我试图将数字显示为我创建的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'是用户想要的次数。
答案 0 :(得分:1)
你的循环中有一些错误。它应该是
for(int x = 0; x < numbers; x++)
{
int num = rand.nextInt(100) + 1;
numList.add(num);
}
答案 1 :(得分:-1)
我认为问题在于将您的号码保存到列表中。你的情况:
for(int x = 1; x >= numbers; x++)
使循环几乎从不运行,因为循环仅在x大于numbers
时才为真。您从x = 1
开始,所以只有当numbers
正好为1时,您的循环才有效。有点,因为它将是无限循环。将其更改为
for(int x = 1; x <= numbers; x++)
它应该没问题。
修改强>
Ayo K提到了我的错误,我在条件上忘了等于
此外,您将两次递增列表,一次在循环声明中,一次在正文中。