0
  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)并使用这些相应的数字搜索数据文件。并返回对应的数字和对应的县。

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

任何指针?谢谢!

4

1 回答 1

2

有点不清楚,但我假设如果输入不正确(不是整数),你想要处理一些东西?使用hasNextInt所以你只会捕获整数。

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

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

如果您想在您的号码在数组内不匹配时显示某些内容,只需在for块后添加代码 if 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!");
}

由于 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!");
    }
  }
}
于 2013-07-19T01:05:47.810 回答