Home > Net >  Count characters in Java with NESTED-LOOPS
Count characters in Java with NESTED-LOOPS

Time:12-06

Write a Java program that will use NESTED FOR-LOOPS to prompt the user for a string of characters, and then for each character in the string, count the number of identical characters to its right.

The program should

  1. Ask the user to enter a string of 1 to 25 characters.
    If the length is less than 1 or greater than 25, an error message (“Invalid Input”) should be displayed, and the program should stop.
  2. Examine each character in the string, from left to right (starting at index 0).

For each character, count the number of identical characters to its right (i.e., with higher index) and display that character and the count.

I did this.But it can't work like this.

enter image description here

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String args[]) throws Exception {
        Scanner scanner=new Scanner(System.in);
        String x=scanner.nextLine();
        int count=0;
        String temp="";
        if(x.length()>25||x.length()<1){
            System.out.println("Invalid Input");
        }
        else{
         for(int i=0;i < x.length();i  ){
            char c1=x.charAt(i);
            for(int j=i;j < x.length();j  ){
                char c2=x.charAt(j);  
                if(c1==c2 && temp.indexOf(c1)==-1){
                    count=count 1;
                }
            }
            if(temp.indexOf(c1)==-1){
                temp=temp c1;
                System.out.println(c1 ": " (count-1));
            }
            count=0;
            }
        }
    }
}

CodePudding user response:

To do this, first split the string into chars: x.toCharArray(), then iterate over the chars:

char[] chars = x.toCharArray();
for(int i = 0; i < chars.length; i  ) {
    char current = chars[i];
    // see below
}

Then, just iterate over the string again, from i 1 ( 1 because we already checked the char at i), and compare:

char[] chars = x.toCharArray();
for(int i = 0; i < chars.length; i  ) {
    char current = chars[i];
    int foundSimilar = 0;
    for(int ii = i 1; ii < chars.length; ii  ) {
        char thatChar = chars[ii];
        if (thatChar == current) foundSimilar  ;
    }
    // then just print out how many chars we found
    System.out.println(current   ": "   foundSimilar);
}

As you can see, this yields the same output as on the image: enter image description here

CodePudding user response:

Here you comparing the same character, as i == j.

for(int j=i;j < x.length();j  ){
                char c2=x.charAt(j); 

You can start j from i 1.

  •  Tags:  
  • java
  • Related