在数组中搜索特定数字并打印出所有相应的变量

时间:2013-07-18 21:41:17

标签: java arrays

void searchForPopulationChange()
  {
     int input;
     int searchCount = 0;

     System.out.println ("Enter the Number for Population Change to be found: ");
     input = scan.nextInt();
     boolean found = false;
     for (searchCount = 0; searchCount < populationChange.length; searchCount++)
     {

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

        System.out.print("WRONG INPUT");
     }

  }

}

你好,上面是我目前的程序。 我有一个问题,让它拉出所有相应的变量。 IE:我输入&#34; 200&#34;,数组中有(2)个单位具有相应的(200)值, 但是,这只打印出其中的一个。

任何人都有快速指示?

1 个答案:

答案 0 :(得分:2)

而不是在找到你的价值时破坏

 for (searchCount = 0; searchCount < populationChange.length; searchCount++)
 {

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

只需在现场打印

 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.print("WRONG INPUT");
 }