我在scala中的过滤器循环不起作用?

时间:2022-05-02 03:07:02
for(i <- data){
        if(i != 'a' || i != 'e' || i != 'i' || i != 'o' || i != 'u'){
            myArray(i) = i;
            println(myArray(i));
        }
    }

Data is a passed in string, and myArray variable is a char array. Why is it that when the char selected is in-putted into myArray it can be a vowel? Please help, thanks.

数据是一个传入的字符串,myArray变量是一个char数组。为什么选择的char被嵌入到myArray时它可以是一个元音呢?请帮助,谢谢。

2 个解决方案

#1


2  

You need to change your if condition like:

你需要改变你的if条件,比如:

if(i != 'a' && i != 'e' && i != 'i' && i != 'o' && i != 'u')

You read it as if i is not a and not e and other then only its not a vowel. Also don't use i which will be value of your data as index of an array. Use a variable outside for loop something like:

你读它的时候就好像我不是a,不是e,然后它不是元音。也不要使用i,它是数据的值作为数组的索引。在循环外部使用一个变量,比如:

var index = 0

and use this index variable and increment it.

然后使用这个索引变量并增加它。

#2


2  

I think more functional way to do the same is:

我认为更实用的方法是:

 def filterVowels(data: Array[Char]): Array[Char] = {
    data filter (isVowel);
  }
  val isVowel = Set('a', 'e', 'i', 'o', 'u') 

#1


2  

You need to change your if condition like:

你需要改变你的if条件,比如:

if(i != 'a' && i != 'e' && i != 'i' && i != 'o' && i != 'u')

You read it as if i is not a and not e and other then only its not a vowel. Also don't use i which will be value of your data as index of an array. Use a variable outside for loop something like:

你读它的时候就好像我不是a,不是e,然后它不是元音。也不要使用i,它是数据的值作为数组的索引。在循环外部使用一个变量,比如:

var index = 0

and use this index variable and increment it.

然后使用这个索引变量并增加它。

#2


2  

I think more functional way to do the same is:

我认为更实用的方法是:

 def filterVowels(data: Array[Char]): Array[Char] = {
    data filter (isVowel);
  }
  val isVowel = Set('a', 'e', 'i', 'o', 'u')