Write methods to test for average grades in java - java

I'm writing code for homework and I got stuck.
The homework is to write a program to get the average of 10 grades that the user inputs.
I got most of it I believe, but in the averageGrades method when I try to declare average it wont let me.
This is what I have:
public class Averagegrades
{
public int min, max;
double average;
public static void main (String [] args)
{
double sum = 0;
Scanner scan = new Scanner(System.in);
int [] gradesarray = new int[10];
System.out.println("Please enter the 10 test grades: ");
for (int i = 0; i < gradesarray.length; i++)
{
gradesarray[i] = scan.nextInt();
if(gradesarray[i] > 100)
{
System.out.println("Please enter a number within 0 - 100: ");
gradesarray[i] = scan.nextInt();
}
}
System.out.println("These are the grades you entered: " +
Arrays.toString(gradesarray));
System.out.println("You have entered " + gradesarray.length + " grades");
for(double num : gradesarray)
{
sum = sum + num;
}
System.out.println("This is the sum " + sum);
}
public double averageGrades()
{
average = sum / (double) gradesarray.length;
}

So this will let you declare avg. The problem is that the method averageGrades could not find sum or gradesarray because those two variables were declared in the main method, and thus not visible to the method.
package test;
import java.util.Arrays;
import java.util.Scanner;
public class Averagegrades
{
public int min, max;
double average;
static double sum;
static int[] gradesarray;
public static void main (String [] args)
{
sum = 0;
Scanner scan = new Scanner(System.in);
gradesarray = new int[10];
System.out.println("Please enter the 10 test grades: ");
for (int i = 0; i < gradesarray.length; i++)
{
gradesarray[i] = scan.nextInt();
if(gradesarray[i] > 100)
{
System.out.println("Please enter a number within 0 - 100: ");
gradesarray[i] = scan.nextInt();
}
}
System.out.println("These are the grades you entered: "+
Arrays.toString(gradesarray));
System.out.println("You have entered "+gradesarray.length+" grades");
for(double num : gradesarray)
{
sum = sum + num;
}
System.out.println("This is the sum "+sum);
}
public double averageGrades()
{
average = sum / (double) gradesarray.length;
return average ;
}
Alternative you could have also done...
public double averageGrades(int sum, int[] gradesarray)
{
average = sum / (double) gradesarray.length;
return average ;
}
and then when calling the method...
averageGrades(sum, gradesarray);
By doing this you wouldnt have to move sum and gradesarray declaration outside of the the main method.
Hope this helps!

The scope of your sum variable is restricted to the main method, however you are utilising the sum variable in the averageGrade method, which lies outside of the main method.
To overcome this, declare the sum variable such that its scope covers the whole class. Declare the sum variable next to the min,max and average variables.
The exact same issue occurs for the integer array object. I suggest you read up on Variable Scope.
For more information on variable scope, check out: http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

Related

Java - print user input of 4 integers, and the lowest, highest and average number

This program is supposed to take user input of four grades, take these grades and calculate the lowest, highest and average of them. Then it needs to print out the four grades along with the lowest, highest, and average of them with proper labels. I cannot figure out how to print out the four grades with my code, and for some reason it prints out the lowest, highest and average after every iteration of the loop, or every user input.
Here is what I have so far:
public class Test2 {
double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;
public void Test2 (double[] grades){
//Loop through all of the grades.
for(int i = 0; i < 4; i++){
double grade = grades[i];
//Add the grade to the total
total += grade;
//If this is the highest grade we've encountered, set as the max.
if(max < grade){
max = grade;
}
//If this is the lowest grade we've encountered, set as min.
if(min > grade){
min = grade;
}
}
System.out.println("Average is: " + (total / 4));
System.out.println("Max is: " + max);
System.out.println("Min is: " + min); }
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] grades = new double[4];
System.out.println("Please enter number");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextDouble();
Test2 g = new Test2();
g.Test2(grades);
} } }
Can anyone help me with this? I need it to print out the four grades (user input), along withe the lowest, highest and average grade from the four grades, but ONLY ONCE, not after every iteration of the loop. Sorry if my code looks bad.
You have to call the method Test2(double grade) only once in the main method as there is a for loop inside Test2 method. I.e call Test2 method in main outside for loop.
Your answer should be the below class.
import java.util.Scanner;
public class Test2 {
double total = 0.0;
double max = 0.0;
double min = Double.MAX_VALUE;
public void doOperations(double[] grades) {
for (int i = 0; i < 4; i++) {
double grade = grades[i];
//Add the grade to the total
total += grade;
//If this is the highest grade we've encountered, set as the max.
if (max < grade) {
max = grade;
}
//If this is the lowest grade we've encountered, set as min.
if (min > grade) {
min = grade;
}
}
System.out.println("Average is: " + (total / 4));
System.out.println("Max is: " + max);
System.out.println("Min is: " + min);
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] grades = new double[4];
System.out.println("Please enter number");
for (int i = 0; i < grades.length; i++) {
grades[i] = input.nextDouble();
}
Test2 test2 = new Test2();
test2.doOperations(grades);
}
}

Calculate Average in arrays

I want to calculate the average numbers using arrays. I want the program asks for the amount of grades and after I want to put the grade numbers.
After I want to get the average output in a double.
This is my code so far:
public class Average {
public static void main(String[] args)
{
//int n = MyConsole.readInt("Enter number of grades: " );
int a = MyConsole.readInt("Enter grade 1: " );
int b = MyConsole.readInt("Enter grade 2: " );
int c = MyConsole.readInt("Enter grade 3: " );
int[] numbers = new int[]{a,b,c};
numbers[0] = a;
numbers[1] = b;
numbers[2] = c;
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Average value of array elements is : " + average);
}
}
Don't know what your class MyConsole is doing, but I guess is a Scanner:
Your code improved will be something like this:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter number of grades: " );
int n = sc.nextInt();
int sum = 0;
for (int i = 0; i < n; i++) {
System.out.print("Enter grade "+ (i + 1) + ": ");
int a = sc.nextInt();
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
}
OUTPUT (2 grades):
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 5
Average value of array elements is : 3.0
OUTPUT (5 grades):
Enter number of grades: 5
Enter grade 1: 10
Enter grade 2: 20
Enter grade 3: 30
Enter grade 4: 10
Enter grade 5: 50
Average value of array elements is : 24.0
NOTE
double average = sum / n;
performs an int division, so you won't have any decimal places! I would propose a fast cast:
double average = sum / (double) n;
With new output:
Enter number of grades: 2
Enter grade 1: 1
Enter grade 2: 4
Average value of array elements is : 2.5
GUESS using your own class:
public static void main(String[] args) {
int sum = 0;
int n = MyConsole.readInt("Enter number of grades: " );
for (int i = 0; i < n; i++) {
int a = MyConsole.readInt("Enter grade "+ (i + 1) + ": ");
sum += a;
}
double average = sum / n;
System.out.println("Average value of array elements is : " + average);
thank you !
Sorry for the poor explanation.
This is my first question
this it the code after edit:
import java.util.Scanner;
public class Average {
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter number of grades: ");
int n = sc.nextInt();
int sum = 0;
int[] numbers = new int[n];
for(int i=0; i < numbers.length ; i++)
{
System.out.println("Enter grade " + (i + 1) + " :");
int a = sc.nextInt();
sum = sum + a;
}
double average = sum / (double) n;
System.out.println("Average value of array elements is : " + average);
sc.close();
}
}
Program to Calculate Average Using Arrays:
public class Inter1 { //name of the class
public static void main(String[] args) {//main method
int number[]={40,56,23,56,87,23,78}; //declaring the int array
int sum=0;
for (int s:number){ //for each
sum +=s;
}
int ave=sum/number.length; //to get the average
System.out.println("the average is "+ave); //out put
}
}
package inter1;
import static java.time.Clock.system;
import java.util.Scanner;
public class Inter1 {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
int total=0;
System.out.println("Enter how many number that do u wanna enter ?? ");
int num= in.nextInt();
int numbers[]=new int[num];
for (int i=0;i<numbers.length;i++){
System.out.println(i+1+":"+"enter the your numbers ? ");
numbers[i]=in.nextInt();
}
for (int i=0;i<numbers.length;i++){
total+=numbers[i];
}
int average =total/numbers.length;
System.out.println("the average is "+average);
}
}
public class Inter1 { //name of the class
public static void main(String[] args) { //main method
System.out.println("==============================");
int num[]={34,56,78,78,34,2,33,99,100,56}; //int array
int total=0;
for (int i=0;i<num.length;i++){ //for loop
total+=num[i];
}
int avrage1=total/num.length; //output
System.out.println("The average is "+avrage1);
}
}

How can I get my user inputted numbers to be read all on one line to be placed into a 2D array?

Basically, I have this program. It is not completed yet but the gist of it is that it is a grade book with user input grades for a number of students they enter. They also enter the number of grades. What I'm struggling with is how to get the program to read the numbers after the first one on the line. The numbers being read is under the name "scores". So I want it to read it as:
1 2 3 4 (it just would read 1 and 5 right now)
5 6 7 8 (I want it to read them all)
Here's my code if it helps:
import java.util.Scanner;
import java.text.DecimalFormat;
public class SeventhAssignment {
public static double scores[][];
public static void main(String[] args) {
DecimalFormat formatter = new DecimalFormat(".00");
Scanner input = new Scanner(System.in);
int students;
System.out.print("Enter number of students");
students = input.nextInt();
if (students <= 0) {
System.out.println("Both numbers must be positive");
System.exit(0);
}
int grades;
System.out.print("Enter number of grades");
grades = input.nextInt();
if (grades <= 0) {
System.out.println("Both numbers must be positive");
System.exit(0);
}
double[][] arr = new double[students][grades];
System.out.println("Enter " + students * grades + " grades: ");
int i;
int j;
for (i = 0; i < students; i++) {
for (j = 0; j < grades; j++) {
Scanner scores = new Scanner(System.in);
arr[i][j] = scores.nextInt();
}
for (i = 0; i < students; i++) {
for (j = 0; j < grades; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
public double getMinimum() {
double lowGrade = scores[0][0];
for (double studentGrades[] : scores) {
for (double grade : studentGrades) {
if (grade < lowGrade)
lowGrade = grade;
}
}
return lowGrade;
}
public double getMaximum() {
double highGrade = scores[0][0];
for (double studentGrades[] : scores) {
for (double grade : studentGrades) {// if grade is greater than
// higherGrade, assign to higher
// grade
if (grade > highGrade)
highGrade = grade;
}
}
return highGrade;// returtn higher grade
}
public static double getAverage(double setofGrades[]) {
double total = 0;// Initializing total
// sum of grade for one student
for (double grade : setofGrades)
total += grade;
// return average of grade
return (double) total / setofGrades.length;
}
public void outputGrades() {
System.out.println("The grades are:\n");
System.out.println(" ");// for alignment
for (double test = 0; test < scores[0].length; test++)
System.out.printf("Test %d", test + 1);
System.out.println("Average"); // student average column heading
for (double student = 0; student < scores.length; student++) {
System.out.printf("student %2d", student + 1);
for (double test : scores[(int) student])// output student grades
System.out.printf("%8d", test);
// call method getAverage to calculate students average grade
// pass row of grades as the argument to getAveerage
double average = getAverage(scores[(int) student]);
System.out.printf("%9.2f\n", average);
}
}
}
Thanks ahead for any help you guys can bring!

How to use Java to calculate average from input?

I need a program that should add x numbers. The numbers should come from user input so I need some sort of loop. I have gotten as far as shown below, but I'm stuck since I have no idea how to add a new number without deleting the previous?
System.out.println("How many numbers to use?");
int number = keyboard.nextInt();
for (int i = 0; i<number ; i++) {
System.out.println("whats the number");
double first = keyboard.nextDouble();
}
If all you need is the average, you don't need to keep all the numbers you get from user input. Just keep one variable that holds their sum.
define the sum variable outside the loop (initialized to 0), and add to it each number you get from user input.
int number = keyboard.nextInt();
double sum = 0;
for (int i = 0; i<number ; i++)
{
System.out.println("whats the number");
sum += keyboard.nextDouble();
}
double average = sum / number;
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
double sum = 0;
int num;
System.out.println("enter how many num");
num = sc.nextInt();
System.out.println("please enter " + num + " numbers");
for (int i = 0; i < num; i++) {
sum += sc.nextDouble();
}
double avg = sum / num;
System.out.println("Average of " + num + " numbers is:" + avg);
}
}

Trying to add sum of all even integers between 2 and the input, and I just get the input back

I'm attempting to write something for an assignment that takes the sum of all the even integers between 2 and the number entered by the user and prints it. If it is below 2 it should return an error. I'm getting an error for anything under 2, however, when I go have it return the sum it just returns the input.
I think I may have messed a variable up in this loop, but I can't see where I went wrong.
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number larger than 2");
int num = input.nextInt();
if (num >= 2) {
int sum = 0;
for (int i = 2; i <= num; i +=2) {
sum += i;
}
System.out.println("The sum of all even numbers between 2 and the input is " + num);
} else {
System.out.println("Invalid, please enter a number above 2");
}
}
}
System.out.println("The sum of all even numbers between 2 and the input is " + num);
should be
System.out.println("The sum of all even numbers between 2 and the input is " + sum);
There is a formula to compute the answer without a loop, by the way. But perhaps that is not the point of the exercise?
It's because you return num instead of sum
Declare sum outside if statement, and print sum instead of num
package com.test;
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number larger than 2");
int num = input.nextInt();
int sum = 0;
if (num >= 2) {
for (int i = 2; i <= num; i += 2) {
sum += i;
}
System.out
.println("The sum of all even numbers between 2 and the input is "
+ sum);
} else {
System.out.println("Invalid, please enter a number above 2");
}
}
}

Categories