为什么我的程序没有输出预期结果?

huangapple go评论72阅读模式
英文:

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);
    }
}
英文:
  1. 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(&quot;Enter: &quot;); 
		Scanner scan = new Scanner(System.in);


		String input = scan.next(); 

		int whitespace = 0;
		int punctuation = 0;
		int consonants = 0;

		for (int i = 0; i &lt; input.length(); i++){ 
			char ch= input.charAt(i);


			if (i == &#39;.&#39; || i == &#39;,&#39; || i == &#39;!&#39; || i == &#39;;&#39; || i ==&#39;?&#39;)
				punctuation++;

			 if ((ch &gt;= &#39;a&#39; &amp;&amp; ch &lt;= &#39;z&#39;) || (ch &gt;= &#39;A&#39; &amp;&amp; ch &lt;= &#39;Z&#39;))  
				consonants++;
	 
			 else if (i == &#39;y&#39; || i == &#39;Y&#39;)
                consonants--;

			else 
				whitespace++;
		} 
		System.out.println(&quot;Consonants: &quot; + consonants);
		System.out.println(&quot;Punctuation: &quot; + punctuation);
		System.out.println(&quot;White spaces: &quot; + 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>



huangapple
  • 本文由 发表于 2020年10月13日 03:42:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64324408.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定