Java 数字不是';t显示我的输出
我正试图从我创建的ArrayList中获取显示为输出的数字。我问用户在ArrayList中需要多少个数字,然后使用for循环生成1-100之间的随机数,无论用户希望多少次,这些数字都会被扔进ArrayList。我只是无法显示,这是我的代码: KNW_MyList类:Java 数字不是';t显示我的输出,java,for-loop,arraylist,random,Java,For Loop,Arraylist,Random,我正试图从我创建的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>
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);
}
}
公共类KNW\u MyList
{
//创建T类型的数组列表对象
ArrayList al=新的ArrayList();
/**
*在adds方法中,向
*数组列表。
*@param number,要添加的编号。
* */
公共无效添加(T编号)
{
新增(编号);
}
/**
*最大的方法,返回
*数组列表。
* */
公营部门
{
T大=al.get(0);
//For循环查找最大值
对于(int x=0;x0)
{
大=al.get(0);
}
}
回报大;
}
/**
*最小的方法,返回
*数组列表。
* */
公共交通
{
T小=al.get(0);
//For循环查找最大值
对于(int x=0;x
演示:
import java.util.*;
导入java.lang.Math;
公共类KNW_MyListDemo
{
公共静态void main(字符串参数[])
{
//创建随机类
Random rand=新的Random();
整数;
扫描仪扫描=新扫描仪(System.in);
//创建ArrayList对象
KNW_MyList numList=新的KNW_MyList();
//询问用户希望阵列中有多少个数字
System.out.println(“您想要多少个数字?:”;
number=scan.nextInt();
如果(数字=数字;x++)
{
int num=rand.nextInt(100)+1;
numList.add(num);
x++;
}
//调用show方法
System.out.println(“数组中的数字:”);
numList.show();
}
}
}
我的ArrayList或forloop有什么问题吗?我不太确定,我对数组列表有点陌生,所以这可能会或可能不会有任何影响?我只想让随机数显示“x”的次数,“x”是用户想要的次数。我想问题在于将数字保存到列表中。您的情况如下:
for(int x = 1; x >= numbers; x++)
使循环几乎从不运行,因为只有当x大于数字时,循环才为真。您从x=1
开始,因此只有当number
正好为1时,您的循环才会正常工作。有点,因为它将是无限循环。换成
for(int x = 1; x <= numbers; x++)
for(intx=1;x循环中的一些错误。应该是
for(int x = 0; x < numbers; x++)
{
int num = rand.nextInt(100) + 1;
numList.add(num);
}
for(int x=0;x
您没有显示类的代码KNW\u MyList
。请仔细阅读什么是KNW\u MyList
?哇,我觉得很傻!非常感谢,我一读第一行就意识到了我的问题!这个答案将给出错误的输出,并且只在列表中添加numbers-1
数字是的,我还注意到您在增加ingx
两次。Ayo K也是对的,我会编辑这个。
for(int x = 0; x < numbers; x++)
{
int num = rand.nextInt(100) + 1;
numList.add(num);
}