Java String Counter

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • TrippW06
    New Member
    • Oct 2008
    • 1

    Java String Counter

    I working on a program to analyze a string and tell the user how may of each char is in the sentence. I have it sorta working but cant fidgure it out. I get a weird last line and my method to remove the "." totally kills the program. I had java several years ago and a friend has asked me to help. Any Ideas?


    Code:
    import java.util.*;
    import java.io.*;
    public class example{
    static Scanner console= new Scanner(System.in);
    public static void main(String[] args)
    {
    System.out.print("Please Enter aString ");
    System.out.println();
    console.useDelimiter("\\n");
    String str =console.next();
    
    String strClean = str.replaceAll(" ","");
    //String strClean1 = strClean.replaceAll(".","");
    System.out.println (strClean);
    
    char[]third =strClean.toCharArray();
    			for(int counter =0;counter<third.length;counter++)
    			{ char letter= third[counter];
    
    				int flage=0;
    				for ( int i=0; i<third.length; i++)
    				{
    					if (letter==third[i])
    
    						flage++;
    
    
    				}
    				if(counter==0)
    				{
    System.out.println("The letter ="+letter+" is repeated "+flage+" # of Times ");
    	continue;
    				}
    				boolean flag=false;
    				for(int j=counter-1;j>=0;j--)
    				{
    					if(letter==third[j])
    						flag=true;
    				}
    				if(!flag)
    				{
    
    System.out.println("The letter ="+letter+" is repeated "+flage+" No of Times ");
    				
    				
    				}
    
    			}
    	}
    
    
    }
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Why don't you use a Map<Character, Integer> and use that for every character
    you read from the input?

    kind regards,

    Jos

    Comment

    Working...