I just studied Arrays but I can't use them in a for loop and I can't understand what's wrong with the code and how to actually get this to work.
import java.util.*;
public class DemoCane {
Scanner sc = new Scanner (System.in);
public static int[] cani;
public static void main (String args []){
setQuantitaCani();
for (int i=0; i<=cani[nrcani].lenght; i++){
Cane cani[i] = new Cane();
cani[i] = Cane.setInfo();
cani[i].getInfo();
}
}
public static void setQuantitaCani(){
System.out.println("Quanti cani vuoi aggiungere?");
int nrcani = sc.nextInt();
cani[] = new int[nrcani];
}
}
I wrote the code this way because I want to get an input from the user about how many dogs he want to enter (cani means dogs). Then, for every dog it creates a new dog object from the dog class (in another file, which has compiled fine) and the user has to set his informations. Shall I use a while loop instead?
EDIT: Every error is in this line:
cani[] = new int[nrcani];
<=in the condition. An array of 5 elements will have indices from 0 to 4. Running to index 5 causes anArrayIndexOutOfBoundsException.Cane cani[i] = new Cane();should becani[i] = new Cane();. also your array is of typeintand notCaneCane?setInfo?getInfo?