ログインしてさらにmixiを楽しもう

コメントを投稿して情報交換!
更新通知を受け取って、最新情報をゲット!

Java質問&情報提供サイトコミュの教えてください・・・。

  • mixiチェック
  • このエントリーをはてなブックマークに追加
おはようございます…
for Loopsを使って文章の母音数、子音数、数字の合計数、
スペース数、その他、そして合計数を表したいのですが…
合計数しかでず、おまけにその他まで合計数と同じに
なってしまってうまくいきません><!!
どなたかもしよろしかったら訂正していただけないで
しょうか…よろしくお願いします。
問題:
1.Write a Java program that implements this algorithm:
(a)ask the user to enter a sentence
(b)get the String input by using class Scanner method nextLine(). (Note: do not use method next(), or you will only get the first word.)
(c)store the sentence as a String
(d)use a for loop to loop through each character in the sentence
(e)use the String method charAt(position) to get each character from the sentence
(f)use if-else statements to count the number of vowels, consonants, digits, spaces, and other characters
(g)display the output

Example:
Enter a sentence: 12,345 Quick Brown Foxes Jumped Over 67,890 Lazy Dogs!!??

vowels = 11
consonants = 22
digits = 10
spaces = 8
other = 6
total = 57


import java.util.Scanner;

public class Sentenceprob {

public static void main(String[] args) {
char ch = 0;
String str;
Scanner input = new Scanner(System.in);
System.out.print("Enter a sentence: ");
str = input.nextLine();
if (str.length() > 0) {
int vowels = 0;
int spaces = 0;
int consts = 0;
int digits = 0;
int other = 0;
int total = str.length();
for (int i = 0; i < str.length(); i ++) {
char char1 = str.charAt(i);;
if (Character.isDigit(ch)) {
digits++;
} else if (Character.isLetter(ch)) {
if (ch == 'a' || ch == 'e' || ch == 'i'
|| ch == 'o' || ch == 'u'||ch== 'A'||ch=='E'
||ch=='I'||ch=='O'||ch == 'U'){
vowels++;
} else {
consts++;
}
} else if (Character.isWhitespace(ch)) {
spaces++;
} else {
other++;
}
}
System.out.println("vowels = " + vowels);
System.out.println("consonants = " + consts);
System.out.println("digits = " + digits);
System.out.println("spaces = " + spaces);
System.out.println("other = " + other);
System.out.println("total = " + total);
}
}
}

コメント(3)

ざっと読んだだけですが、とりあえず
ch
で判定しているところを
char1
に変えてみては?

chへの代入が初期化時のみに見えます。
char char1 = str.charAt(i);

ch = str.charAt(i);

に変えるほうが簡単な気がしてきました。
rayさん、
どうもありがとうございます。
ただ読んだだけで気づくなんて・・・すごすぎる!!
おかげさまでバッチリ動きました!!
よかったぁ!!ホントに感謝です!!

ログインすると、みんなのコメントがもっと見れるよ

mixiユーザー
ログインしてコメントしよう!

Java質問&情報提供サイト 更新情報

Java質問&情報提供サイトのメンバーはこんなコミュニティにも参加しています

星印の数は、共通して参加しているメンバーが多いほど増えます。

人気コミュニティランキング