vendredi 11 septembre 2020

Why is the first item of my array not working with the conditions in my if statement? [duplicate]

so I've written this code to be able to count the number of times a word pops up (word frequency) but I have to have a test case where the first element in the array is not a number and I can't seem to get my if statements to work.. below is my code:

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      
      String [] wordsList = scan.nextLine().split(" ");
      
      if (wordsList[0] == "5") {
         int listSize = Integer.parseInt(wordsList[0]);
         getFrequencyOfWord(wordsList, listSize);
      }
      else if (wordsList[0] == "16") {
         int listSize = Integer.parseInt(wordsList[0]);
         getFrequencyOfWord(wordsList, listSize);
      } 
      else {
         System.out.println("no");
      }
   }
   
   public static void getFrequencyOfWord(String[] wordsList, int listSize) {
      int count;
      int [] occurrences = new int [listSize];
      
      for (int i = 1; i < listSize + 1; i++) {
         count = 0;
         for (int j = 0; j < listSize; j++) {
            if (wordsList[i].equals(wordsList[j + 1])) {
               count++;
            }
            occurrences[i - 1] = count;
         }
      }
      for (int g = 0; g < listSize; g++) {
         System.out.println(wordsList[g + 1] + " "  + occurrences[g]);
      }
   }
}

Below is the code before I added the if statement in main and it works fine with the test cases that have an integer as the first element. For example, the test case is "5 hey hi Mark hi mark" and it works with the code below but the test case I need to work is "hey hi Mark hi mark". It just says compilation error and the code above doesn't work with it. If you could help with this that would be great, thank you.

import java.util.Scanner;

public class LabProgram {
   public static void main(String[] args) {
      Scanner scan = new Scanner(System.in);
      
      String [] wordsList = scan.nextLine().split(" ");
      int listSize = Integer.parseInt(wordsList[0]);
      
      getFrequencyOfWord(wordsList, listSize);
   }
   
   public static void getFrequencyOfWord(String[] wordsList, int listSize) {
      int count;
      int [] occurrences = new int [listSize];
      
      for (int i = 1; i < listSize + 1; i++) {
         count = 0;
         for (int j = 0; j < listSize; j++) {
            if (wordsList[i].equals(wordsList[j + 1])) {
               count++;
            }
            occurrences[i - 1] = count;
         }
      }
      for (int g = 0; g < listSize; g++) {
         System.out.println(wordsList[g + 1] + " "  + occurrences[g]);
      }
   }
}

Aucun commentaire:

Enregistrer un commentaire