(Occurrences of each digit in a string) Write a method that counts the occurrenc
ID: 3627744 • Letter: #
Question
(Occurrences of each digit in a string) Write a method that counts the occurrences of each digit in a string using the following header:
public static int[] count(String s)
The method counts how many times a digit appears in the string. The return value is an array of ten elements, each of which holds the count for a digit. For example, after executing int[] counts = count("12203AB3"), counts[0] is 1, counts[1] is 1, counts[2] is 2, counts[3] is 2.
Use input and output dialog boxes.
The program should keep running until the user enters “quit”.
And here is my code, but I have trouble to complish "The program should keep running until the user enters “quit”.". I will offer the lifesaver to the one solve this problem.
import javax.swing.JOptionPane;
public class CountDigit{
public static void main(String[] args){
String s = JOptionPane.showInputDialog("Enter a 10-digit number, or the word "quit": ");
int[] count = CountDigits.count(s);
for (int i = 0; i < count.length; i++){
if(count[i] != 0)
JOptionPane.showMessageDialog(null, "The occurence of " + i + " is " + count[i]);
}
}
public static int[] count(String s){
int[] count = new int[10];
for (int i = 0; i < count.length; i++){
for(int j = 0; j < s.length(); j++){
if(s.charAt(j) == 48 +i)
count[i]++;
}
}
return count;
}
}
Explanation / Answer
Use this as your new main function. public static void main(String[] args) { while(true) { String s = JOptionPane.showInputDialog("Enter a 10-digit number, or the word "quit": "); if(s.equals("quit")) break; int[] count = count(s); for (int i = 0; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.