Difficulty Adding Values and Array Lengths [duplicate] - java

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
I'm trying to write some code to calculate an on base percentage. The program gathers the players name, year he has played on the team (size of array) and the year he started. Once I begin the array and start the information, if the user entered two years, I receive an error right at the second value because of the arrays length. How do I get around this issue? Any help is appreciated. Thank you.
This is the error I receive: "java.lang.ArrayIndexOutOfBoundsException: 2"
I've tried creating variables for each item, adding and dividing to get the on base percentage. Once I do that, I can't seem to figure out how to print that out for each year. For example "Year 1985: -OBP-, Year 1986: -OBP-"
import java.util.Scanner;
public class RyanBaseballOBPArray
{
public static void main(String[] args)
{
int numYears;
double [] years;
String name;
int startYear;
double oBP;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter name of baseball player: ");
name = keyboard.nextLine();
System.out.print("Enter the number of years " + name +" has been playing: ");
numYears = keyboard.nextInt();
years = new double[numYears];
System.out.print("Enter " +name +" first year on the team: ");
startYear = keyboard.nextInt();
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[1] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[2] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[3] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[4] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[5] = keyboard.nextInt();
years[0] = (years[1] + years[2] + years[3]) / years[4] + years[2] + years[3] + years[5];
}
printOnBasePercentage(name, startYear, years);
}
public static void printOnBasePercentage(String name, int startYear, double []years){
System.out.println(name + "'s On Base Percentage");
System.out.println(years[0]);
}
}

I believe your issue stems from the fact you have hard-coded array access to the years array whose length is defined by keyboard input.
years[5] = keyboard.nextInt();
Thus if someone only plays for 3 years there are only 3 elements in the year array, and you are trying to access the 6th giving you an out of bounds exception.

Related

How to calculate input from an array

I'm having trouble with this array I'm working on. In the for loop, I need to somehow calculate an on base percentage. The element at index 0 will store the OBP. How can I retain the information the user inputs to calculate the OBP? Thank you.
for (int index = 0; index < years.length; index++)
{
System.out.print("For Year " + (index +1 ) + "\nEnter number of hits: ");
years[index] = keyboard.nextInt();
System.out.print("For Year " + (index +1) + "\nEnter number of walks: ");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of times player"
+ "has been hit by a pitch:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of at bats:");
years[index] = keyboard.nextInt();
System.out.print("For Year" + (index +1) + "\nEnter the number of sacrafice flies"
+ "that year: ");
years[index] = keyboard.nextInt();
}
I'd suggest a HashMap inside a HashMap for this use case.
Before loop:
HashMap<Integer, HashMap<String, Integer>> years = new HashMap<>();
HashMap<String, Integer> entry = new HashMap<>();
For every input from user's keyboard (example):
entry.put("hits", 5);
years.put(2019, entry);
entry.put("walks", 10);
years.put(2019, entry);
In the end you get a result such as:
{2019={hits=5, walks=10}}
Retrieving results is simple too:
// retrieve map of data for a specific year:
years.get(2019)
result: {hits=5, walks=10}
// retrieve specific data for a specific year:
years.get(2019).get("hits")
result: 5
You will want to store the values entered by the user in a variable. Instead of having an array of inputs (which is one way of doing it) - you can simply store each value in a separate variable and then do the calculation at the end.
See my sample code below:
public static void main(String args[]) {
// let's take incoming values from the user for our calculations
Scanner keyboard = new Scanner(System.in);
// we'll use this array to store the values entered by the user
// in position zero of the array we'll store the OBP
// in positions 1-5 we'll store the inputs as entered by the uesr
float[] values = new float[6];
// we'll use this flag to determin if we should ask the user input again or quit the program
boolean letsDoThisAgain = true;
while (letsDoThisAgain){
System.out.println("Enter a Year: ");
int year = keyboard.nextInt();
System.out.println("For Year " + year + ", enter number of:");
System.out.println("Hits: ");
values[1] = keyboard.nextFloat();
System.out.println("Walks: ");
values[2] = keyboard.nextFloat();
System.out.println("Number of times player has been hit by a pitch: ");
values[3] = keyboard.nextFloat();
System.out.println("Number of at bats: " );
values[4] = keyboard.nextFloat();
System.out.println("Number of sacrifice flies: ");
values[5] = keyboard.nextFloat();
// calculate the OBP
values[0] = (values[1] + values[2] + values[3] - values[5] ) / values[4]; // or however you calculate it
System.out.println("OBP: " + values[0]);
System.out.println("------");
System.out.println("Do you want to do it again? (y/n): ");
String quitOrDoItAgain = keyboard.next();
if( "n".equalsIgnoreCase(quitOrDoItAgain)){
letsDoThisAgain = false;
}
}
System.out.println("Thanks for playing... Good Bye!");
}
By the usage of a proper data structure like Map<string year, object playerstats> including OBP calculation on the object player stats before storing but this is an in-memory solution only last till the program is running if you like persistent then look on the database side
Also from the way you have presented your code it seems you are over-writing the value at year[index] always.
if you just want to use an array, then go like
years[index] = year[index] (math operation) keyboard.nextInt()

How do I make my nextLine() wait for the user's input? [duplicate]

This question already has answers here:
Scanner is skipping nextLine() after using next() or nextFoo()?
(24 answers)
Closed 5 years ago.
for (int i = 1; i <= value; i++) {
System.out.print("Player " + i + ", Please Enter your name : ");
String PlayerName = input.nextLine();
System.out.print("Please enter a number between 0 and 9 : ");
int PlayerNumber = input.nextInt();
System.out.println(PlayerName + " : " + PlayerNumber);
}
Output : Player 1, Please Enter your name : Please enter a number between 0 and 9 :
If I change input.nextLine to input.next , it will wait for the users first input but he/she won't be able to write their full name.
My question : What can I change so the user can input his full name first and then his number?
Consume the newLine after input.nextInt()
for (int i = 1; i <= value; i++) {
input.nextLine(); //add this to top
System.out.print("Player " + i + ", Please Enter your name : ");
String PlayerName = input.nextLine();
System.out.print("Please enter a number between 0 and 9 : ");
int PlayerNumber = input.nextInt();
System.out.println(PlayerName + " : " + PlayerNumber);
}

How to show the number as astrisk [duplicate]

This question already has answers here:
Displaying asterisk depending on the number entered [closed]
(3 answers)
Closed 8 years ago.
So I have to show the number of total grades(which i have calculated already) as astrisk. the output should be like this,
A=******
B=******
C=******
D=*****
And this is my code:
import java.io.*;
import java.util.*;
public class grades
{
public static final void main(String args[]) throws FileNotFoundException
{
System.out.println("name");
Scanner myScanner = new Scanner(new File("students.txt"));//Creating new scanner object
int lineNumber =1;//Line Number for each student.
while (myScanner.hasNext())
{
String firstName = myScanner.next();//Scanning student first name and storing in the string
String lastName = myScanner.next();// Scanning student last name and storing in the string
String athleteFlag=myScanner.next();//Scanning for verification of athlete and storing in the string
String athlete= "Y";
String notAthlete = "N";
//if else statement to declare if student is a athlete
if (athleteFlag.equals(athlete))
{
athleteFlag="YES";
}
else if(athleteFlag.equals(notAthlete))
{
athleteFlag="NO";
}
int quiz1=myScanner.nextInt();// Grades on Quiz 1
int quiz2=myScanner.nextInt();// Grades on Quiz 2
int quiz3=myScanner.nextInt();// Grades on Quiz 3
int quiz4=myScanner.nextInt();// Grades on Quiz 4
int quiz5=myScanner.nextInt();// Grades on Quiz 5
int test1=myScanner.nextInt();// Grades on Test 1
int test2=myScanner.nextInt();// Grades on Test 2
//student quiz average
double quizAverage = (double)(quiz1+quiz2+quiz3+quiz4+quiz5)/5;
//Overall Numerical Grade
float overallNumericalGrade =(float)(quizAverage+test1+test2)/3;
//Students letter Grade, eligibility and counting number of each grade
String grade;
String eligibility;
int gradeA=0;
int gradeB=0;
int gradeC=0;
int gradeD=0;
int gradeF=0;
if(overallNumericalGrade>=90.0)
{
grade="A";
eligibility ="YES";
gradeA++;
}
else if(overallNumericalGrade>=80.0)
{
grade = "B";
eligibility ="YES";
gradeB++;
}
else if(overallNumericalGrade>=70.0)
{
grade = "C";
eligibility ="YES";
gradeC++;
}
else if(overallNumericalGrade>=60.0)
{
grade = "D";
eligibility ="NO";
gradeD++;
}
else
{
grade = "F";
eligibility ="NO";
gradeF++;
}
System.out.println(lineNumber + " "+lastName+","+firstName+"/ "+athleteFlag+ "/ " + eligibility +
" / " +"Grades on all quiz "+ quiz1+ " "+quiz2+" "+quiz3+" "+ quiz4+" "+quiz5+" "+test1+" "+
test2+ " /" +"quiz average is " + quizAverage +"\n " + "Overall Numerical grade is " +
overallNumericalGrade+" / "+ "Student letter Grade is " + grade);
lineNumber++;
}
}
}
I just dont know how to output this. Any help will be appriciated. Thanks in advance.
Assuming the total of all grade is overallNumericalGrade and that you want to display it as * in the last output (as this is the only output in your code), You could do
System.out.println(lineNumber + " "+lastName+","+firstName+"/ "+athleteFlag+ "/ " + eligibility +
" / " +"Grades on all quiz "+ quiz1+ " "+quiz2+" "+quiz3+" "+ quiz4+" "+quiz5+" "+test1+" "+
test2+ " /" +"quiz average is " + quizAverage +"\n " + "Overall Numerical grade is " +
String.valueOf(overallNumericalGrade).replaceAll(".", "*")+" / "+ "Student letter Grade is " + grade);
The important part is here
String.valueOf(overallNumericalGrade).replaceAll(".", "*")
Where I convert the total value to a String then replace everything with *.
If the total is not overallNumericalGrade then simply use the replacement on whatever is the value.
Edit : To answer to your comment, here more explanation.
String.replaceAll is a method that replace everything corresponding to the given Regular expression(regex) given by what we give as second parameter ( in that case *). The regex I gave is simply a . which means any character except linebreak. So, String.valueOf(overallNumericalGrade) convert it to a String so I can call the replaceAll method, then replace everything with *.
As for an answer to your second question, once again you could use the replacement to replace each linebreak of grade by a simple space so that it display all on the same line. Something like
grade.replaceAll(System.getProperty("line.separator"), " ");
Notice that I used System.getProperty("line.separator") instead of giving in the char so that it work on any system.

Listing multiples of user-inputted numbers

The task is to "Write a program that displays a user-indicated number of multiples for an integer entered by the user."
I suppose I do not need a completely direct answer (although I do want to know the methods/formula to use), as I want to use this as a learning experience in order to do and learn from the task myself. I really want to know about the process and which methods to use, along with finding a formula. :||
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
So far, I have:
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
\\just stuff to base my code off of
int integer;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
\\pretty much everything from here on out.. I'm not sure what to really do.
int n = integer;
int result = (integer * (numberMultiples));
while (result > 0){}
System.out.print(result);
}
} \\at the moment this code doesn't seem to have any running errors
I'm really not sure how to write a code that displays a user-inputted number of a user-inputted integer. The hardest part seems to be writing the loop formula. Not sure where to start.
NEW QUESTION
I need to loop my program as well. (By asking a question to the user first.) Mines isn't working, as it just keeps looping only the integer loop and doesn't let me type yes/no.
import java.util.Scanner;
public class MultipleLoops
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
int integer, numberMultiples;
String repeat = "yes";
while (repeat != "no")
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++){
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
}
}
}
Ok so you need to understand the problem first to know how to solve it
x = First input
n = Second input
you need to calculate n multiple of x
example with x = 3 and n = 10
To calculate 10 multiple of 3 we need to do :
1st multiple = x*1
2nd multiple = x*2
3rd multiple = x*3
...
n multiple = x*n
you can notice that these operations can be replaced by one for loop (notice first and last character of every line, it can be index of your loop )
Back to java :)
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
Replace your code with the following and try this code :
import java.util.Scanner;
public class MultipleLooping{
public static void main(String[] args){
Scanner keyboard = new Scanner(System.in);
int integer,numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
for (int i=1; i<=numberMultiples; i++){
System.out.println("Listing multiple N# " + i + " = "+ i*integer );
}
}
}
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing multiple N# 1 = 3
Listing multiple N# 2 = 6
Listing multiple N# 3 = 9
Listing multiple N# 4 = 12
Listing multiple N# 5 = 15
Listing multiple N# 6 = 18
Listing multiple N# 7 = 21
Do you want like this ? Below is the code
package com.ge.cbm;
import java.util.Scanner;
public class MultipleLooping
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
//just stuff to base my code off of
int integer;
int firstEntered;
int numberMultiples;
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
firstEntered = integer;
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
//pretty much everything from here on out.. I'm not sure what to really do.
for (int i=0;i<numberMultiples;i++){
integer=integer*firstEntered;
System.out.println(integer);
}
}
}
Output:
Enter an integer:
3
How many multiples of 3 would you like to know?
7
Listing the first 7 multiples of 3:
9
27
81
243
729
2187
6561
this should work
while(repeat.equals("yes"))
{
System.out.println("Enter an integer: ");
integer = keyboard.nextInt();
System.out.println("How many multiples of " + integer + " would you like to know?");
numberMultiples = keyboard.nextInt();
System.out.println("Listing the first " + numberMultiples + " multiples of " + integer + ": ");
for (int i=1; i<=numberMultiples; i++)
{
System.out.println(integer + " * " + i + " = " + i*integer );
}
System.out.println("Would you like to do this again? Enter yes or no: ");
repeat = keyboard.nextLine();
repeat = keyboard.nextLine();
}

Need help declaring a variable within a for loop (Java)

I'm currently working on a program and ran into an error while trying to execute a for loop. I want to declare a variable in the for loop, then break once that variable obtains a certain value, but it returns the error "cannot be resolved to a variable."
Here's my code
int i = -1;
for (; i == -1; i = index)
{
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
int index = (input.indexOf('y'));
}
I want to run the output segement of my program until the user inputs yes, then the loop breaks.
The variable index's scope is local to the block of the for loop, but not the for loop itself, so you can't say i = index in your for loop.
You don't need index anyway. Do this:
for (; i == -1;)
or even
while (i == -1)
and at the end...
i = (input.indexOf('y'));
}
Incidentally, I'm not sure you want input.indexOf('y'); an input of "blatherskyte" will trigger this logic, not just "yes", because there's a y in the input.
Instead of using a for loop, you can do-while(it suits much better for this scenario.
boolean exitLoop= true;
do
{
//your code here
exitLoop= input.equalsIgnoreCase("y");
} while(exitLoop);
for indefinite loop, i would prefer while.
boolean isYes = false;
while (!isYes){
Scanner scan = new Scanner(System.in);
System.out.println("Please enter your first and last name");
String name = scan.nextLine();
System.out.println("Please enter the cost of your car,"
+ "\nthe down payment, annual interest rate,"
+ "\nand the number of years the car is being"
+ "\nfinanced, in that order.");
DecimalFormat usd = new DecimalFormat("'$'0.00");
double cost = scan.nextDouble();
double rate = scan.nextDouble();
int years = scan.nextInt();
System.out.println(name + ","
+ "\nyour car costs " + usd.format(cost) + ","
+ "\nwith an interest rate of " + usd.format(rate) + ","
+ "\nand will be financed annually for " + years + " years."
+ "\nIs this correct?");
String input = scan.nextLine();
isYes = input.equalsIgnoreCase("yes");
}
You cannot do this. If the variable is declared inside of the loop, then it is re-created every run. In order to be part of the condition for exiting the loop, it must be declared outside of it.
Alternatively, you could use the break keyworkd to end the loop:
// Should we exit?
if(input.indexOf('y') != -1)
break;
Here you want to use a while loop. Usually you can decide which loop to use by saying your logic out loud to yourself, While this variable is(not) (value) do this.
For your problem, initialize the variable outside of the loop, and then set the value inside.
String userInput = null;
while(!userInput.equals("exit"){
System.out.println("Type exit to quit");
userInput = scan.nextLine();
}

Categories