Click here to Skip to main content
15,887,302 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
This is my code so far. I am new at Java code so I am lost on how to fix this.


import java.io.*;
import java.util.*;
public class Main {

    public static void main(String[] args) {
        int n;

        Scanner input = new Scanner(System.in);

        System.out.println("\n\nWelcome to the 2023 Kootney Freestyle Cup sign up! Please enter the following information. \n");

        System.out.println("Number of Participants: ");
        int i = input.nextInt();

        String [] name = new String[i];
        int [] age = new int[i];
        int [] compNumber = new int[i];

        for(n=0; n<i; n++) {
            input.nextLine();
            System.out.println("Name: ");
            name[i] = input.nextLine();

            System.out.println("Age: ");
            age[i] = input.nextInt();

            System.out.println("Competition Number: ");
            compNumber[i] = input.nextInt();
        }
        double price;
        price = i * 12.50;

        System.out.println("Receipt \n\n");

        for(n=0; n<i; n++) {
            System.out.println("Participant " + i + ":" + name);
            System.out.println("Age: " + age);
            System.out.println("Competition Number: " + compNumber);
            System.out.println("$" + price);
            System.out.println("\nThank you");
        }

    }
}









It is displaying this error


Welcome to the 2023 Kootney Freestyle Cup sign up! Please enter the following information. 

Number of Participants: 
2
Name: 
Bill Java
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
	at Main.main(Main.java:21)

Process finished with exit code 1


What I have tried:

I have tried a lot of websites but just can't figure it out.
Posted
Updated 7-Apr-23 18:25pm

1 solution

Check the index of your arrays in your for loop:
Java
for(n=0; n<i; n++) {
    //...
    name[i] = input.nextLine();
    //...
    age[i] = input.nextLine();
} 

i is the dimension of the array. You should be using n the loop variant variable, instead.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900