简体   繁体   中英

Searching an array for specfic numbers and printing out all corresponding variables

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");
     }

  }

}

hello, above is currently my program. I am having an issue with having it pull out ALL of the corresponding variables. IE: I enter "200", there are (2) units in the array that have a corresponding (200) value, however, this only prints out 1 of them.

Anyone have any quick pointers?

instead of breaking when you find your value

 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");
 }

just print it on the spot

 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");
    }
 }

you can still check for wrong input after your loop is finished

 if (found == false)
 {
    System.out.print("WRONG INPUT");
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM