英文:
Why my program doesn't print the wanted outcome?
问题
import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        System.out.print("Enter: ");
        Scanner scan = new Scanner(System.in);
        String input = scan.next();
        int whitespace = 0;
        int punctuation = 0;
        int consonants = 0;
        for (int i = 0; i < input.length(); i++) {
            char ch = input.charAt(i);
            if (ch == '.' || ch == ',' || ch == '!' || ch == ';' || ch == '?')
                punctuation++;
            if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
                consonants++;
            else if (ch == 'y' || ch == 'Y')
                consonants--;
            else
                whitespace++;
        }
        System.out.println("Consonants: " + consonants);
        System.out.println("Punctuation: " + punctuation);
        System.out.println("White spaces: " + whitespace);
    }
}
英文:
- Write a Java program that takes an input string and determines the number of consonants, vowels (‘y’ excluded), punctuation (‘.’, ‘,’ , ‘;’ , ‘!’ , ‘?’), and whitespace characters (‘\n’, ‘\t’, ‘ ’). Print the results to the console with reasonable clarity in output.
 
import java.util.Scanner;
public class a {
	public static void main(String[] args) {
		System.out.print("Enter: "); 
		Scanner scan = new Scanner(System.in);
		String input = scan.next(); 
		int whitespace = 0;
		int punctuation = 0;
		int consonants = 0;
		for (int i = 0; i < input.length(); i++){ 
			char ch= input.charAt(i);
			if (i == '.' || i == ',' || i == '!' || i == ';' || i =='?')
				punctuation++;
			 if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))  
				consonants++;
	 
			 else if (i == 'y' || i == 'Y')
                consonants--;
			else 
				whitespace++;
		} 
		System.out.println("Consonants: " + consonants);
		System.out.println("Punctuation: " + punctuation);
		System.out.println("White spaces: " + whitespace);
	}
}
Enter: yuuh.
Consonants: 4
Punctuation: 0
White spaces: 1
答案1
得分: 1
else if (i == 'y' || i == 'Y')
             consonants--;
你正在使用 i 来检查字符,而不是使用 ch。
<details>
<summary>英文:</summary>
else if ( i== 'y' || i== 'Y')
consonants--;
You are using i to check the character instead of ch.
</details>
				通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论