I wanted to implement the following Python function in Java. I have a series of doubts a little simpler and they are the following:
- I wanted to know if
a:b
we are implementing the in operator of other languages like Python I wanted to know if it is the same
count += 1
ascount ++
def sentences(param):` vocales = "AEIOUÁÉÍÓÚÜaeiouáéíóúü" contador = 0 if len(param) > 0: for i in param.split(): if i[0] in vocales: contador += 1 return contador
Java code
public class Inicio {
public static int vocales(String param) {
String comprobacion = "AEIOUÁÉÍÓÚÜaeiouáéíóúü";
int count = 0;
String [] sentence = param.split(" ");
if (param.length() > 0) {
for (String i:sentence) {
if (i.charAt(0):comprobacion) { // Se produce el error
count += 1;
}
}
}
return count;
}
I explain a little how this works in Java.
The first statement you mention is a foreach, it is made up of three parts, the first is the data type of the variable, the second is the name of the variable and the third after the colon is the list from which the elements will be extracted , this is used to iterate the elements of the list that will be assigned to the variable in each iteration, so in your case you will
String words:sentence
iterate the elements of the arraysentence
and in each iteration this element will be assigned to the variablewords
.The second statement, as explained above, the statement will
words.charAt(0):vowels
not work in an if since it does not return a boolean value and actually not in a foreach as explained above, I understand that in Python you evaluate if the first character is contained in the string in java You can do it in several ways, one of them isString.contains(Character.toString(words.charAt(0)))
.The third statement
count+=1
is equal tocount = count + 1
and count++ increases the value of count but it will return the original value of count before the increment, in your case it will work and you will not notice the difference but I leave you an example so that you understand it better:i = 1; j = ++i; (i is 2, j is 2)
i = 1; j = i++; (i is 2, j is 1)
The answer is based on the first version of your question. I hope it helps you.