Average of an array and associate with name - java

Does anyone know how to display the average race time for participants in this simple program?
It would also be great to display the associated runners name with the time.
I think that I have the arrays structure properly and have taken in the user input.
Thanks for any assistance you can provide. Here's my code...
import java.util.Scanner;
public class RunningProg
{
public static void main (String[] args)
{
int num;
Scanner input= new Scanner (System.in);
System.out.println("Welcome to Running Statistical Analysis Application");
System.out.println("******************************************************************* \n");
System.out.println("Please input number of participants (2 to 10)");
num=input.nextInt();
// If the user enters an invalid number... display error message...
while(num<2|| num >10)
{
System.out.println("Error invalid input! Try again! \nPlease input a valid number of participants (2-10)...");
num=input.nextInt();
}
// declare arrays
double resultArray [] = new double [num]; // create result array with new operator
String nameArray [] = new String [num];// create name array with new operator
// Using the num int will ensure that the array holds the number of elements inputed by user
// loop to take in user input for both arrays (name and result)
for (int i = 0 ; i < nameArray.length ; i++)
{
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
nameArray[i] = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
resultArray[i] = input.nextDouble();
}

This seems like a homework problem so here is how you can solve your problems, in pseudo-code:
Total average race time for participants is calculated by summing up all the results and dividing by the amount of results:
sum = 0
for i = 0 to results.length // sum up all the results in a loop
sum = sum + results[i]
average = sum / results.length // divide the sum by the amount of results to get the average
It would be even better to perform the summation while you read user input and store the runner's names and results. The reason is that it would be more efficient (there would be no need for a second loop to perform the sum) and the code would be cleaner (there would be less of it).
Displaying runners with theirs times can be done by iterating over the two arrays that hold names and results and print values at corresponding index:
for i = 0 to results.length
print "Runner: " + names[i] + " Time: " + results[i]
This works because you have the same amount of results and names (results.length == names.length), otherwise you would end up with an ArrayIndexOutOfBounds exception.
Another way to do this is to use the object-oriented nature of Java and create an object called Runner:
class Runner {
String name;
double result;
Runner(String n, double r) {
result = r;
name = n;
}
}
Then use an array to store these runners:
Runner[] runners = new Runner[num];
for (int i = 0 ; i < num ; i++) {
System.out.println ("Please enter a race participant Name for runner " + (i+1) );
String name = input.next();
System.out.println ("Please enter a race result (time between 0.00 and 10.00) for runner " + (i+1) );
double result = input.nextDouble();
runners[i] = new Runner(name, result);
}
Then you can just iterate over the array of runners and print the names and the results... Here is pseudo-code for this:
for i = 0 to runners.length
print runners[i].name + " " + runners[i].result

Related

How can I get the system output value after the whole loop is done?

this is my first question in this community as you can see I'm a beginner and I have very little knowledge about java and coding in general. however, in my beginner practices, I came up with a little project challenge for myself. as you can see in the figure, the loop starts and it prints out the number that is given to it through the scanner. the problem with my attempt to this code is that it gives me the output value as soon as I press enter. what I want to do is an alternative of this code but I want the output values to be given after the whole loop is done all together.
figure
So, basically what I want is to make the program give me the input values together after the loop ends, instead of giving them separately after each number is put.
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
calc(); }
public static int calc (){
Scanner scan = new Scanner(System.in);
int count = 1;
int pass = 0;
int notpass = 0;
System.out.println("how many subjects do you have? ");
boolean check = scan.hasNextInt();
int maxless = scan.nextInt();
if (check){
while(count <= maxless ){
System.out.println("Enter grade number " + count);
int number = scan.nextInt();
System.out.println("grade number" + count + " is " + number);
if (number >= 50){
pass++;
}else{
notpass++;
}
count++;
}
System.out.println("number of passed subjects = " + pass);
System.out.println("number of failed subjects = " + notpass);
}else{
System.out.println("invalid value!");
} return pass;
}
}
I think what you want to do is create an array of int numbers.
It would be something like this:
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int maxless = 5;
int[] numbers = new int[maxless];
int count = 0, pass = 0, notPass = 0;
while(count < maxless){
System.out.println("Enter grade number " + (count + 1) + ":");
numbers[count] = scan.nextInt();
if(numbers[count] >= 50){
pass++;
}
else{
notPass++;
}
count++;
}
for(int i=0; i<maxless; i++){
System.out.println("Grade number " + (i + 1) + " is " + numbers[i]);
}
}
}
The output is the following:
Enter grade number 1:
90
Enter grade number 2:
76
Enter grade number 3:
54
Enter grade number 4:
67
Enter grade number 5:
43
Grade number 1 is 90
Grade number 2 is 76
Grade number 3 is 54
Grade number 4 is 67
Grade number 5 is 43
When dealing with arrays, just remember that the indexation begins at 0. You can read more about arrays here: http://www.dmc.fmph.uniba.sk/public_html/doc/Java/ch5.htm#:~:text=An%20array%20is%20a%20collection,types%20in%20a%20single%20array.
A tip: it's gonna be easier to help if you post the code on your question as a text, not an image, so we can copy it and try it on.
Approach 1 :
You can use ArrayList from Collection Classes and store the result there and after the loop is completed, just print the array in a loop.
Example :
//Import class
import java.util.ArrayList;
//Instantiate object
ArrayList<String> output = new ArayList();
while(condition){
output.add("Your data");
}
for(i = 0; i < condition; i++){
System.out.println(output.get(i));
}
Approach 2 :
Use StringBuilder class and append the output to the string, after the loop is completed, print the string from stringbuilder object.
Example :
//import classes
import java.util.*;
//instantiate object
StringBuilder string = new StringBuilder();
while(condition){
string.append("Your string/n");
}
System.out.print(string.toString());
Approach 3 : (As mentioned by Sarah)
Use arrays to store the result percentage or whatever and format it later in a loop. (Not a feasible approach if you want to store multiple values for the same student)
Example :
int studentMarks[] = new int[array_size];
int i = 0;
while(condition){
studentMarks[i++] = marks;
}
for(int j = 0; j < i; j++)
System.out.println("Marks : " + studentMarks[j]);

User Input to determine the length of an array in Java

I am currently taking an intro to java class at my school due to my growing interest in programming.
I am to create a program that takes user input for a min and max integer. I am also to take user input for the size of the array as well as whether or not the user would like both the sorted and unsorted lists printed out.
After I collect this information, I need to generate random values within the given min/max range and sort those values(I had no problem completing these steps).
My code:
//Third Project by John Mitchell
package thirdProject;
//Imported library
import java.util.*;
//First class
public class thirdProject {
//Created scanner and random class as well as variables
public static Scanner scan = new Scanner(System.in);
public static Random rand = new Random();
public static int min, max, rand_num, sum, total, temp, i, j;
public static boolean sorted;
public static int[] values = new int[];
//Allowing for the average output to be of type double
public static double average;
//Main method
public static void main(String[] args) {
//Prompt user to enter minimum value to be sorted
System.out.println("Please enter a minimum value: ");
min = scan.nextInt();
//Prompt user to enter maximum value to be sorted
System.out.println("\nPlease enter a maximum value: ");
max = scan.nextInt();
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
//Prompt the user whether or not they would like both lists
System.out.println("\nWould you like to see both the sorted and unsorted lists? Please enter 'True' for yes or 'False' for no.");
sorted = scan.nextBoolean();
//Prints lists that were generated
if (sorted == true) {
gen_random_val();
System.out.println("\nThe unsorted list is: " + Arrays.toString(values) + ".");
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
} else {
gen_random_val();
sort_values();
System.out.println("\nThe sorted list is: " + Arrays.toString(values) + ".");
}
}
//Second method
public static void gen_random_val() {
//For loop that generates values within the range of values given
for(int i = 0; i < values.length; i++) {
values[i] = rand_num = Math.abs(rand.nextInt(max) % (max - min + 1) + min);
sum = sum + values[i];
average = (sum*1.0) / values.length;
}
}
//Third method
public static void sort_values() {
//For loop that sorts values
for(i=0; i<(total-1); i++) {
for(j=0; j<(total-i-1); j++) {
if(values[j] > values[j+1]) {
temp = values[j];
values[j] = values[j+1];
values[j+1] = temp;
}
}
}
}
}
Currently, the hard codes length of 10 values in the array works fine as I have recycled part of my code from a previous project. I am looking for guidance on how to simply make the size determined by user input.
Thank you.
For example you can do this:
//Prompt user to enter total number of values to be sorted
System.out.println("\nPlease enter the number of values that you would like sorted: ");
total = scan.nextInt();
values = new int[total];
You don't have to give values to variables when you declare them.

How do I get inputs from a user and find the highest, lowest, and average of them?

I am in the process of writing code that asks the user for their name, how many jobs they have, and the income of those jobs. Then the code finds the highest and lowest paying incomes, and the average of the jobs they entered.
Im having issues with the highest and lowest paying portion, along with finding the average, while still maintaining what the user entered in order to recite it later.
Ex:
Inputs: 10000 30000 50000
"Hello Audrey. You have had 3 jobs. The highest paying job paid $50000. The lowest paying job paid $10000. The average pay for the jobs entered is $30000
**** heres the code I have edited, but it is not running properly. I believe it has to do with int and double. Im not sure which code should be double and which ones should be int.****
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class JobIncome {
public static void main(String[] args) throws FileNotFoundException {
Scanner input = new Scanner (System.in);
System.out.println("What is your first name? ");
String firstName = input.nextLine();
Scanner scan = new Scanner (System.in);
System.out.println("How many jobs have you had? ");
int jobNum = scan.nextInt();
//Declarations
int total = 0;
int average = 0;
//for loop asks for the incomes of the user's previous
//jobs and stores them into an array
int arrayOfIncomes[] = new int[jobNum];
for(int i = 1; i <= arrayOfIncomes.length; i++){
System.out.println("Enter the income of job #" + i + " : ");
arrayOfIncomes[i] = scan.nextInt();
total = total + arrayOfIncomes[i];
}
average = total/jobNum;
//Start of the code that will find the min and max
int min = arrayOfIncomes[0];
int max = arrayOfIncomes[0];
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] > max) {
max = arrayOfIncomes[i];
}
}
for (int i = 1; i < arrayOfIncomes.length; i++) {
if (arrayOfIncomes[i] < min) {
min = arrayOfIncomes[i];
}
}
//Print statement that gives the user all their information
System.out.println("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
//Prompt asking the user if they would like to print their info into a text file
System.out.println("Would you like to output your information into a text file, yes or no? ");
String yesNo = input.nextLine();
if(yesNo.equals("yes")){
System.out.println("");
} else {
System.out.println("Goodbye.");
}
//Output code
Scanner console = new Scanner(System.in);
System.out.print("Your output file: ");
String outputFileName = console.next();
PrintWriter out = new PrintWriter(outputFileName);
//This code prints the information into the output text file
out.print("Hello, " + firstName + ". You have had" + jobNum +
"jobs. The highest paying job paid $" + max +
". The lowest paying job paid $" + min +
". The average pay for the " + jobNum + "jobs entered is $" + average + ".");
out.close();
}
Fix the code by instantiating an array, jobIncomes with the length equivalent to the number of jobs. You could keep a running average, but you would lose precision when rounding. You will also need to instantiate three integer variables: total, max and min, each at zero.
For every iteration of the loop, you should add the following code:
jobIncomes[i-1]=s.nextInt();
if (jobIncomes[i-1]<min)
{ min=jobIncomes[i-1];}
if (jobIncomes[i-1]>max
{max=jobIncomes[i-1];}
total+=jobIncomes[i-1];
When you print the average, you can cast the formula average = total/jobNum. You might also want to change the array values to read from 0 to jobNum-1, if you want to index simply by i in the if statements.
Create an int variable sum. Add the sum as you get input from the user then divide the sum with the variable jobNum while casting at least one variable to double.
Example:
double ave = (double) sum / jobNum;

School Assignment Multidimensional Array Trouble

I am currently working on an assignment for my Java programming class. I seem to have got myself in a bit of a bind. Any assistance in helping me realize what I am doing wrong would be greatly appreciated.
Assignment
Write a program that does the following:
Put the data below into a multi-dimensional array
Prompts the user for the company they would like employee salary statistics.
Write a method that returns the average employee salary as a double. Pass the company number and employee Wages to this method.
Write a method that returns the total employee salary as an int. Pass the company number and employee Wages to this method.
Write a method that returns the number of employees as an int. Pass the company number and employee Wages to this method.
In the main method call the other methods and out put the results.
Keep in mind that I am still new and struggling to understand some of the principles of programming.
When I run the program I am getting locations instead of method calculations (bad output):
Here is what I have so far:
package salaries;
import java.util.Scanner;
public class Salaries {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
//declare, instantiate, and define value of multi array [3] [12]
double [][] mSalary = { { 49920, 50831, 39430, 54697, 41751, 36110,
41928, 48460, 39714, 49271, 51713, 38903},
{ 45519, 47373, 36824, 51229, 36966, 40332,
53294, 44907, 36050, 51574, 39758, 53847},
{ 54619, 48339, 44260, 44390, 39732, 44073,
53308, 35459, 52448, 38364, 39990, 47373}};
//declare, instantiate, and define value
//of single array for company names
//and output values to user for selection
String [] company = { "Alhermit", "Logway", "Felter" };
for( int i = 0; i < company.length; i++ )
System.out.println( "Company " + i + " : " +company[i] );
Scanner scan = new Scanner( System.in );
int cCompany;
do{
//ouput for user to select a company
System.out.print("Select company: (0)" +company[0]+ ", (1)"
+company[1]+ "; (2)" +company[2]+ " > ");
//scan user input into cCompany
cCompany = scan.nextInt();
//call number method
num nums = new num();
nums.number(mSalary, cCompany);
//call total method
total sum = new total();
sum.total(mSalary, cCompany);
//call average method
avg cAvg = new avg();
cAvg.average(mSalary, cCompany);
//output statistics to user on selected company
System.out.println( "You have selected the company " + company[cCompany] + ". " );
System.out.println( company[cCompany] + " has " + nums + " of employees." );
System.out.println( "A total employee salary of " + sum + "." );
System.out.println( "The average employee salary is " + cAvg );
}
while( cCompany < 0 || cCompany > 2);
}
}
//total class to calculate
//salary of user selected company
class total {
public static int total( double [][] mSalary, int cCompany ){
//assign variables
int sum = 0;
//for loop to calculate salary total of user input company
for( int j = 0; j < mSalary[cCompany].length; j++ ){
sum += mSalary[cCompany][j];
}
//return statement
return sum;
}
}
//average class to calculate
//average of user selected company
class avg {
public static double average( double [][] mSalary, int cCompany){
//assign variables
int cAvg = 0;
int sum = 0;
int count = 0;
//totals the values for the selected company by
//iterating through the array with count.
while( count < mSalary[cCompany].length){
sum += mSalary[cCompany][count];
count +=1;
}
cAvg = sum / mSalary[cCompany].length;
return cAvg;
}
}
//number class to calculate amount of
//employees in user selected company
class num {
public static int number( double [][] mSalary, int cCompany){
//assign variables
int nums = 0;
//number of employees based on length of colomn
nums = mSalary[cCompany].length;
return nums;
}
}
nums, sum, and cAvg are all instances of classes that you have, you're printing out the instances of those classes.
(By the way - you should change the name of these classes. Classes start with a capital letter. It differentiates them from variables.)
There are two things wrong with this.
You are instantiating a class which contains no data and has no toString method.
You're instantiating a class which only has static methods to return the data from. You don't need to instantiate the class at all; instead, just print the result of the method call.
That would change at least one of these calls to something like:
System.out.println( company[cCompany] + " has " + num.number(mSalary, cCompany); + " of employees." );
I leave the rest as an exercise for the reader.

I need to turn a comma-separated string into an array list and then calculate the average of those scores [duplicate]

This question already has answers here:
Splitting String and put it on int array
(8 answers)
Closed 6 years ago.
I am trying to take the code inputs that I have and turn them into an int array list so that I can use them to calculate the average score but I'm not sure on how to do this. Also when it comes to the scores the inputs can range from 1-5, so one student could have 3 scores and the next could have 5 and so on. This is the code I have so far.
My main question is how do I take my list inputs and turn them into separate array integers?
//data declarations and initalizations
final int MAX_STUDENTS = 12;
final int MAX_SCORE = 5;
//data declarations
double avg; //average total for all students
int numStudents; //number of students 1-12
double totalAvgStu = 0.0; //
int num;
String stuScores = " "; //student score 1-5
//array declarations and inistiations
int [] score = new int[MAX_SCORE]; // score from input range between 1-5
double [] avgScores = new double[MAX_STUDENTS]; //avg total of score for one student
String [] testScores = new String[MAX_STUDENTS];
String [] array1 = new String[MAX_SCORE];
//user inputs for number of students
numStudents = UtilsKS.readInt("Enter number of students: ", false);
//while loop for correct input of students
while (numStudents <= 0 || numStudents > 12) {
System.out.print("ERROR: must be 1-12, ");
numStudents = UtilsKS.readInt("Enter number of students: ", false);
}
// user input for student score using a for loop
for (int i = 0; i < numStudents; i++) {
stuScores = UtilsKS.readString("Enter comma-separated test score for student " + (i+1) + ": ", false);
}
//for loop for arrays
for (int i=0; i<avgScores.length; i++) {
totalAvgStu += avgScores[i];
}
//outputs
String header = "average score1 score2 score3 score4 score5";
System.out.println("\n" + header);
System.out.println("\nAvg for all students = " + totalAvgStu/avgScores.length);
//initializing testscore to = what scores are inputed per student
for (int t=0; t<numStudents; t++) {
testScores[t] = stuScores;
}
Arrays.stream("1,2,3,4,5".split(",")).mapToInt(Integer::parseInt).average();
I suggest considering my compact solution. That returns OptionalDouble. getAsDouble() will return you the result if you firstly check it by isPresent() to avoid NoSuchElementException.
EDIT:
I don't like to write massive pieces of code with long variable names, but I made the exception for you to better understanding.
String commaSeparatedString = "1,2,3,4,5";
String[] numbers = commaSeparatedString.split(",");
Stream<String> stringStream = Arrays.stream(numbers);
IntStream intStream = stringStream.mapToInt(value -> Integer.parseInt(value));
OptionalDouble average = intStream.average();
System.out.println(average.isPresent() ?
"average = " + average.getAsDouble() :
"stream is empty!")
Can you provide a sample input and output?
Also an easy(hacky) way would be to intialize 2 variables temp and sum. Parse the string using the comma. Store the value in the temp and add to sum. Store a counter for number of times youve done these steps. Divide sum by counter to get average.

Categories

Resources