Я работаю над бонусом за одно из моих заданий. Я должен создать действительно большой массив, но пользователю не нужно использовать все слоты в массиве. Раньше я использовал расширенный цикл for для регулярного массива, который заполнял все его индексы. Я не уверен, как изменить это, чтобы соответствовать новым критериям.Частично заполненный массив - получите минимальное значение и toString
Всякий раз, когда я вводим числа в тесте, toString
возвращает пустые места, а минимальное значение возвращает 0, поскольку значения пустого места равны 0 с.
public class NumberSetBonus
{
private int[] numbers;
private int count;
/**
* Constructs an empty NumberSet of a specified size
* @param size the number of elements in the set
*/
public NumberSetBonus(int size)
{
numbers = new int[size];
count = 0;
}
/**
* addNumber adds a number to the number set
* @param num new number
*/
public void addNumber(int num)
{
numbers[count] = num;
count++;
}
/**
* getMin finds the minimum value stored in the NumberSet
* @return the minimum value
* precondition: array is full of values
*/
public int getMin()
{
int min = numbers[0];
for(int n : numbers)
if(n < min)
min = n;
return min;
}
/**
* getMax finds the maximum value stored in the NumberSet
* @return the maximum value
* precondition: array is full of values
*/
public int getMax()
{
int max = numbers[0];
for(int n : numbers)
if(n > max)
max = n;
return max;
}
/**
* find determines whether a specified value exists in the set.
* @param num the number to find
* @return whether the value exists
*/
public boolean find(int num)
{
boolean find = true;
for(int n : numbers)
if(n == num)
find = true;
return find;
}
/**
* getSum calculates the sum of the values in the set.
* @return the sum
*/
public int getSum()
{
int sum = 0;
for(int n : numbers)
sum += n;
return sum;
}
/**
* getMean calculates the mean of the values in the set.
* @return the mean as a double
* precondition: array is full of values
* NOTE: use the length field of the array
*/
public double getMean()
{
return getSum()/(double) numbers.length;
}
/**
* count counts the occurrence of a specified number within the set.
* @param num the number to find
* @return the number of times num occurs in the set
*/
public int count(int num)
{
int quantity = 0;
for(int n : numbers)
if(n == num)
quantity++;
return quantity;
}
/**
* toString returns a String containing the values in the set on a
* single line with a space between each value.
* @return the String version of the set
*/
public String toString()
{
String set = " ";
for(int n : numbers)
set += n + " ";
return set;
}
}
Вот мой тестер, где я прошу для входа пользователя, и где toString()
возвращает 0s
public class NumberSetBonusTester
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
final int LENGTH = 100;
NumberSetBonus list = new NumberSetBonus(LENGTH);
int arraySize = 0;
System.out.print("You can enter up to 100 numbers in this array. \nType in a negative number if you want to stop adding numbers.\nEnter a number: ");
while(arraySize < LENGTH)
{
int number = input.nextInt();
if(number <= 0)
break;
list.addNumber(number);
arraySize++;
}
System.out.print("\nset 1:\t\t");
System.out.println(list);
System.out.println("list sum:\t" + list.getSum());
System.out.println("list mean:\t" + list.getSum()/arraySize);
System.out.println("list max:\t" + list.getMax());
System.out.println("list min:\t" + list.getMin());
System.out.println();
System.out.print("Enter a number to find ==> ");
int searchNum = input.nextInt();
if (list.find(searchNum))
System.out.println(searchNum + " is in the set " + list.count(searchNum) + " times");
else
System.out.println(searchNum + " is not in the set");
}
}
Большое спасибо! Вы рок: D – user3001948