Daniel Pereira Daniel Pereira - 1 month ago 6
Java Question

Java: Create a new array from Class

I have my

Fila
class with this:

import java.util.Arrays;

public class Fila {

private int [] fila;

public Fila(int[] fila) {
this.fila = fila;
}

public Fila() {

}

public int[] getFila() {
return fila;
}

public void setFila(int[] fila) {
this.fila = fila;
}

@Override
public String toString() {
return "Fila{" +
"fila=" + Arrays.toString(fila) +
'}';
}
}


Now I want to create a new Array of int on my main and insert new values inputted by user. My main atm have this code:

import java.util.Arrays;
import java.util.Scanner;

public class Main {
public static void main(String[] args) {

Scanner teclado = new Scanner(System.in);
System.out.println("Fila dimension? ");
int n = teclado.nextInt();

Fila [] a = new Fila [n];
System.out.println("Dimension of Fila: "+a.length);
System.out.println("Place that you want to add? ");
int l = teclado.nextInt();

for (int i = l-1; i <= l-1; i++) {
System.out.println("Number? ");
a [i] = teclado.nextInt();
}
System.out.println(Arrays.toString(a));

}
}


But I have incompatible types here:
a [i] = teclado.nextInt();


What I need to do?

Answer

It looks to me like you want:

public class Main {
    public static void main(String[] args) {
        Scanner teclado = new Scanner(System.in);
        System.out.println("Fila dimension? ");
        int n = teclado.nextInt();

        int [] a = new int [n];
        System.out.println("Dimension of Fila: "+a.length);
        System.out.println("Place that you want to add? ");
        int l = teclado.nextInt();

        for (int i = l-1; i <= l-1; i++) {
            System.out.println("Number? ");
            a [i] = teclado.nextInt();
        }
        System.out.println(Arrays.toString(a));

        Fila fila = new Fila(a);
        // Do something else with fila here...
    }
}

WHen you wrote Fila a = new Fila[n] you are in fact creating an array of Fila objects, and not an array of ints.