对于.equals,是否有相同或替代?

时间:2017-10-02 21:42:09

标签: java

我应该编写一个程序,用户输入一个字符串,其中包含每个元音的数量,以及有多少非元音。

import java.util.*;

public class Strings {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner MyScan = new Scanner(System.in);

        int countnon = 0;
        for (int i = 0; i < test.length(); i++) {
            if (test.substring(i, i + 1).equals("a") || test.substring(i, i + 1).equals("e")
                    || test.substring(i, i + 1).equals("i") || test.substring(i, i + 1).equals("o")
                    || test.substring(i, i + 1).equals("u")) {
                break;
            } else {
                countnon++;
            }
        }
        System.out.println(countnon + " occurences of non-vowels");
        MyScan.close();
    }
}

出于某种原因,最后一段代码,即具有countnon变量的代码,没有给出正确的数字值。我做错了什么?我试着调试一些代码,但我找不到我错的地方。

1 个答案:

答案 0 :(得分:0)

    int countnon = 0;
    for (int i = 0; i < test.length(); i++) {
        if (test.substring(i, i + 1).equals("a") || test.substring(i, i + 1).equals("e")
                || test.substring(i, i + 1).equals("i") || test.substring(i, i + 1).equals("o")
                || test.substring(i, i + 1).equals("u")) {
            break;  // HERE
        } else {
            countnon++;
        }
    }

您已使用break,因此您会在找到第一个元音时立即停止。这意味着如果你的所有非元音都出现在字符串中的元音之前,你只会得到正确的答案。

改为使用continue

或者,根本不使用任何东西:空块就足够了。

或者,改变你的状况:

if (!string.equals("a") && !string.equals("e") /* etc */) {
  countnon++;
}
相关问题