首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >循环数组

循环数组
EN

Stack Overflow用户
提问于 2013-07-19 09:00:30
回答 1查看 110关注 0票数 0
代码语言:javascript
复制
  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),并使用这些相应的数字搜索数据文件。并返回相应的号码和它所对应的县。

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

有什么建议吗?谢谢!

EN

回答 1

Stack Overflow用户

发布于 2013-07-19 09:05:48

这有点不清楚,但我想如果输入不正确(不是整数),您想要一些东西来处理吗?使用hasNextInt,这样您将只捕获整数。

代码语言:javascript
复制
Scanner scanner = new Scanner(System.in);
while (!scanner.hasNextInt()) {
    scanner.nextLine();
}
int num = scanner.nextInt();

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

如果您的数字在数组中没有匹配项,如果您想要显示一些内容,只需在您的for块后面添加代码(如果为found == false )。例如:

代码语言:javascript
复制
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仍然为false,因此while循环开始工作,并再次打印请求输入的行。

编辑:由于将这两个概念添加到代码中似乎有问题,下面是整个函数:

代码语言:javascript
复制
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!");
    }
  }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17736510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档