Buenas tardes. I have created a boolean array and made the inserted indices return true to the cell. What I want is that the toString method prints the index of the cell in which the value is true and "---" in those in which it is false. I've given it 7 laps but I can't... Thanks
public class TestBooleana {
public static void main(String[] args) {
// TODO Auto-generated method stub
Booleana one = new Booleana(1, 18, 23, 45, 47, 79, 12);
System.out.println(one.toString());
}
}
class Boolean
class Booleana{
int talla = 100;
boolean[] enteros = new boolean[talla];
public Booleana(int... num) {
for(int a: num)
insertar(a);
}
public void insertar(int a) {
if(a < talla) enteros[a] = true;
}
public String toString() {
for(int i = 0; i < enteros.length; i++) {
if(enteros[i] == true) return i + " ";
}
return "---";
}
}
You have two problems, the first is that in your insert method, what does not meet your condition you are not assigning anything to, in your case according to your logic the value inserted if the condition is not met should be
false
, so this part of your code:It would look like:
With this, we go to your method
toString
, where the problem is that you are trying to concatenate while returning values, which of course won't work.You should keep something in mind:
The solution to this is to create an
String
aside, which will be the one that we return at the end of the function, without using return inside the loop .So your method looks like this
toString
:With this it would already work, keep in mind that the shorthand if:
It is actually a short assignment depending on conditionals, where character
?
represents aif
and character:
represents aelse
, there is no direct representation ofelse if
in a shorthand if.What is fulfilled will be what will be assigned as a value to the variable.
Another error you have is this one here:
I'm not saying it's wrong, because in some programming languages you can omit the
{}
, but if I didn't put them it gave me strange results so I had to put them infor
:So your complete corrected code (I've put the classes together in one place just for testing), would look like this:
I've decided to put the full code at the end so we can compare it to the edits made to your code so we don't get lost.