Calculate Average in arrays - java

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);
}
}

Related

Adding 2 integers in 1 User input

I want to make the user input 2 integers in 1 input like this
Enter two integers: 2 2 // sum = 4
Here is my sample code:
Scanner s = new Scanner(System.in);
int x, num1, num2, sum;
System.out.print("*Enter 2 integer: ");
x = s.nextInt();
int sum = num1 + num2;
System.out.println(" Sum = "+ sum);
Is it possible to add 2 integers without using variables num1 and num2?
I want the output to be like this.
Enter two integers: 2 2
sum = 4
Add any number of integers:
Scanner s = new Scanner(System.in);
System.out.print("Enter some integers: ");
int sum = 0;
while (s.hasNextInt()) {
sum += s.nextInt();
}
System.out.println(" Sum = " + sum);
Case 1:
If you have only 2 values then follow the below code
import java.util.*;
class Add {
public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("*Enter 2 integer: ");
for(int i = 0; i < 2; i++)
sum += scan.nextInt();
System.out.println(" Sum = "+ sum);
}
}
Case 2:
If you have some More than 2 numbers but you have an idea about how many numbers to sum then follow the below code.
import java.util.*;
class Add {
public static void main(String[] args) {
int sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("*Enter how many integers to sum: ");
int iterate = scan.nextInt();
System.out.print("*Enter " + iterate + " integer: ");
while(iterate-- > 0)
sum += scan.nextInt();
System.out.println(" Sum = "+ sum);
}
}

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);
}
}

Write methods to test for average grades in 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

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 sum powers of 2 with while loop

I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}

Categories