Home > Net >  How can I list both indexes of a word in a string array if the word appears more than once?
How can I list both indexes of a word in a string array if the word appears more than once?

Time:01-21

I have a program where I have a list of names, and the output states how many times the name appears and what line(s) the word appears on. Right now, if I have a name that appears twice, it only outputs the line number of the word that appears first. How can I make it so it will say what lines the name is on if it appears more than once?

class Main {
  public static void main(String[] args) {
    String nameList="Joe\nBob\nSteve\nJasper\nZack\nInayah\nKevin\nSheila\nSophie\nAdi\nJasper";
    String[] spl = nameList.split("\n");

    System.out.println(nameList);

    int position = java.util.Arrays.asList(spl).indexOf("Jasper")   1;

    String amount = "Jasper";
    int count = 0;
    for(String word : spl) {
      if(word.equals(amount)) { 
       count  ;
      }
    }
    System.out.println("The name "   amount   " Appears "   count   " Times"); 
    System.out.print("The name appears on line "   position );
    if (count>1) {
      System.out.print(" and line" /*the second line it appears on*/);
    }
  }
}

CodePudding user response:

Here is a simple solution that works for your given input of one name per line.

public class Main {
  public static void main(String[] args) {
    String nameList="Joe\nBob\nSteve\nJasper\nZack\nInayah\nKevin\nSheila\nSophie\nAdi\nJasper";
    String[] spl = nameList.split("\n");
    int lineArr[];
    lineArr = new int[11];
    int line = 0;

    System.out.println(nameList);

    int position = java.util.Arrays.asList(spl).indexOf("Jasper")   1;

    String amount = "Jasper";
    int count = 0;
    for(String word : spl) {
        line  ;
      if(word.equals(amount)) { 
       lineArr[count] = line;
       count  ;
      }
    }
    System.out.println("The name "   amount   " Appears "   count   " Times"); 
    System.out.print("The name appears on line "   position );
    while (count>1) {
      count--;
      System.out.print(" and line "   lineArr[count]);
    }
  }
}

The array lineArr is declared to keep track of the presence of your keyword Jasper. The array needs to have up to the maximum number of lines worth of elements to keep track of whether or not the keyword is present on all lines. You could further improve the program by adding logic that isn't hardcoded and detects the number of lines used to declare the array length.

In your for(String word : sp1) loop, all we have to do is keep track of what line we are on and store that in the lineArr array when the keyword is found.

  •  Tags:  
  • Related