创建具有有限值和停止值的未定义Java数组?

时间:2016-03-10 00:41:34

标签: java arrays

我在创建一个数组时遇到问题,该数组会要求用户输入一个连续的数字列表(我的执行循环),该数组将限制在1-100之间。如果用户输入这些参数之外的任何内容,则该值不会输入到数组中。如果用户输入-1,则会停止do while循环。我需要它来打印出值,但它只给出了第一个值和一个循环。请帮帮我,谢谢! PS:我不能使用ArrayList

int count = 0;

do 
{
  input = userinput.nextDouble();
  if (input >= 1 && input <= 100)
  {
    array[count] = input;
  }
  else if (input > 100 || input < -1)
  {
    System.out.println("Please enter a valid mark (0-100)");
  }
  count = count + 1;
}
while (input != -1);

for (int counter = 0; counter < count; count++)
{
  System.out.println(array[counter]);
}

1 个答案:

答案 0 :(得分:3)

您在循环中增加了count而不是counter来打印值,因此循环将会过多次并且只打印第一个元素。

试试这个:

double[] array = new double[1000000];
int count = 0;
do 
{
  input = userinput.nextDouble();
  if (input >= 1 && input <= 100)
  {
    if (count < array.length) array[count++] = input;
  }
  else if (input != -1)
  {
    System.out.println("Please enter a valid mark (1-100)");
  }
}
while (input != -1);

for (int counter = 0; counter < count; counter++)
{
  System.out.println(array[counter]);
}

此外,补充java.util.List的类对于存储编号未知的元素非常有用。

java.util.List<Double> list = new java.util.LinkedList<Double>(); // requires JRE >= 1.5
double input;
do 
{
  input = userinput.nextDouble();
  if (input >= 1 && input <= 100)
  {
    list.add(input);
  }
  else if (input != -1)
  {
    System.out.println("Please enter a valid mark (1-100)");
  }
}
while (input != -1);
Double[] array = list.toArray(new Double[list.size()]);

for (int counter = 0; counter < array.length; counter++)
{
  System.out.println(array[counter]);
}