【问题标题】:Method to check vowels in a string [duplicate]检查字符串中元音的方法[重复]
【发布时间】:2017-04-12 17:02:19
【问题描述】:
public static void main(String[] args) {
    Scanner Input= new Scanner(System.in);
    System.out.print("Enter String: ");
    String s =Input.nextLine();
    int index = s.length();
    boolean isVowel= true;
    isVowel = vowels(s,index);
    if(isVowel==true)
        System.out.println("Its Vowel");
}
public static boolean vowels(String s,int index){
    String small=s.toLowerCase();
    String large = s.toUpperCase();
    char z=s.charAt(s.length()-1);
    if (s==small) {
        large = s.toUpperCase();
        if(s==large){
        }
        for (int i = 0; i < s.length(); i++) {
            if (z=='A'||z=='E'||z=='I'||z=='O'||z=='U') {
                System.out.println("Character at " + s.charAt(s.length()-1) + " is a vowel");
                return true;
            } else if(z!='A'||z!='E'||z!='I'||z!='O'||z!='U'){
                System.out.println("The String contains no Vowels");    
                return false;
            }
        }
    }
    return true;
    }
}

它不断返回最后一个打印语句,“字符串不包含元音” 有什么建议吗?

【问题讨论】:

  • 请格式化您的代码并正确解释您的问题。阅读stackoverflow.com/help/how-to-ask
  • 你想要的输出是什么?
  • 单步调试您的代码,我们不是调试服务。
  • 您似乎错误地嵌套了很多东西。这可能是由于格式不正确。您的 for 循环在 if(s==small) 内。

标签: java string methods char


【解决方案1】:
import java.util.*;

public class Solution{
    public static void main(String[] args) {
        Scanner Input= new Scanner(System.in);
        System.out.print("Enter String: ");
        String s =Input.nextLine();
        if(vowels(s)) System.out.println("It contains a vowel!");
        else System.out.println("It does not!");
    }
    public static boolean vowels(String s){
        String word = s.toUpperCase();
        char[] words = word.toCharArray();
        for(int i = 0; i<words.length; i++){
            char z = words[i];
            if (z=='A'||z=='E'||z=='I'||z=='O'||z=='U') return true;
        }
        return false;
    }

}

如果我理解你的问题,我认为上面的代码应该可以做到。

【讨论】:

    猜你喜欢
    • 2011-11-22
    • 2014-03-16
    • 1970-01-01
    • 1970-01-01
    • 2016-08-09
    • 2015-01-22
    • 1970-01-01
    • 2018-07-09
    • 2016-02-12
    相关资源
    最近更新 更多