循环数组

时间:2013-07-19 01:00:30

标签: java arrays

  void searchForPopulationChange()
  {
     String goAgain;
     int input;
     int searchCount = 0;
     boolean found = false;

     while(found == false){
        System.out.println ("Enter the Number for Population Change to be found: ");
        input = scan.nextInt();



        for (searchCount = 0; searchCount < populationChange.length; searchCount++)
        {
           if (populationChange[searchCount] == input)
           {
              found = true;
              System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
           } 

        }


     }
  }

}

您好! 我正在研究一种将用户输入的方法, 让我们说(5000)并使用那些相应的数字搜索数据文件。 并返回相应的数字,以及与之对应的县。

但是,我能够运行此代码以返回正确的值, 但是当我输入“不正确”的值时,我无法让它运行。

任何指针? 谢谢!

1 个答案:

答案 0 :(得分:2)

有点不清楚,但我想如果输入不正确(不是整数)你想要处理什么?使用hasNextInt,这样您就只能捕获整数。

Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
    scanner.nextLine();
}
int num = scanner.nextInt();

这将保持循环输入,直到它是一个有效的整数。您可以在循环中包含一条消息,提醒用户输入正确的数字。

如果您希望在数组内部数字不匹配时显示某些内容,只需在for阻止后添加代码,如果found == false。例如:

for (searchCount = 0; searchCount < populationChange.length; searchCount++)
    {
       if (populationChange[searchCount] == input)
       {
          found = true;
          System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
       } 

    }
if (found == false) {
     System.out.println("Error, No records found!");
}

由于发现仍然是假的,您的while循环开始并打印您的行,请求再次输入。

编辑:由于您似乎在将这两个概念添加到代码中时遇到问题,因此这里有整个功能:

void searchForPopulationChange() {
 String goAgain;
 int input;
 int searchCount = 0;
 boolean found = false;

 while(found == false){
    System.out.println ("Enter the Number for Population Change to be found: ");
    Scanner scanner = new Scanner(System.in);
    while (!scanner.hasNextInt()) {
      scanner.nextLine();
      }
    input = scanner.nextInt();

    for (searchCount = 0; searchCount < populationChange.length; searchCount++)
    {
       if (populationChange[searchCount] == input)
       {
          found = true;
          System.out.print(""+countyNames[searchCount]+" County / City with a population of "+populationChange[searchCount]+" individuals\n");
       } 

    }

    if (found == false) {
       System.out.println("Error, No records found!");
    }
  }
}