使用while循环时无法接受用户输入

时间:2015-11-09 20:31:47

标签: java arrays loops input while-loop

我有这个代码,它应该是一个用户输入并将其存储在一个数组中,我只是想知道为什么它不允许我输入任何数字。

输入部分应该在if语句中吗?还有什么是让它正常工作的最佳方法?

import java.util.*;

public class fun_with_loops {

    static Scanner scan = new Scanner(System.in);

    public static void main (String[] args) throws java.io.IOException
    {
        int[] numbers = new int[10];
        int numberSize = 0;
        System.out.print("Enter a few numbers please\n");



        while (numbers.length < 10)
        {
            int input = scan.nextInt();
            if (input != 0)
            {
                numbers[numberSize] = input;
                numberSize++;
            }
            else
            {
                break;
            }

        }

    }  
}

4 个答案:

答案 0 :(得分:1)

<强>问题

循环控件的以下表达式总是被评估为false:

while (numbers.length < 10)

因为数组的长度实际上与声明时的长度相等。

<强>解决方案

为了按预期编程工作,您必须使用numberSize变量作为控件:

while (numberSize < 10)

因为它会根据输入数量而增长。

答案 1 :(得分:0)

正如Am_I_Helpful所说,你在一个不会改变的值上使用while循环。我不确定在这种情况下是否需要使用。由于您希望循环特定次数,因此您可能希望使用for循环。如果次数取决于数组的大小,您仍然可以用数组长度(numbers.length)替换“10”。

for (int i; i< 10; i++)
    {
        int input = scan.nextInt();
        if (input != 0)
        {
            numbers[numberSize] = input;
            numberSize++;
        }
        else
        {
            break;
        }

    }

希望它有所帮助!

关于何时使用每个循环的简短而完美的总结: http://mathbits.com/MathBits/CompSci/looping/whichloop.htm

但当然在编码时总是取决于你的目标,所以如果你不是那个编码,有时很难说哪个是最好的。

答案 2 :(得分:0)

因为数组初始化为10,所以长度始终为10.需要使用计数器变量。这是代码:

static Scanner scan = new Scanner(System.in);

public static void main (String[] args) throws java.io.IOException
{
    int[] numbers = new int[10];        
    System.out.print("Enter a few numbers please\n");


    int count = 0;
    while (count < 10)
    {
        int input = scan.nextInt();
        if (input != 0)
        {
            numbers[count] = input;
            count++;
        }
        else
        {
            break;
        }

    }

答案 3 :(得分:0)

length属性返回数组的大小,而不是数组中存在的元素数。您需要自己跟踪数组中的元素数量。

    for(int eleCount = 0; eleCount < 10; eleCount++) 
    {
        int input = scan.nextInt();
        if (input != 0)
        {
            numbers[eleCount] = input;
        }
        else
        {
            break;
        }

    }
相关问题