撰寫一個程式,讀取一行文本String并顯示文本中出現的所有字母,每行一個,按字母順序,以及每個字母在文本中出現的次數。
為此,您必須使用int長度型別的陣列26,以便索引處的元素0包含a' 的數量,索引處的元素1包含b' 的數量,依此類推。
允許大寫和小寫字母作為輸入,但將相同字母的大寫和小寫版本視為相同。
提示:使用方法chatAt(int index)的String類指定索引處得到的字串中的個性。
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] letters = new int[26];
char choice;
while (true) {
// taking user input
System.out.println("Please enter text ending with period:");
String text = sc.nextLine();
// converting it lowercase
text = getActualText(text).toLowerCase();
char c = 'a';
for (int i = 0; i < letters.length; i )
// increasing character by 1
letters[i] = countLetters(text, c );
System.out.println("\nThe frequency of the letters");
c = 'a';
for (int i = 0; i < letters.length; i ) {
// showing only those letters whose frequnecy is greater than 0
if (letters[i] != 0)
System.out.println(c ": " letters[i]);
c ;
}
System.out.print("Would you like to try another text?(Y/N) ");
choice = sc.nextLine().charAt(0);
if (choice == 'n' || choice == 'N')
break;
}
}
private static int countLetters(String text, char c) {
int count = 0;
for (int i = 0; i < text.length(); i )
// counting the frequency
if (text.charAt(i) == c)
count ;
return count;
}
/**
* This method will extract the first sentence from a text ending with full stop(.)
*/
private static String getActualText(String text) {
String newText = "";
for (int i = 0; i < text.length(); i ) {
if (text.charAt(i) == '.')
// breaking out of the loop if the full stop is found
break;
// adding it to the text
newText = text.charAt(i) "";
}
return newText;
}
}
uj5u.com熱心網友回復:
嘗試將現有條件更改為以下新條件:
現有條件:(允許不等于0的頻率):
if(letters[i] != 0) {//showing only those letters whose frequency is greater than 0
新條件:(允許大于或等于0的頻率):
if(letters[i] >= 0) {
uj5u.com熱心網友回復:
遍歷文本一次并計算每個字母的出現次數就足夠了。然后只顯示帶有 count 的字母>0。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.print("\nEnter the text: ");
String str = scan.nextLine();
print(histogram(str));
} while (shouldContinue(scan));
}
private static int[] histogram(String str) {
int[] letters = new int[26];
for (int i = 0; i < str.length(); i )
if (Character.isLetter(str.charAt(i)))
letters[Character.toLowerCase(str.charAt(i)) - 'a'] ;
return letters;
}
private static void print(int[] letters) {
System.out.println("The frequency of the letters:");
for (int i = 0; i < letters.length; i )
if (letters[i] > 0)
System.out.println((char)('a' i) ": " letters[i]);
}
private static boolean shouldContinue(Scanner scan) {
while (true) {
System.out.print("Would you like to try another text (Y/N)? ");
String str = scan.nextLine();
if (str.length() != 1)
continue;
if ("Y".equalsIgnoreCase(str))
return true;
if ("N".equalsIgnoreCase(str))
return false;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/406969.html
標籤:
