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);
}
}
Related
I need to first ask the user to input how many problems they want to do. Then generate the first, then the second after they answer the first and so on.
public static void main(String[] args) {
int number1 = (int) (Math.random() * 40 + 10), number2 = (int) (Math.random() * 40 + 10), uanswer, ianswer, counter, icounter,
acounter, counter1, ui, aacounter, bcounter;
Scanner input = new Scanner(System.in);
System.out.println("How many problems do you want to do?");
ui = input.nextInt();
counter = 1;
icounter = 1;
acounter = counter + icounter;
{
System.out.print("What is " + number1 + " + " + number2 + "? ");
}
uanswer = input.nextInt();
ianswer = number1 + number2;
while (counter < 10000 && icounter < 1000 && acounter < 1000 && number1
+ number2 != uanswer) {
System.out.println("Incorrect, the answer is "
+ ianswer + ", " + icounter + " out of " + icounter + " incorrect. Try again?");
icounter++;
acounter++;
uanswer = input.nextInt();
}
if (ianswer == ianswer) {
aacounter = acounter - 1;
bcounter = icounter - 1;
System.out.println("Correct, the answer is " + ianswer
+ ", " + counter + " out of " + aacounter + " correct, "
+ bcounter + " out of " + aacounter + " incorrect.");
}
}
With my current code, I only see one problem, even though I asked for 2 or more problems at the beginning.
You need to add a loop around this statement:
System.out.print("What is " + number1 + " + " + number2 + "? ");
like:
for(int i=0; i<ui; i++){
System.out.print("What is " + number1 + " + " + number2 + "? ");
...
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+"%)");
The code I have written so far, is below and works however I am having a few issues with it
1) It runs the program more than once
2) The numbers don't seem to be very random, it seems to pick the same numbers out
3) I need the value 1 to display as Ace, the value 11 to display as Jack, the value 12 to display at Queen and the value 13 to display as King
I have gone over my code several times and cant figure out why it is doing point 1
I am not sure if it is just me, or if it is an issue with point 2
I know I need an if statment to do number 3 but not quite sure where to put it
The idea of the program is for the player to verse the computer and draw 7 cards each in turn, (suite doesn't need to be included) and output each card followed by the winner, with 1 output as ace, 11 output as jack, 12 output as queen and 13 output at king.
Many thanks for your help
import java.math.*;
import java.util.*;
public class CardProj {
public static void main(String[] args) {
Scanner mykbd = new Scanner(System.in);
Random rn = new Random();
{
for (int i = 0; i < 14; i++) {
int card1player = 0;
int card2player = 0;
int card3player = 0;
int card4player = 0;
int card5player = 0;
int card6player = 0;
int card7player = 0;
int card1Computer = 0;
int card2Computer = 0;
int card3Computer = 0;
int card4Computer = 0;
int card5Computer = 0;
int card6Computer = 0;
int card7Computer = 0;
System.out.println("Player Card 1: " + card1player);
card1Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 1: " + card1Computer);
System.out.println("");
card2player = rn.nextInt(7) + 1;
System.out.println("Player Card 2: " + card2player);
card2Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 2: " + card2Computer);
System.out.println("");
card3player = rn.nextInt(7) + 1;
System.out.println("Player Card 3: " + card3player);
card3Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 3: " + card3Computer);
System.out.println("");
card4player = rn.nextInt(7) + 1;
System.out.println("Player Card 4: " + card4player);
card4Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 4: " + card4Computer);
System.out.println("");
card5player = rn.nextInt(7) + 1;
System.out.println("Player Card 5: " + card5player);
card5Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 5: " + card5Computer);
System.out.println("");
card6player = rn.nextInt(7) + 1;
System.out.println("Player Card 6: " + card6player);
card6Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 6: " + card6Computer);
System.out.println("");
card7player = rn.nextInt(7) + 1;
System.out.println("Player Card 7: " + card7player);
card7Computer = rn.nextInt(7) + 1;
System.out.println("Computer Card 7: " + card7Computer);
System.out.println("");
int playertotal = card1player + card2player + card3player + card4player + card5player + card6player + card7player;
int computertotal = card1Computer + card2Computer + card3Computer + card4Computer + card5Computer + card6Computer + card7Computer;
if (playertotal > computertotal) {
System.out.print("Player Wins, Players Score is, " + playertotal + " Computers Score is, " + computertotal + " ");
} else if (computertotal > playertotal) {
System.out.print("Computer Wins, Computer Score is, " + computertotal + " Players Score is, " + playertotal + " ");
} else {
System.out.print("Draw Players Score is, " + playertotal + " Computers Score is, " + computertotal + " ");
}
}
}
}
}
You can create an array of cardPlayers and cardComputers. For instance try this below
int numPlayers = 14;
int [] cardPlayer = new int[numPlayers];
int [] cardComputer = new int[numPlayers];
for (int i = 0; i < numPlayers; i++) {
System.out.println("Player Card " + i + ": " + cardPlayer[i]);
cardComputer[i] = rn.nextInt(7) + 1;
System.out.println("Computer Card " + "i" + cardComputer[i]);
System.out.println("");
}
This will make your code more readable and reduce lines in total
Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}
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!