如何将这个“计数器”值从一种方法返回到主方法?

时间:2019-05-14 21:22:24

标签: java methods modularity

我正在实践此问题,作为在main方法之外使用方法的实践。这个问题需要我们采取三种不同的方法,每种方法执行不同的任务,但是它们之间不必相互关联。

smallestNumber():接受用户输入的3个数字并输出最小的数字

average():取用户输入的3个数字并输出平均值

countVowels():获取用户输入的短语并输出该短语中的元音数量

对于我来说,我能够将方法1和方法2的值返回给main方法。 对于方法3,当我尝试返回计数器值时,即使短语中有元音,它也始终返回0。

有人可以解释我在做什么错吗? (对于缩进问题很抱歉,我之前从未使用过Stack Overflow)

我不知道为什么它总是返回0

public static int countVowels(String words) {
    int count=0;
    for (int i=0; i<words.length(); i++) {
        if (words.charAt(i) == 'a' || words.charAt(i) == 'e' || words.charAt(i) == 'i' || words.charAt(i) == 'o' || words.charAt(i) == 'u') {
            count++;
        } 
    }
    return(count);

}

3 个答案:

答案 0 :(得分:0)

您的countint(不是String),因此您应该返回int。而不是String.indexOf(String),您应该使用String.charAt(int)(或在for-each上使用String.toCharArray()循环)。不需要增加零,而只考虑小写字母(所以调用String.toLowerCase())。喜欢,

public static int method3(String words) {
    int count = 0;
    for (char ch : words.toLowerCase().toCharArray()) {
        if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
            count++;
        }
    }
    return count;
}

还要考虑一个更有意义的方法名称(例如countVowels())。

答案 1 :(得分:0)

如果您的方法的返回类型为String,则返回一个字符串:

public static String method3(String words){
 int count = 0;
//logic here
return "" + count; // The "" + will convert the count to a string, if that is what you want. 

}

您还可以更改方法的返回类型,以返回int:

public static int method3(String words){
     int count = 0;
    //logic here
    return count;

    }

根据您的逻辑,如果变量 words 中的字符串具有任何元音,则它将使计数增加1,如果没有,则不会对其进行计数并返回0。 如果您发送的是空字符串或不带元音的字符串,则该方法将返回0。

答案 2 :(得分:0)

  • return移动到循环外部(您的代码返回到内部,解释了为什么总是得到0)
  • toLowerCase每个word字符,以说明大小写
  • 制作一组所有元音,并检查其中是否包含word的每个字符(请参阅下一个项目符号)
  • *请注意,您的代码调用的indexOf将始终仅返回第一个匹配项的索引;即使将return移到了循环之外,这也会导致您的代码不一定总是返回正确的答案。 您使用indexOf编写的代码还会使其具有二次O(n ^ 2)运行时(其中n是word的长度)。 我这里的解决方案不使用indexOf,并且在运行时为线性O(n)。您的解决方案和我的解决方案都是恒定的O(1)内存空间。

如下

public static String countVowels(String word){
  int count = 0;

  Set<Character> vowels
    = new HashSet<>(Arrays.asList("a", "e", "i", "o", "u"));
  for(int i = 0; i < words.length(); i++){
    if(vowels.contains(Character.toLowerCase(word.charAt(i)))) {
      count++;
    }
  }

  return "This is the number of vowels " + count;
}

更好(代码样式优化)-使用 for-loop

public static String countVowels(String word){
  int count = 0;

  Set<Character> vowels
    = new HashSet<>(Arrays.asList("a", "e", "i", "o", "u"));
  for(char curChar: word.toCharArray()){
    if(vowels.contains(Character.toLowerCase(curChar))) {
      count++;
    }
  }

  return "This is the number of vowels " + count;
}
相关问题