Java array index out of bounds? - java

Can someone help me with an error posted below? The program runs, but I'm getting an error regarding my main when display donations is called. How can i fix this so it runs? Does it have to do with a syntax error? It's my first time working with arrays so I welcome feedback for good habits. Thanks!
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at donations.processDonations(donations.java:78)
at donations.main(donations.java:33)
import java.util.Scanner; //needed for input
public class donations {
static double[] cashDonations = new double[6]; // stores the cash donations
// from 6 sites
static double[] lbsFood = new double[6]; // stores the pounds of food
// donated from 6 sites
static String[] siteName = new String[6]; // stores the names of the 6 sites
static String bestSiteCash = " "; // stores the site name with the highest
// cash donation
static String bestSiteFood = " "; // stores the site name with the highest
// food donation
static double totalCash = 0; // stores the total cash collected for all
// sites
static double totalFood = 0; // stores the total food pounds collected for
// all sites
static double maxFood = 0; // store the highest food collection
static double maxCash = 0; // stores the highest cash collection
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // needed for input
String anotherCourse = "yes"; // variable to control running program
// again
do {
getDonations();
processDonations();
displayDonations();
// This code ends the do while to run again
System.out.print("Enter yes if you want to run again: ");
anotherCourse = input.next();
input.nextLine(); // causes skipping issue to fix
System.out.print("\n\n\n");
} while (anotherCourse.equalsIgnoreCase("yes"));
} // end of main
public static void getDonations() {
Scanner input = new Scanner(System.in); // needed for input
// Prompt user for site info
for (int i = 0; i < 6; i++) {
System.out.println("Enter site " + (i + 1) + " name: ");
siteName[i] = input.next();
System.out.println("Enter cash donation(USD) for " + siteName[i]
+ ": ");
cashDonations[i] = input.nextDouble();
// double [] cashDonations = new double [6]; You have this already
// at the top
// int i;
// for (i = 0 ; i < 6 ; i++)
// cashDonations[i] = input.nextDouble();
// double [] lbsFood = new double [6];
System.out.println("Enter food donation(lbs.) for " + siteName[i]
+ ": ");
lbsFood[i] = input.nextDouble();
}
}
public static void processDonations() {
totalCash = 0;
totalFood = 0;
maxCash = cashDonations[0];
maxFood = lbsFood[0];
totalCash = cashDonations[1] + cashDonations[2] + cashDonations[3]
+ cashDonations[4] + cashDonations[5] + cashDonations[6];
totalFood = lbsFood[1] + lbsFood[1] + lbsFood[2] + lbsFood[3]
+ lbsFood[4] + lbsFood[5] + lbsFood[6];
}
public static void displayDonations() {
System.out.print("Total Cash Donations are " + totalCash);
System.out.print("Total Food Donations are " + totalFood);
System.out.print("Donation totals for " + siteName[1]);
System.out.print("Total cash: " + cashDonations[1]);
System.out.print("Food donations " +lbsFood[1]);
System.out.println();
System.out.print("Donation totals for " + siteName[2]);
System.out.print("Total cash: " + cashDonations[2]);
System.out.print("Food donations " +lbsFood[2]);
System.out.println();
System.out.print("Donation totals for " + siteName[3]);
System.out.print("Total cash: " + cashDonations[3]);
System.out.print("Food donations " +lbsFood[3]);
System.out.println();
System.out.print("Donation totals for " + siteName[4]);
System.out.print("Total cash: " + cashDonations[4]);
System.out.print("Food donations " +lbsFood[4]);
System.out.println();
System.out.print("Donation totals for " + siteName[5]);
System.out.print("Total cash: " + cashDonations[5]);
System.out.print("Food donations " +lbsFood[5]);
System.out.println();
System.out.print("Donation totals for " + siteName[6]);
System.out.print("Total cash: " + cashDonations[6]);
System.out.print("Food donations " +lbsFood[6]);
System.out.println();
}// end of displayDonations()
}// end of class

static double[] cashDonations = new double[6];
That is an array with 6 spaces, correct. However:
maxCash = cashDonations[0];
totalCash = cashDonations[1] + cashDonations[2] + cashDonations[3] + cashDonations[4] + cashDonations[5] + cashDonations[6];
Here, you are accessing 7 spaces. 0, 1, 2, 3, 4, 5 and 6.

You have several places in your code where you are referring to index 6 directly in your code. Here are a few:
System.out.print("Donation totals for " + siteName[6]);
System.out.print("Total cash: " + cashDonations[6]);
System.out.print("Food donations " +lbsFood[6]);
But all of your arrays are declared to be of length 6.
static double[] cashDonations = new double[6]; // stores the cash donations
// from 6 sites
static double[] lbsFood = new double[6]; // stores the pounds of food
// donated from 6 sites
static String[] siteName = new String[6];
Arrays in Java are 0-based, so an array of length n only has indices 0 through n - 1, or 0 through 5 here. If you need an index 6, make your array length 7.

I noticed that you've made a common "off-by-one" error ¯\_(ツ)_/¯
Here you've properly declared 3 arrays the size of 6:
static double[] cashDonations = new double[6];
static double[] lbsFood = new double[6];
static String[] siteName = new String[6];
Although there are, indeed, 6 elements in each array the first element is referred to as 0
[0], [1], [2], [3], [4], [5]
In your code you call on a 7th element "[6]" that doesn't exist:
totalCash = cashDonations[1] + cashDonations[2] + cashDonations[3]
+ cashDonations[4] + cashDonations[5] + cashDonations[6];
totalFood = lbsFood[1] + lbsFood[1] + lbsFood[2] + lbsFood[3]
+ lbsFood[4] + lbsFood[5] + lbsFood[6];
To fix it you just need to make your elements from 0 to 5:
totalCash = cashDonations[0] + cashDonations[1] + cashDonations[2]
+ cashDonations[3] + cashDonations[4] + cashDonations[5];
totalFood = lbsFood[0] + lbsFood[1] + lbsFood[2]
+ lbsFood[3] + lbsFood[4] + lbsFood[5];
It's an easy mistake because we've been taught that 0 has a value of nothing our whole lives.
Keep programming and don't give up!

Related

Sports game summary using Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
IndexOutOfBounds with array
(5 answers)
Closed 6 years ago.
The basic idea of this assignment is to create a program that can provide a summary and identify who won a "match" in a sports event (football, basketball, Soccer, baseball, etc.)
**This is my code:**
`import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
for (int i = 1; i <= numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
int numberOfScoresT1[] = new int[sc.nextInt()];
System.out.println("How many " + scoreName + " for " + t2N + "?");
int numberOfScoresT2[] = new int[sc.nextInt()];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}`
This is the error I'm receiving:
Please enter game name:
Football
Please enter Football team 1 name:
Dolphins
Please enter Football team 2 name:
Jaguars
What is a score in Fotball called?
Touchdown
How many points per Touchdown in Fotball?
7
What is a period in Fotball called?
Quarter
How many Quarter in Fotball?
4
Quarter #1
How many Touchdown for Dolphins?
3
How many Touchdown for Jaguars?
2
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Team.main(Team.java:36)
I recognize that the arrays I'm using are in the for loop, and I think thats what is causing the problem, but i'm not sure how to fix it.
This is a sample output is supposed to look like:
Quarter #1:
How many Touchdowns for Dolphins? 2
How many Touchdowns for Chargers? 1
Quarter #2:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 1
Quarter #3:
How many Touchdowns for Dolphins? 0
How many Touchdowns for Chargers? 2
Quarter #4:
How many Touchdowns for Dolphins? 3
How many Touchdowns for Chargers? 0
Football Game Results:
Dolphins scored 5 Touchdowns for a score of 35
Chargers scored 4 Touchdowns for a score of 28
Dolphins Win by 7 points!
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum2 += numberOfScoresT2[counter];
Should the second parameter of the loop be
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
seeing as you are accessing numberOfScoresT2 array in the body.
Your inner for loops should be as follows
for (int counter = 0; counter < numberOfScoresT1.length; counter++)
sum1 += numberOfScoresT1[counter];
for (int counter = 0; counter < numberOfScoresT2.length; counter++)
sum2 += numberOfScoresT2[counter];
You have used length of array numberOfScoresT1 instead of array numberOfScoresT2 in second inner for loops.
import java.util.Scanner;
public class Team {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Ask questions about the game type etc.
System.out.println("Please enter game name: ");
String gameName = sc.next();
System.out.println("Please enter " + gameName + " team 1 name: ");
String t1N = sc.next();
System.out.println("Please enter " + gameName + " team 2 name: ");
String t2N = sc.next();
System.out.println("What is a score in " + gameName + " called? ");
String scoreName = sc.next();
System.out.println("How many points per " + scoreName + " in " + gameName + "?");
int scoreValue = sc.nextInt();
System.out.println("What is a period in " + gameName + " called?");
String periodName = sc.next();
System.out.println("How many " + periodName + " in " + gameName + "?");
int numberOfPeriods = sc.nextInt();
int sum1 = 0;
int sum2 = 0;
int numberOfScoresT1[] = new int[numberOfPeriods];
int numberOfScoresT2[] = new int[numberOfPeriods];
for (int i = 0; i <numberOfPeriods; i++) {
System.out.println(periodName + " #" + i);
System.out.println("How many " + scoreName + " for " + t1N + "?");
numberOfScoresT1[i] = sc.nextInt();
System.out.println("How many " + scoreName + " for " + t2N + "?");
numberOfScoresT2[i] = sc.nextInt();
}
sc.close();
for (int counter = 0; counter < numberOfPeriods; counter++) {
sum1 += numberOfScoresT1[counter];
sum2 += numberOfScoresT2[counter];
}
System.out.println("Team 1 scored " + sum1 + " team 2 scored " + sum2);
}
}

Java ArrayList is not adding up correctly

I am having trouble with the logic I think. My results are not adding up correctly. Can someone please help? The problem is in the arrayList.size, nums.length or something. I entered 50 40 60 as my integers.
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + list.get(arraySize)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}
}
You are sorting list so it will return last value from sorted list. Collections.sort(list) is sorting asc so you get max number from the list. First approach,
1) Either you have to manage origanal list before sorting like
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
And get the value from ori.
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
2) Second approach, Create variable which will store temp last entered value. you can use it.
Might it helps!!
So your example like:
public static void main(final String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (input.hasNextInt()) {
list.add(input.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
System.out.printf("%s", "You entered: ");
for (int i = 0; i < nums.length; i++) {
System.out.printf("%d%s", nums[i], ", ");
}
ArrayList<Integer> ori = new ArrayList<Integer>(list);
Collections.sort(list);
int b = Collections.max(list);
int c = Collections.min(list);
int arraySize = nums.length-1;
double sum = 0;
for(int i = 0; i < list.size(); i++)
{
sum += list.get(i);
}
System.out.println(" \nLast Number is : " + ori.get(list.size()-1)
+ "\nLargest Number is: " + b
+ "\nSmallest number is :" + c
+ "\n" + "You entered " + (arraySize+1) + " numbers"
+ "\nTotal numbers added up is: " + sum
+ "\nAverage number is: " + (sum / (nums.length)));
input.close();
}

How do i keep track of correct answers?

public static void main(String[] args) {
Scanner Keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =Keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = Keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
}else{
System.out.println("Wrong!");
}
System.out.println("The correct answer is " +sum);
I have no clue on how to keep track of the correct answers. I need something to keep track of when it prints correct. I don't know what to do though. I know I just need to record the corrects and divide by four. Four because thats how many questions I have in my quiz.
If you just need to keep track of how many right answers were provided, just add an int variable starting with 0 as a value and increment it. If you want to keep track of the questions and answers which were right, create an empty ArrayList and add a string every time a correct answer is provided.
Here an example of the second option:
ArrayList<String> correctAnswers = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
for (int i=0;i<10;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers.add(x + " + " + y + " = " + sum);
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers:");
for (String correctAnswer : correctAnswers) {
System.out.println(correctAnswer);
}
It asks 10 questions, keeps track of the right answers and outputs them after the 10th question.
An example for the first option:
int correctAnswers=0;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your name: ");
String firstname =keyboard.nextLine();
System.out.println("Welcome "+ firstname+ "!"+ " Please answer the following questions:");
int totalAnswers=4;
for (int i=0;i<totalAnswers;i++) {
int x = (int)(20 * Math.random()) + 1;
int y = (int)(20 * Math.random()) + 1;
int sum = (x+y);
System.out.println(x + " + " + y + " = ");
String sInput = keyboard.nextLine();
int answer1 = Integer.parseInt(sInput);
if (answer1 ==sum){
System.out.println("Correct!");
correctAnswers++;
}
else{
System.out.println("Wrong!");
System.out.println("The correct answer is " +sum);
}
}
System.out.println("Correct answers: "+ correctAnswers + "("+correctAnswers*100/totalAnswers+"%)");

I have 2 errors compiling my java Lottery program using arrays

import java.util.Random;
import java.util.Scanner;
public class LotteryGame{
public static void main(String[] args) {
int NUM_DIGITS = 6;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Winning numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " " + lotteryNumbers[5] + " ");
System.out.println("Your numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " " + userDigits[5] +" ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 6) {
System.out.println("First prize!!!");
}
if (sameNum == 5) {
System.out.println("Second prize!!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers, you lost.");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(59);
lotteryNumbers[1] = randNum.nextInt(59);
lotteryNumbers[2] = randNum.nextInt(59);
lotteryNumbers[3] = randNum.nextInt(59);
lotteryNumbers[4] = randNum.nextInt(59);
lotteryNumbers[5] = randNum.nextInt(59);
return lotteryNumbers[5];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter first digit: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter second digit: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter third digit: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter fourth digit: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter fifth digit: ");
userDigits[4] = keyboard.nextInt();
System.out.print("Enter sixth digit: ");
userDigits[5] = keyboard.nextInt();
return userDigits[5];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 6; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}
When I compile I get the following errors-
LotteryGame.java:51: error: incompatible types: unexpected return value
return lotteryNumbers[5];
^
LotteryGame.java:72: error: incompatible types: unexpected return value
return userDigits[5];
^
2 errors
Can any of you help me with these compilation errors? I'm trying to get this to work. The user is supposed to input 6 numbers, and the program is supposed to pick randomly 6 numbers. Using these numbers, the program will compare the numbers with echoed input.
generateNumbers and getUserData are void functions, meaning they don't return anything, so you can't return anything from them.
You probably want to declare them as functions returning int instead:
public static int generateNumbers(int[] lotteryNumbers)
Univerio is correct in answering your original question.
Looking at your test code you might consider removing the return statement on those two functions since you are just populating both arrays.

Methods and arrays

Here is my code:
import java.util.*;
import java.text.*;
public class zadanko4
{
int ile;
public static final int vat8 = 8;
public static final int vat23 = 23;
public static final int vat5 = 5;
//deklaracje zmiennych tablicowych
static double[] price;
static String[] name;
static int[] quantity;
static int[] vat;
//tworzenie tablic
price = new double[ile];
name = new String[ile];
quantity = new int[ile];
vat = new int[ile];
public static void printSellerData(String tekst)
{
System.out.print(tekst);
}
public static void printBuyerData(String company, String taxNo, String phone, String email)
{
System.out.print(company + taxNo + phone + email);
}
public static void printInvoiceDate(Date data)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(data));
}
public static void printInvoiceHeader(String naglowek)
{
System.out.print(naglowek);
}
public static void printInvoiceProduct(String name, int quantity, double price, int vat)
{
System.out.printf(name + quantity + price + vat);
}
public static void readProductsData()
{
//uzytkownik wprowadza liczbe produktow
System.out.println("podaj liczbe produktow");
Scanner scanner = new Scanner(System. in );
ile = scanner.nextInt();
}
public static void main(String[] args)
{
int i;
String line;
for (i = 0; i < ile; i++)
{
System.out.print("Podaj cene produktu nr " + (i + 1) + ": ");
price[i] = scanner.nextDouble();
System.out.print("Podaj nazwe produktu nr " + (i + 1) + ": ");
name[i] = scanner.next();
System.out.print("Podaj ilosc produktu nr " + (i + 1) + ": ");
quantity[i] = scanner.nextInt();
System.out.print("Podaj vat produktu nr " + (i + 1) + ": ");
vat[i] = scanner.nextInt();
System.out.printf("Dane sprzedajacego\n");
printSellerData("Company: MaxDom Ltd, Kochanowskiego 17, 31-782 Krakow, Poland\n");
printSellerData("Tax no: 677-000-21-39\n");
printSellerData("Phone: +48123454943\n");
printSellerData("Email: office#maxdom.pl\n\n");
System.out.printf("Dane kupujacego\n");
printBuyerData("Softpol Ltd, Mickiewicza 5, 31-009 Krakow, Poland\n", "342-909-33-12\n", "+48505392100\n", "office#softpol.eu\n");
// printInvoiceNumber(+numer+);
Date data = new Date();
printInvoiceDate(data);
printInvoiceHeader("|No.|Product desciptrion |Quantity |Unit price |Total |VAT rate |VAT |Gross|");
printInvoiceHeader("|______________________________________________________________________________________________________|");
//printInvoiceProduct("name[i]", ilosc[prod], cena[prod], vat[prod]");
printInvoiceProduct("|" + (i + 1) + " |" + name[i] + " |" + quantity[i] + " |" + price[i] + " |" + (quantity[i] * price[i]) + " |" + (vat[i] / 100.0) + " |" + (quantity[i] * price[i] * (vat[i] / 100.0)) + " |" + (quantity[i] * price[i]) * (1 + (vat[i] / 100.0)));
}
}
}
and my problems:
I have 4 errors like: error: <identifier> expected. It is connected
with arrays but i have no idea what is wrong.
By the last line: printInvoiceProduct.... I want to display 1 product which user entered, but nothing displays.
Why is that?
Create new memory addresses for arrays as you refer them. Like;
static double[] price = new double[ile];
This is also not enough because these static arrays trying to make a static reference to a non-static variable, "ile". So if you want your arrays to be static, just make "ile" static also.
printInvoiceProduct method is declared to pass 4 arguments to it but you've called it by only one String object.
Even if you solve compilation errors you will face again problems.
For example you are creating an array with size zero This will fail. So instead of creating your array objects above; create in the main function after knowing size of array.
So get rid of ile variable. Take input in the main and then instantiate all the array.
Even I don't see a need of class level arrays all can be method local.
On top of that I don't think this is correct platform to solve such problem. Consider putting your problem on
https://codereview.stackexchange.com/

Categories

Resources