首页 > 解决方案 > For循环中的无限循环

问题描述

我试图更改我的程序以显示月份的名称。

        private static void getValues(double [] array)
        {
            Scanner keyboard = new Scanner (System.in);

            //get the values of the months
            for (int i = 0 ; i  < array.length ; i ++)
            {
                    System.out.println("Enter the value for the month "  + (i+1));
                    array[i] = keyboard.nextDouble();
                    if (array[i] < 0 )
                    {
                        System.out.println("The value SHOULD NOT BE a NEGATIVE number");
                        break;
                    }

            }
    }
}

我将代码更改为以下内容:

String  [] month = {"January", "February","March",etc};

for ( int i = 0 ; i < array.length ; i ++)
{
  for (int index = 0; month.length; index++)
   {
     System.out.println("The rainfall value of the " + month[index]);
       array[i] = keyboard.nextDouble();
                if (array[i] < 0 )
                {
                    System.out.println("The value SHOULD NOT BE a NEGATIVE number");
                    break;
                }
    }
 }

它运行了,但我创建了一个无限循环。我在哪里错过了它?十分感谢大家。

标签: javafor-loop

解决方案


您在第二个 for 循环中缺少检查。

for (int index = 0; month.length; index++)

条件应该index < month.length不是month.length


推荐阅读