繁体   English   中英

For循环正在打印出多个打印语句

[英]For loop is printing out multiple print statements

我正在为 class 制作一个程序,它可以打印出一个单词中的元音数量,我们将不胜感激。 目前,程序打印出正确数量的元音,但之前多次打印出打印语句“vowels:”。 我试过移动打印语句和大括号,但它说“错误:'else if'没有'if'”。 我对 Java 完全陌生,如果解决方案显而易见,我很抱歉。 先感谢您:)

      import java.util.Scanner;
         public class Main
        {
             public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
                System.out.print("Enter text: ");
                String text = input.nextLine();
                text = text.toLowerCase();
                int vowels= 0;
                int l;
                l= text.length();

               for (int i = 1; i < text.length(); i++) { 
                 String wordPRT = text.substring(i,i+1);
                  if (wordPRT.compareToIgnoreCase("a")==0 || wordPRT.compareToIgnoreCase("e")==0|| 
                     wordPRT.compareToIgnoreCase("i")==0
                      || wordPRT.compareToIgnoreCase("o")==0
                      || wordPRT.compareToIgnoreCase("u")==0){
                         vowels++;

                    System.out.println("vowels: " + vowels);
                 }
                 else if(vowels<1){

               System.out.print("no vowels");

                }
              }
             }
            }









您在 for 循环中打印所有内容,而不是计算元音并在最后打印。

尝试类似:

int vowelsCounter = 0;
for(...) {
  ... logic to count the vowels
  if(isvowel(string.charAt(i)){
     vowelsCountr++;
  }
}

if(vowelsCounter > 0 ) {
   printSomething
}
else {
  print something else
}

此外,您不应将subString用于此类循环,但string.charAt(i)

将打印语句移出for循环。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter text: ");
        String text = input.nextLine();
        text = text.toLowerCase();
        int vowels = 0;
        int l;
        l = text.length();

        for (int i = 1; i < text.length(); i++) {
            String wordPRT = text.substring(i, i + 1);
            if (wordPRT.compareToIgnoreCase("a") == 0 || wordPRT.compareToIgnoreCase("e") == 0
                    || wordPRT.compareToIgnoreCase("i") == 0 || wordPRT.compareToIgnoreCase("o") == 0
                    || wordPRT.compareToIgnoreCase("u") == 0) {
                vowels++;    
            }
        }
        if (vowels >= 1) {
            System.out.println("vowels: " + vowels);
        } else {
            System.out.print("no vowels");
        }
    }
}

示例运行:

Enter text: Hello
vowels: 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM