【问题标题】:Why my program doesn't print the wanted outcome? [closed]为什么我的程序没有打印出想要的结果? [关闭]
【发布时间】:2020-10-12 19:42:53
【问题描述】:
  1. 编写一个 Java 程序,该程序接受输入字符串并确定辅音、元音(不包括“y”)、标点符号(“.”、“,”、“;”、“!”、“?”)的数量,和空白字符('\n'、'\t'、'')。以合理的清晰度将结果打印到控制台。
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

【问题讨论】:

  • 将 {} 用于您的 ifs。
  • 好吧,如果你没有一个变量来保存元音的数量,你怎么能期望打印出适当数量的元音呢。
  • 为什么找到元音时增加consonants,找到y时减少consonants?这不是你被要求做的。另外,为什么有时检查字符,有时检查它的索引?

标签: java


【解决方案1】:
else if ( i== 'y' || i== 'Y')
             consonants--;

您正在使用 i 来检查字符而不是 ch。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    相关资源
    最近更新 更多