Java 2 dimensional arrays and average - java

Can someone please help me with this homework?
I have tried something but I'm not sure if my solution covers all the tasks.
I have to write a Java program, which initializes a two-dimensional array with the marks from the 5th semester (there are only 5 marks, as you know) of n students (the user should input the number of students).
The program should outputs as a result:
The average grade of all students for 5th semester;
The number of the student with the highest average grade;
The number of the student with the lowest average grade;
The number of students with an average grade greater than the average grade of all students;
The number of students with an average grade less than the average grade of all students;
The program should do data validation as follows: student’s marks should be between 2 and 6, and the number of students should not exceed 30.
and here is my solution so far :
package ocenki;
public static void main(String[] args) {
Scanner scan = new Scanner (System.in ) ;
System.out.println ("Enter notes here:") ;
double [] marks= new double [5] ;
for ( int i=0; i<=4; i++)
{
System.out.println ("Please, input mark for " + i +(" subject")) ;
marks[i] = scan. nextDouble () ;
while (marks[i]<2 || marks[i]>6)
{
System.out.println ("Please, input marks between 2 and 6:") ;
marks[i] = scan.nextDouble () ;
}
}
double sum=0;
double min=marks[0];
double max=marks[0];
for ( int i=0; i<=4; i++)
{
sum = sum+marks[i] ;
if(marks[i]>max)
{
max=marks[i];
}
if(marks[i]<min)
{
min=marks[i];
}
}
System.out.println("The average is " + sum/5 + ", the minimum is " + min + " and the maximum is " + max);
}

Please find the solution for your Q-4 AND Q-5
Solution
double avg= sum/5;
for ( int i=0; i<=4; i++)
{
if(marks[i]>avg)
{
moreAvg++;
}
if(marks[i]<avg)
{
lessAvg++;
}
}
FULL CODE -
public static void main(String[] args) {
Scanner scan = new Scanner (System.in ) ;
System.out.println ("Enter notes here:") ;
double [] marks= new double [5] ;
for ( int i=0; i<=4; i++)
{
System.out.println ("Please, input mark for " + (i+1) +(" subject")) ;
marks[i] = scan. nextDouble () ;
while (marks[i]<2 || marks[i]>6)
{
System.out.println ("Please, input marks between 2 and 6:") ;
marks[i] = scan.nextDouble () ;
}
}
double sum=0;
double min=marks[0];
double max=marks[0];
int lessAvg=1,moreAvg=0;
for ( int i=0; i<=4; i++)
{
sum = sum+marks[i] ;
if(marks[i]>max)
{
max=marks[i];
}
if(marks[i]<min)
{
min=marks[i];
}
}
double avg= sum/5;
for ( int i=0; i<=4; i++)
{
if(marks[i]>avg)
{
moreAvg++;
}
if(marks[i]<avg)
{
lessAvg++;
}
}
System.out.println("The average is " +avg + ", the minimum is " + min + " and the maximum is " + max);
System.out.println("4.The number of students with an average grade greater than the average grade of all students"+moreAvg);
System.out.println("5.The number of students with an average grade less than the average grade of all students"+lessAvg);
}

Related

I cant get my nested loop to average student scores correctly after first loop

This is my Java programming class assignment: Write a program, that takes users’ input and the number of students, and test scores. It should then average test scores and display them on the screen. (Wants us to do this using a nested loop).
The issue that I am having is when the program goes into the second loop the sum is still totaling the scores from the previous loop. so it is throwing off any student average calculated after the first one.
'Import java.util.Scanner;'
class Main { public static void main(String[] args) {
int ans, ans1;
double sum = 0;
Scanner sc = new Scanner(System.in);
System.out.print("\n\nFor how many students do you have scores ? ");
ans = sc.nextInt(); //Number of Students
for (int x=1; x<=ans; x++) {
System.out.print("\n\nHow many test scores does student #" + x+" have? ");
ans1 = sc.nextInt(); //Number of scores entered
for (int z=1; z<=ans1; z++) {
double ans2;
System.out.print("\nEnter score "+z+" for student " +x+": ");
ans2 = sc.nextDouble();
sum += ans2 + 0; //Student Scores
}
double avg = sum/ans1;
System.out.printf("\nStudent #"+x+" Average Score: %.1f", avg);
}
}
}
Output:
For how many students do you have scores ? 2
How many test scores does student #1 have? 3
Enter score 1 for student 1: 84
Enter score 2 for student 1: 79
Enter score 3 for student 1: 97
Student #1 Average Score: 86.7
How many test scores does student #2 have? 3
Enter score 1 for student 2: 92
Enter score 2 for student 2: 88
Enter score 3 for student 2: 94
Student #2 Average Score: 178.0 //Average should be 91.3
You should reset the sum variable inside the loop.
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int ans, ans1;
double sum = 0;
Scanner key = new Scanner(System.in);
System.out.println("\nHow many students have scores?: ");
ans = key.nextInt();
for(int i = 0; i < ans; i++){
System.out.print("\nHow many test scores does Student "+ (i+1) + " have?: ");
ans1 = key.nextInt();
for(int j = 0; j < ans1; j++){
double ans2;
System.out.print("\nEnter score " + (j + 1) + " for Student " + (i + 1) +": ");
ans2 = key.nextDouble();
sum += ans2;
}
double avg = sum/ans1;
System.out.printf("\nStudent " + (i + 1) + " Average score: %.1f", avg);
sum = 0; //add this line
}
}
}
The "sum" variable should be inside the ans loop as it must be reset for each student. :)

How to insert existing arrays inside a 3D array

I would like to create a 3d array with the already existing arrays(Score, CourseRating, and SlopeRating). I would like to do so, so that I can match the Scores with their Ratings. If it is not possible, I was thinking I could maybe find the index of the score, and match it with the Course and Slope rating so that I can calculate the Handicap Index.
import java.util.Arrays;
import java.util.Scanner;
public class RoughDraft {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int count;
int[] Scores;
double[] SlopeRating;
double[] CourseRating;
System.out.print("\nHow many scores would you like to enter?: ");
count = scnr.nextInt();
// ------ adds Scores, Course Rating and Slope Rating to Arrays ------ //
Scores = new int[count];
CourseRating = new double[count];
SlopeRating = new double[count];
if(count >= 5 && count <= 20) {
for(int i = 0; i < count; i++) {
System.out.printf("\nEnter Score #%d: ", i + 1);
if(scnr.hasNextInt()) {
Scores[i] = scnr.nextInt();
}
System.out.printf("Enter Course Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
CourseRating[i] = scnr.nextDouble();
}
System.out.printf("Enter Slope Rating #%d: ", i + 1);
if(scnr.hasNextDouble()) {
SlopeRating[i] = scnr.nextDouble();
}
}
}
else {
System.out.print("Enter a minimum of 5 scores and a maximum of 20 scores.");
main(args);
}
System.out.print("\nScores: " + Arrays.toString(Scores));
System.out.print("\nCourse Ratings: " + Arrays.toString(CourseRating));
System.out.print("\nSlope Rating: " + Arrays.toString(SlopeRating));
}
}

How do I show the numbers I entered in Java

I'm writing a program where at the end I have to display the numbers I entered and the maximum and minimum of those entered numbers. However I'm running into a little problem, here is my code,
import java.util.*;
public class question3controlstructures {
public static void main (String [] args) {
Scanner in = new Scanner (System.in);
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
numbersinput ++;
System.out.println("do you want to enter another number?");
answer = in.next();
sum = sum + numberEntered;
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
}
}
The above comment are absolutely useful. However, here is little code
package com.mars;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Question3controlstructures {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.print("Enter integers please ");
System.out.println("(EOF or non-integer to terminate): ");
while (scan.hasNextInt()) {
list.add(scan.nextInt());
}
Integer[] nums = list.toArray(new Integer[0]);
int sum = 0;
int i = 0;
for ( ; i < nums.length; i++) {
sum = sum + nums[i];
}
System.out.println("sum..." + sum);
System.out.println("The average is: " + sum / i);
System.out.println(i);
System.out.println("max.. "+Collections.max(list));
System.out.println("min.. "+Collections.min(list));
scan.close();
}
}
As suggent in comments , you need a list to store the multiple numbered entered.
just compare the min and max every time you enter a number
int min = Integer.MAX_VALUE
int max = Integer.MIN_VALUE
int numberEntered;
int numbersinput = 0;
String answer ="";
double sum = 0;
do {
System.out.println("Enter a number");
numberEntered = in.nextInt();
System.out.println("YOU HAVE ENTERED: " + numbersEntered);
if (min > numberEntered) min = numberEntered;
if (max < numberEntered) max = numberEntered;
numbersinput ++;
sum = sum + numberEntered;
System.out.println("do you want to enter another number?");
answer = in.next();
} while (answer.equals("yes"));
System.out.println("The sum is: " + sum);
System.out.println("The average is: " + sum/numbersinput);
System.out.println(numberEntered);
//you can print your min max here.
The IntSummaryStatistics class together with Java 8's Stream API may be less verbose than dealing with min, max, sum and avg calculation manually.
public static void main(String[] args) {
// Get user input.
List<Integer> numbers = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextInt()) {
// No user friendly way to gather user input, improve!
numbers.add(scanner.nextInt());
}
// Transform input to statistics.
IntSummaryStatistics stats = numbers.stream()
.collect(Collectors.summarizingInt(Integer.intValue()));
// Print statistics.
String jointNumbers = numbers.stream()
.collect(Collectors.joining(", "));
System.out.printf("You entered %d numbers: %s\n, stats.getCount(), jointNumbers);
System.out.println("Min: " + stats.getMin());
System.out.println("Max: " + stats.getMax());
System.out.println("Sum: " + stats.getMax());
System.out.println("Avg: " + stats.getAverage());
}

How to use Scanner get store input in one integer

How can I make it so the there will be the same number of questions as the user inputs the number of jobs. For example, lets say you had worked in 5 jobs, I want the program to ask the user to ask,
Your salary for job 1
Job 2
Job 3
Job 4
Job 5, and so on. My code right now is.
import java.util.Scanner;
public class Personal_Info {
public static void main(String[] args) {
Scanner Scanner = new Scanner(System.in);
int Salary1;
int Salary2;
int Salary3;
int TotalJobs;
int Average;
String Name;
int Largest;
int Smallest;
int Sum;
System.out.print("What is your first name?: ");
Name = Scanner.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = Scanner.nextInt();
System.out.print("Enter income from job #1: ");
Salary1 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary2 = Scanner.nextInt();
System.out.print("Enter income from job #3: ");
Salary3 = Scanner.nextInt();
Sum = Salary1 + Salary2 + Salary3;
Average = Sum / TotalJobs;
Largest = Salary1;
Smallest = Salary1;
if(Salary2 > Largest)
Largest = Salary2;
if(Salary3 > Largest)
Largest = Salary3;
if(Salary2 < Smallest)
Smallest = Salary2;
if (Salary3 < Smallest)
Smallest = Salary3;
System.out.println("Hello " + Name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + Largest + ". The lowest paying job paid is "+ Smallest + ". The average is " + Average + ".");
but it wouldn't work cause it'll only ask the user three times, job 1, 2, and 3.
If I try,
for (int x = 0; x<TotalJobs; x++){
System.out.print("How many jobs have you had?: ");
number = Scanner.nextInt();
I don't know how to get the highest/smallest/average from that stored value which would be 'number'.
Hope this will help You
class SalaryCalculate{
public static void main(String args[]){
int totalJobs,jobcounter,maxSalary,minSalary,averageSalary=0;;
int[] jobsincome;
String name;
Scanner sc= new Scanner(System.in);
System.out.println("Enter your name");
name=sc.nextLine();
System.out.println("How many jobs you had");
totalJobs= sc.nextInt();
jobsincome= new int[totalJobs];
for(int i=0;i<totalJobs;i++){
jobcounter=i+1;
System.out.println("Enter the income for your job "+jobcounter);
jobsincome[i]=sc.nextInt();
averageSalary=averageSalary+jobsincome[i];
}
jobsincome=average(jobsincome);
maxSalary=jobsincome[totalJobs-1];
minSalary=jobsincome[0];
averageSalary=averageSalary/totalJobs;
System.out.println("Hi "+name+" your min salary is "+minSalary+" max salary is "+maxSalary+" average salary is "+averageSalary);
}
public static int[] average(int jobsincome[]){
int length=jobsincome.length;
for(int i=0;i<length;i++){
for(int j=i+1;j<length;j++){
if(jobsincome[i]>jobsincome[j]){
int temp=jobsincome[j];
jobsincome[j]=jobsincome[i];
jobsincome[i]=temp;
}
}
}
return jobsincome;
}
}
Use an array.
Also only capitalize classes, not variables
System.out.print("How many jobs have you had?: ");
int totalJobs = scanner.nextInt();
int[] salaries = new int[totalJobs];
// Loop here
// System.out.print("Enter income from job #"+x);
// salaries[x] = scanner.nextInt();
With this list, you can get the length directly and use separate loops for the sum, min, max. Or streams
With the sum and length, find an average
use an integer arraylist to keep salaries and loop through inputs
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
ArrayList<Integer> sallaries = new ArrayList<>();
int TotalJobs;
double average;
String name;
int largest;
int smallest;
System.out.print("What is your first name?: ");
name = input.nextLine();
System.out.print("How many jobs have you had?: ");
TotalJobs = input.nextInt();
for (int i= 0; i<TotalJobs ; i++){
System.out.print("Enter income from job #"+(i+1)+" : ");
sallaries.add(input.nextInt());
}
average = sallaries.stream().mapToInt(Integer::intValue).average().orElse(-1);
largest = Collections.max(sallaries);
smallest = Collections.min(sallaries);
System.out.println("Hello " + name + "You've had " + TotalJobs + " jobs. " + "The highest paying job paid is " + largest + ". The lowest paying job paid is "+ smallest + ". The average is " + average + ".");
}

Methods unindentified error in java

I wrote a small program consisting of two classes. I am trying to call the methods from the second class but I get an error.
The error is:
Exception in thread "main" java.lang.Error: Unresolved compilation
problems: The method getSum(int[]) is undefined for the type
UserInteraction The method getAverage(int[]) is undefined for the type
UserInteraction at UserInteraction.main(UserInteraction.java:66)
Here's the code of the first class:
import java.util.Scanner;
public class UserInteraction {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int choice = 0;
String[] subjects = new String[10];
int grades[] = new int[10];
double sum = 0.0;
Grades method = new Grades();
do
{
System.out.println("1. Enter a course name and a grade");
System.out.println("2. Display all grades");
System.out.println("3. Calculate the average grade");
System.out.println("4. Exit program");
choice = scan.nextInt();
if ( choice == 1 )
{
Scanner scansubjects = new Scanner(System.in);
Scanner scangrades = new Scanner(System.in);
System.out.println("Enter 10 subjects and their corresponding grades:");
System.out.println();
int i = 0;
for( i = 0; i < 10; i++ )
{
System.out.println("Subject:");
String temp = scansubjects.nextLine();
subjects[i] = temp.toLowerCase();
System.out.println("Grade:");
grades[i] = scangrades.nextInt();
if( i == ( subjects.length - 1 ) )
{
System.out.println("Thank you!");
System.out.println();
}
}
}
if ( choice == 2 )
{
System.out.println("Subjects" + "\tGrades");
System.out.println("---------------------");
for(int p = 0; p < subjects.length; p++)
{
System.out.println(subjects[p] + "\t" + "\t" + grades[p]);
}
}
if ( choice == 3 )
{
System.out.println("Total of grades: " + getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + getAverage(grades));
System.out.println();
}
} while ( choice != 4);
}
}
And the second class is:
public class Grades {
public static double getAverage(int[] array)
{
int sum = 0;
for(int i : array) sum += i;
return ( ( double ) sum )/array.length;
}
public static double getSum(int[] array)
{
int sum = 0;
for (int i : array)
{
sum += i;
}
return sum;
}
}
You don't need this, because it only has static methods:
Grades method = new Grades(); // <-- delete this line
To call static methods they must be preceded with their class name like this:
System.out.println("Total of grades: " + Grades.getSum(grades));
System.out.println("Count of grades: " + grades.length);
System.out.println("Average of grades: " + Grades.getAverage(grades));
Your code doesn't compile. Don't try to execute non-compiling code. Fix all the compilation errors before executing the code. They're visible in the "Problems" view of your Eclipse IDE.
You need to call Grades.getSum and Grades.getAverage to get the right result. Also, don't forget to import the Grade class, using the command import Grades; in the beginning of the UserInteraction class.

Categories

Resources