数组未捕获第一个用户条目

时间:2013-09-06 03:49:38

标签: java arrays user-input

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

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

谢谢!

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));
 }

2 个答案:

答案 0 :(得分:1)

Prolem

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

  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的价值,并希望将credit存储在inputs中,那么您应该这样做:

 double credits = in.nextDouble();
 inputs[0] = credits ;
    int currentSize = 1;   

答案 1 :(得分:0)

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