Got this assignment with the purpose to withdraw a minimum, maximum, and average score from various inputs. Right now I'm focused on the aspect of taking scanner data and putting it into the array, because I think I know how to make the flags and get an average.
public class BattingAverage
{
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
// named constant for array size here
int arraySize = 8
//array
double[] avg;
// Use this integer variable as your loop index. (Given in the assignment)
int loopIndex;
// Use this variable to store the batting average input by user. (Also Given)
double battingAverage = 0;
// String version of batting average input by user. (Given)
String averageString;
// Use these variables to store the minimum and maximum batting averages. (Given)
double min, max;
// Use these variables to store the total and the average. (Given)
double total, average;
// I wrote these statements to get user input and then store it in the "avg" array
System.out.println("Enter a batting average: ");
averageString = s.nextLine();
battingAverage = Double.parseDouble(averageString);
for (double x = 0; x<8; x ) {
battingAverage = Scanner.nextDouble();
avg[0] = battingAverage;
avg[1] = battingAverage;
avg[2] = battingAverage;
avg[3] = battingAverage;
avg[4] = battingAverage;
avg[5] = battingAverage;
avg[6] = battingAverage;
avg[7] = battingAverage;
}
My comprehension of the code is that the print and scanner prompt the inputs, the strings are converted into doubles, then the for loop indexes the user inputs. I think that I need to put if/else statements around each "avg[x] = battingAverage" statement so that it doesn't try to save the first input at each index, but I'm also getting the error message "non-static method nextDouble() cannot be referenced from a static context" in this line
"battingAverage = Scanner.nextDouble();"
CodePudding user response:
On this line:
battingAverage = Scanner.nextDouble();
When you refer to Scanner
, you are referring to the class Scanner and all of the static methods on it. nextDouble()
is a member level method of Scanner similar to nextLine()
; it can only be called on an instance of class Scanner. If you change it to s.nextDouble()
that compilation error should go away.
CodePudding user response:
When you refer to the indexes of an array, the value used as the index doesn't have to be a constant.
So you can, for example, say:
int x = 1;
avg[x] = someNumber;
Does that give you any ideas for simplifying the code inside your for loop?