숫자를 작게 배열하는 데 문제가 있습니다. 임 sortedinlist에있는 intlist의 메서드를 무시하려고, 내가 얻을 출력 0, 0,0입니다. 내가 어떻게 고칠 수 있니?상속을 사용하여 배열의 최소값에서 최대 값으로 배열 정렬 (오류 무시)
run:
0: 100
1: 50
2: 200
3: 25
0: 0
1: 0
2: 0
SortedIntList.java
public class SortedIntList extends IntList
{
public SortedIntList(int Size)
{
super(Size);
}
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else{
int empty = 0;
int f;
for(f=0;f<list.length-1;f++){
if(list[f] == 0)
{empty = f;}
}
list[empty] = value;
numElements++;
}
int k = 0; int temp = 0;
for(int i=0;i<list.length-1;i++)
{
k = i;
for(int j = i+1; j < list.length; j++)
{
if(list[j] < list[k])
k = j;
}
temp = list[k];
list[k] = list[i];
list[i] = temp;
}
}
}
ListTest.java
public class ListTest {
public static void main(String[] args)
{
IntList myList = new IntList(10);
myList.add(100);
myList.add(50);
myList.add(200);
myList.add(25);
System.out.println(myList);
SortedIntList myList2 = new SortedIntList(10);
myList2.add(20);
myList2.add(100);
myList2.add(30);
System.out.println(myList2);
}
}
IntList.java
public class IntList {
protected int[] list;
protected int numElements = 0;
//-------------------------------------------------------------
// Constructor -- creates an integer list of a given size.
//-------------------------------------------------------------
public IntList(int size)
{
list = new int[size];
}
//-------------------------------------------------------------
// Adds an integer to the list. If the list is full,
// prints a message and does nothing.
//-------------------------------------------------------------
public void add(int value)
{
if (numElements == list.length)
System.out.println("Can't add, list is full");
else
{
list[numElements] = value;
numElements++;
}
}
//-------------------------------------------------------------
// Returns a string containing the elements of the list with their
// indices.
//-------------------------------------------------------------
public String toString()
{
String returnString = "";
for (int i=0; i<numElements; i++)
returnString += i + ": " + list[i] + "\n";
return returnString;
}
}