0

我正在尝试使用一种方法用浮点数填充数组。每次我运行我的程序时,它都不会捕获输入的第一个数字。

如何更正我的代码以便捕获第一个用户输入?

谢谢!

public static void main(String[] args)
{

    //Read user input into the array

    final int INITIAL_SIZE = 8;
    double[] inputs = new double[INITIAL_SIZE];
    Scanner in = new Scanner(System.in);
    System.out.println("Please enter the number of credits for a course, Q to     quit:");
    double credits = in.nextDouble();

    int currentSize = 0;   

    while (in.hasNextDouble())
    {

        if (credits <= 0)
        {
            System.out.println("All entries must be a positive number.");
        }

        else
        {    
            // Grow the array if it has been completely filled

            if (currentSize >= inputs.length)
            {
                 inputs = Arrays.copyOf(inputs, 2 * inputs.length);
            }
            inputs[currentSize] = in.nextDouble();
            currentSize++;
        }
    }
    System.out.println(Arrays.toString(inputs));
 }
4

2 回答 2

1

问题是

您没有存储第一个用户条目,所以它没有显示给您

  Scanner in = new Scanner(System.in);
    System.out.println("Please enter the number of credits for a course, Q to     quit:");
 -->   double credits = in.nextDouble();

您已从用户那里获取值,但未将其存储在inputs

如果您想credit从用户那里获取价值并想要存储creditinputs那么您应该这样做:

 double credits = in.nextDouble();
 inputs[0] = credits ;
    int currentSize = 1;   
于 2013-09-06T04:01:01.213 回答
0

问题可能出在这一行:inputs[currentSize] = in.nextDouble(); 您将第一个值存储在credits但未将其分配给inputs数组。

于 2013-09-06T03:57:38.787 回答