Java- 使用嵌套for循环从用户输入中删除元音

huangapple go评论77阅读模式
英文:

Java- Remove vowels from user input using nested for loop

问题

import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        
        char[] vowels = {'a', 'e', 'i', 'o', 'u',
                         'A', 'E', 'I', 'O', 'U'}; // 字符数组
        
        Scanner in = new Scanner(System.in);
        System.out.println("输入短语:");
        String phrase = in.nextLine();

        for (int i = 0; i < phrase.length(); i++) {
            for (int j = 0; j < vowels.length; j++) {
                char ch = vowels[j];
                char ch2 = phrase.charAt(i);
                if (ch == ch2) {
                    phrase = phrase.replace(phrase.charAt(i), ' ');
                }
            }
        }
        System.out.println(phrase);
    }
}
英文:

So I've seen this simple question and answer a few times and I just wanted to try a different way to solve it.
My solution does work- it replaces every vowel with an empty char.
However, I've been trying to figure out a way in my code where the char can be simply removed and not replaced with empty char ' '.

For example...
In my code, if the user inputted: happy, the result is h ppy

Although this does answer the question, I would like to also see the output: hppy

Hopefully, I can get some help, thanks!

import java.util.Scanner;

public class Main {
    public static void main(String args[]){
        
        char [] vowels = {&#39;a&#39;,&#39;e&#39;,&#39;i&#39;,&#39;o&#39;,&#39;u&#39;,
                            &#39;A&#39;,&#39;E&#39;,&#39;I&#39;,&#39;O&#39;,&#39;U&#39;};//char array
        
        
        Scanner in = new Scanner(System.in);
        System.out.println(&quot;Enter phrase: &quot;);
        String phrase = in.nextLine();
        

        for (int i = 0; i &lt; phrase.length(); i++) {
            for (int j = 0; j &lt; vowels.length; j++) {
                char ch = vowels[j];
                char ch2 = phrase.charAt(i);
                if (ch == ch2) {
                    phrase = phrase.replace(phrase.charAt(i), &#39; &#39;);
                    
                   
                }
                
            }
           
        }
         System.out.println(phrase);

</details>


# 答案1
**得分**: 2

这应该可以运行:`phrase.replaceAll("[aeiouAEIOU]", "")`

<details>
<summary>英文:</summary>

This ought to work: `phrase.replaceAll(&quot;[aeiouAEIOU]&quot;, &quot;&quot;)`

</details>



huangapple
  • 本文由 发表于 2020年5月5日 04:12:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/61600790.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定