Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

count the number of 4's in a line using Character

Status
Not open for further replies.

Lhuffst

Programmer
Jun 23, 2003
503
0
0
US
I have some code that counts the number of 4's in a line (from a text file) and prints the results. I did it using the String class but have to switch it to using the Character class and I don't have a clue how to do it. I am just learning Java and this is one of the exercises. Thanks for any and all help. lhuffst

Here is the code that works as a string
Code:
String lineInfo = input.nextLine();
		
// get the number of characters in each line	
		
counts+= lineInfo.length();



[b]
// get the number of 4's in each line	
		
			
char[] chars = lineInfo.toCharArray();
for (int i = 0; i < chars.length; i++)
{
  if (chars[i] == '4')
     countFours++;
}
[/b]
 
Is there an assignment or it is just an exercise for self study?
 
Self study -- have to learn Java for work. The book I bought has exercises for practice and those are what I'm trying to work on.
 
The improved for-construct, available since 1.5, is more easy to write and read, and should be used, if you don't need the index (i) for something else:
Code:
for (char c : lineInfo.toCharArray())
{
        if (c == '4')
                countFours++;
}

lineInfo.charAt (i) would be a step less verbose, if you use 1.4 or below.

don't visit my homepage:
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top