I have a Java assignment where I need to read in a Character and then count the number of times that character appears in the array. This is what I have so far.
import javax.swing.JOptionPane; public class ArraySring { public static void main(String args[]) { String userChar; userChar = JOptionPane.showInputDialog("Enter a character"); String dow[] = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" }; for(int x=0; x<7; x++) { System.out.println(dow[x]); } System.out.println(); } } // end ArrayStrings
Advertisement
Answer
Here you go:
public static void main(String args[]) { char userChar = JOptionPane.showInputDialog("Enter a character").toLowerCase().charAt(0); int count = 0; String dow[] = // ... for (String str : dow) for (char ch : str.toLowerCase().toCharArray()) if (ch == userChar) count++; System.out.println(count); }