I am trying to get the numbers display as my output from the ArrayList I have created. I asked the user how many numbers do they want in the ArrayList, then used a for loop to generate random numbers between 1-100 and they would be thrown into the ArrayList however many times the user wants the to be. I just can't get the to be displayed, here's my code:
The KNW_MyList class:
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);
}
}
Demo:
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();
}
}
}
Is there something wrong with my ArrayList or my forloop? I am not quite sure, am kinda new to array list so maybe this might or might not have any effect? I just wanna get the random numbers to display 'x' amount of times, 'x' being the number of times the user wants.
Aucun commentaire:
Enregistrer un commentaire