I'll start by saying I am a Java (/programming) newbie and this is my first question on the website.
Just learnt how to make an ordered list in Java using recursive nodes. Everything was easy until I ran into this exercise asking me to write a method that would double whatever value is contained in each node. Here is the code I tried to write:
public class ListaInteri<E extends Integer>
{
private NodoLista inizio;
// Private inner class each instance of these has a raw type variable and a
// ref
// to next node in the list
private class NodoLista
{
E dato;
NodoLista pros;
}
// method that adds whatever is meant by x to the begging of the list
public void aggiungi(E x)
{
NodoLista nodo = new NodoLista();
nodo.dato = x;
if (inizio != null)
nodo.pros = inizio;
inizio = nodo;
}
// a method that switches last and first elements in the list
public void scambia()
{
E datoFine;
if (inizio != null && inizio.pros != null) {
E datoInizio = inizio.dato;
NodoLista nl = inizio;
while (nl.pros != null)
nl = nl.pros;
datoFine = nl.dato;
inizio.dato = datoFine;
nl.dato = datoInizio;
}
}
// and here is the problem
// this method is supposed to double the value of the raw type variable dato
// of each node
public void raddoppia()
{
if (inizio != null) {
NodoLista temp = inizio;
while (temp != null) {
temp.dato *= 2;
}
}
}
// Overriding toString from object (ignore this)
public String toString(String separatore)
{
String stringa = "";
if (inizio != null) {
stringa += inizio.dato.toString();
for (NodoLista nl = inizio.pros; nl != null; nl = nl.pros) {
stringa += separatore + nl.dato.toString();
}
}
return stringa;
}
public String toString()
{
return this.toString(" ");
}
}
and here is the error the compiler gives me.
ListaInteri.java:39: inconvertible types
found : int
required: E
temp.dato*=2;
^
1 error
Now keep in mind any kind of help would be greatly appreciated anyway here are the questions I would like an answer to.
EDIT; sorry had to make it readable should be ok now. EDIT2: almost readable argh!
Integer is final, it cannot be extended. Therefore, your use of Generics is pointless (though syntactically valid), and you might as well just use int - the problem will then disappear.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With