Search code examples
javastringfor-loopchar

Print the number of commas as well as where they occur within a string


I've tried using a for loop to detect the commas within the given input of "Gil,Noa,Guy,Ari" and then list the location of the commas within the string:

import java.util.Scanner;

public class FindCommas {
   public static void main(String[] args) {
      Scanner scnr = new Scanner(System.in);
      String delimitedData;
      int i;
        int freqOccurred = 0;

      delimitedData = scnr.nextLine();

      for (i = 0; i < delimitedData.length(); ++i) {
         if (Character.isLetter(delimitedData.charAt(i))) {
         System.out.println("Comma found at index " + i);
         }
      }

      for(String subString: delimitedData.split(",")){
         freqOccurred = freqOccurred + 1;
      }
      freqOccurred = freqOccurred - 1;

    System.out.println("Comma occurs " + freqOccurred + " times");
    }
}

The output it produces:

Comma found at index 0

Comma found at index 1

Comma found at index 2

Comma found at index 4

Comma found at index 5

Comma found at index 6

Comma found at index 8

Comma found at index 9

Comma found at index 10

Comma found at index 12

Comma found at index 13

Comma found at index 14

Comma occurs 3 times

It skips the index location of where the commas are and I cannot figure out how to flip it to only produce the index of the commas rather than just the index of the letters.

Expected output:

Comma found at index 3

Comma found at index 7

Comma found at index 11

Comma occurs 3 times

Note: code must not contain arrays.


Solution

  • Answer for those who want it:

       public static void main(String[] args) {
          Scanner scnr = new Scanner(System.in);
          String delimitedData;
          int i;
            int freqOccurred = 0;
       
          delimitedData = scnr.nextLine();
          
          for (i = 0; i < delimitedData.length(); ++i) {
             if (delimitedData.charAt(i) == ',') {
                System.out.println("Comma found at index " + i);
             }
          }
          
          for(String subString: delimitedData.split(",")){
             freqOccurred = freqOccurred + 1;
          }
          freqOccurred = freqOccurred - 1;
    
        System.out.println("Comma occurs " + freqOccurred + " times");
        }
    }