How to go through a string and if it is a vowel add it with a for (String index out of range)

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

How to go through a string and if it is a vowel add it with a for (String index out of range)

问题

import java.util.Scanner;
import java.lang.StringBuilder;

public class ReemplazarVocales {
    public static void main(String[] args) {
        Scanner InputText = new Scanner(System.in);
        StringBuilder str = new StringBuilder();
        
        System.out.println("Escribe una frase\n");
        String Sentence = InputText.next();

        Sentence = Sentence.toLowerCase();
        char Vocal;

        for (int i = 0; i <= Sentence.length(); i++){

            Vocal = Sentence.charAt(i);
            String Consonant = Character.toString(Vocal);
            
            if (Consonant != "a" || Consonant != "e" || Consonant != "i" || Consonant != "o" || Consonant != "u"){
                str.append(Consonant);
            }
        }
        
        System.out.println("\nTu frase sin vocales " + str);
    
    }
}
英文:

I am trying to create a program that loops through a string, and if it is a vowel that adds it to a variable and then displays. The idea is not to use regular expressions so I use a for. And the problem is that it does not show me the result well, can you help me?

import java.util.Scanner;
import java.lang.StringBuilder;

public class ReemplazarVocales {
    public static void main(String[] args) {
        Scanner InputText = new Scanner(System.in);
        StringBuilder str = new StringBuilder();
        
        System.out.println(&quot;Escribe una frase\n&quot;);
        String Sentence = InputText.next();

        Sentence = Sentence.toLowerCase();
        char Vocal;

        for (int i=0;i &lt;= Sentence.length();i++){

            Vocal = Sentence.charAt(i);
            String Consonant = Character.toString(Vocal);
            
            if (Consonant != &quot;a&quot; ||Consonant !=&quot;e&quot; || Consonant !=&quot;i&quot; || Consonant !=&quot;o&quot; || Consonant!=&quot;u&quot;){
                str.append(Consonant);
            }
        }
        
        System.out.println(&quot;\nTu frase sin vocales &quot; + str);
    
    }
}

答案1

得分: 2

代码中存在三个问题:

  1. 你的代码中循环的索引是从 int i=0 循环到 i=length,这会导致越界错误。

由于字符串索引从 0 开始,你可以这样循环:

for (int i=0; i < Sentence.length(); i++) {
    Vocal = Sentence.charAt(i);
    String VocalP = Character.toString(Vocal);

    if (!VocalP.equals("a") && !VocalP.equals("e") && !VocalP.equals("i") && !VocalP.equals("o") && !VocalP.equals("u")) {
        str.append(VocalP);
    }
}
  1. 你需要使用逻辑运算符 (&&) 而不是逻辑或 (||),因为你希望消除所有的元音。

  2. 建议使用 equals 或 equalsIgnoreCase 来进行字符串比较,以比较两个字符串。

英文:

There seem to be three problem in you code:

  1. you are looping from index int i=0 till i=length, which will give you IndexOutOfBound.

Since string indexing start from 0 you can loop like

for (int i=0;i &lt; Sentence.length();i++){

            Vocal = Sentence.charAt(i);
            String VocalP = Character.toString(Vocal);

            if (!VocalP.equals(&quot;a&quot;) &amp;&amp; !VocalP.equals(&quot;e&quot;) &amp;&amp; !VocalP.equals(&quot;i&quot;) &amp;&amp; !VocalP.equals(&quot;o&quot;) &amp;&amp; !VocalP.equals(&quot;u&quot;)){
                str.append(VocalP);
            }
        }
  1. you need to have (&&) instead of Logical (||) because you wish to eliminate all the vowels.

  2. It is adviceable to do string comparision using equals or equalsIgnoreCase to compare two strings

答案2

得分: 1

> 我正在尝试创建一个程序,它会遍历一个字符串,如果是元音字母,就将它添加到一个变量中,然后显示出来。

  1. 你试图获取索引处的字符 Sentence.length(),这是不可能的,因为 Java 将字符存储在字符串中,从索引 0 开始,因此最后一个索引等于字符串长度减一。尝试访问超出限制的索引会导致 StringIndexOutOfBoundsException
  2. 你无需将 char 转换为 String,就可以直接将其添加到 StringBuilder 中;你可以直接将 char 值附加到 StringBuilder 对象
  3. 你需要使用 == 替换 !=
  4. 你需要使用 Scanner#nextLine 替换 Scanner#next,后者在遇到空格时停止扫描输入。

A.

String Sentence = InputText.next();

替换为

String Sentence = InputText.nextLine();

B.

for (int i=0;i &lt;= Sentence.length();i++)

替换为

for (int i = 0; i &lt; Sentence.length(); i++)

C.

Vocal = Sentence.charAt(i);
String Consonant = Character.toString(Vocal);

if (Consonant != &quot;a&quot; ||Consonant !=&quot;e&quot; || Consonant !=&quot;i&quot; || Consonant !=&quot;o&quot; || Consonant!=&quot;u&quot;){
    str.append(Consonant);
}

替换为

Vocal = Sentence.charAt(i);
// String Consonant = Character.toString(Vocal);// It&#39;s not needed

if (Vocal == &#39;a&#39; || Vocal == &#39;e&#39; || Vocal == &#39;i&#39; || Vocal == &#39;o&#39; || Vocal == &#39;u&#39;) {
	str.append(Vocal);
}

我还建议你遵循Java 命名约定,例如 Vocal 应改为 vocalSentence 应改为 sentence,根据命名约定。

英文:

> I am trying to create a program that loops through a string, and if it
> is a vowel that adds it to a variable and then displays.

  1. You are trying to get a character at the index = Sentence.length() which is not possible because java stores the characters in a string starting with index, 0 and therefore the last index is equal to the length-of-the-string minus one. Trying to access an index beyond the limits results in StringIndexOutOfBoundsException.
  2. You do not need to convert a char into a String in order to add it to a StringBuilder; you can append a char value directly to the StringBuilder object.
  3. You need to use == instead of !=.
  4. You need to use Scanner#nextLine instead of Scanner#next which stops scanning the input as soon as it encounters whitespace.

A. Replace

String Sentence = InputText.next();

with

String Sentence = InputText.nextLine();

B. Replace

for (int i=0;i &lt;= Sentence.length();i++)

with

for (int i = 0; i &lt; Sentence.length(); i++)

C. Replace

Vocal = Sentence.charAt(i);
String Consonant = Character.toString(Vocal);

if (Consonant != &quot;a&quot; ||Consonant !=&quot;e&quot; || Consonant !=&quot;i&quot; || Consonant !=&quot;o&quot; || Consonant!=&quot;u&quot;){
    str.append(Consonant);
}

with

Vocal = Sentence.charAt(i);
// String Consonant = Character.toString(Vocal);// It&#39;s not needed

if (Vocal == &#39;a&#39; || Vocal == &#39;e&#39; || Vocal == &#39;i&#39; || Vocal == &#39;o&#39; || Vocal == &#39;u&#39;) {
	str.append(Vocal);
}

I also recommend you follow the Java naming conventions e.g. Vocal should be vocal and Sentence should be sentence as per the naming conventions.

答案3

得分: -1

你写了:

if (VocalP!="a" || VocalP!="e" || VocalP!="i" || VocalP!="o" || VocalP!="u")

仔细观察会发现这个条件永远为真。举个例子,如果只考虑前两个选项:

if (VocalP!="a" || VocalP!="e")

如果字母不是 'a' 或者字母不是 'e',而字母是 'a',条件仍然会被判断为真,因为它不是 'e'。根据你的问题,你应该使用 == 而不是 !=,所以尝试一下:

if (VocalP=="a" || VocalP=="e" || VocalP=="i" || VocalP=="o" || VocalP=="u")
英文:

You wrote:

if (VocalP!=&quot;a&quot; || VocalP!=&quot;e&quot; || VocalP!=&quot;i&quot; || VocalP!=&quot;o&quot; || VocalP!=&quot;u&quot;)

which if you look closely will always be true.
for example if you take the first two options only:

if (VocalP!=&quot;a&quot; || VocalP!=&quot;e&quot;)

if the letter is not 'a' OR the letter is not 'b'

and the letter is 'a' it will still evaluate to true because it is not 'e'
from your question you should be using == instead of !=
so try:

if (VocalP==&quot;a&quot; || VocalP==&quot;e&quot; || VocalP==&quot;i&quot; || VocalP==&quot;o&quot; || VocalP==&quot;u&quot;)

huangapple
  • 本文由 发表于 2020年10月22日 19:52:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64481646.html
匿名

发表评论

匿名网友

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

确定