The purpose of this assignment was to get a phone number and print out how many digits of each were in the phone number.
Ex:
phone number = 555-3311
1 = 2
2 = 0
3 = 2
etc.
Instead of getting how many times the number shows up I just get a square and I'm really confused. I'm sure its some simple error but please don't outright tell me. I'd really appreciate it, if I could learn this on my own but I need a little push in the right direction of where to look.
import java.util.*;
public class CharacterFrequency {
public static Scanner kbd = new Scanner(System.in);
public static void main(String[] args) {
String telephone, output = "";
int index = 0;
char [] numbers = new char[10];
System.out.print("Please enter a 10-Digit telephone number: ");
telephone = kbd.nextLine();
telephone = telephone.replaceAll("[^0-9]","");
System.out.println("\nThe number of times each digit appears:");
for(int count = 0; count < telephone.length(); count++)
{
numbers[telephone.charAt(count) - '0']++;
}
for(int count = 0; count < numbers.length; count++)
{
if(numbers[count] == 0)
{
output += (char)('0' + count) + " - 0\n";
}
if(numbers[count] != 0)
{
output += (char)('0' + count) + " - " + numbers[count]+"\n"; <--- I think the error is on this line
}
}
System.out.println(output);
}
}
Xethiro
6
Newbie Poster
Recommended Answers
Jump to Post@X, with a little rework, line 53 can vanish. That is, just System.out.format instead of lines 45 and 50.
That tosses out the need for the output array.
But let's say you don't want to use System.out.format. Look at Integer.toString
Jump to Post@Xethiro. I gotta ask now. Didn't a google of that find the document and maybe examples like:
http://www.tutorialspoint.com/java/lang/integer_tostring_int.htmI don't mind all this but as a programmer I think you could do a …
Jump to PostLine 50 where you write output += (char)('0' + count) is as if you are thinking C code. I see Java in the tag and I'd use the Java's own Integer.toString(count) instead. Try it Sam I am.
All 9 Replies
rproffitt
2,565
"Nothing to see here."
Moderator
Xethiro
6
Newbie Poster
rproffitt
2,565
"Nothing to see here."
Moderator
Xethiro
6
Newbie Poster
rproffitt
2,565
"Nothing to see here."
Moderator
cgeier
187
Junior Poster
Xethiro
6
Newbie Poster
rproffitt
2,565
"Nothing to see here."
Moderator
Xethiro
6
Newbie Poster
rproffitt
commented:
Skill points added.
+6
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.