I need help on writing a program about counting how many times a letter in a given word is repeated in alphabetical order. Lower and upper case letters are equals and it has to work for numbers as well. For example:
we have to use array and loops. also, it must not count the space if there is more than 1 word /number given and it should also prompt the user if they want to continue or not. If not then they should enter a dot '.' or when there's a dot '.' after the word, it should close the program after counting the letters.
University
e:1 i:2 n:1 r:1 s:1 t:1 u:1 y:1
import java.util.Scanner;
import java.lang.Character;
public class Array {
public static void main(String[] args) {
Scanner input=new Scanner (System.in);
int[] letters =new int [26];
String str= input.nextLine();
str=str.toLowerCase();
for (int i=0; i<str.length(); i++)
{
letters[i]=0;
}
System.out.println(str.length());
System.out.println(char2int('a'));
System.out.println(char2int ('D'));
}
public static int char2int (char c) {
return Character.toLowerCase(c)-(int)'a';
}
}
This comes out to, for example
me
2
0
3
I'm going to give you a big hint, what you need to do is call a method (say countLetters
) that takes a word and a letter - so that would be,
// Count the "letter"(s) in the word.
public static int countLetters(String word, char letter) {
int count = 0;
if (word != null) {
char lc = Character.toLowerCase(letter);
for (char c : word.toCharArray()) {
if (lc == Character.toLowerCase(c)) {
count++;
}
}
}
System.out.printf("%s: %d\n",
String.valueOf(letter), count);
return count;
}
public static void main(String[] args) {
String test = "Universe";
countLetters(test, 'e');
countLetters(test, 'u');
}
Output is
e: 2
u: 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.