In: Computer Science
Can you provide java code for a program that prompts the user by asking "How many one mile races have you ran?". After the user inputs how many one mile races have they run it then prompts the user to input how many seconds it took for them to finish each race. So for example, if the user ran 6 races then the user will have to input 6 race times. Is there a way when you prompt the user to enter the race time to ask "How many seconds did you take you to finish race 1?" and the same for the second race (if they completed more than one race and so on for how many races they completed. Then can it display the average number of seconds it took for every race, by saying "Your average race time is" + averageRacetime+ "in seconds". Then can the program ask if the user "Do you want to start a new average race time?" if no then the program starts if yes then the program starts over and again asks "How many one mile races have you ran?" following the same structure as the first one.
Code:
import java.util.*;
class averageRace
{
public static void main(String[] args)
{
while(true)
{
int n;
double
averageRacetime,sum=0;
/*Decalred
averiables*/
Scanner scnr=new
Scanner(System.in);
/*Creting
scanner object*/
System.out.print("How many one mile races have you ran? ");
n=scnr.nextInt();
/*Rading no of
races */
double[] time =
new double[n];
for(int
i=0;i<n;i++)
{
System.out.print("How many seconds did you take
you to finish race "+(i+1)+"?" );
time[i]=scnr.nextDouble();
/*Reading time in each race*/
sum+=time[i];
/*Adding the time to sum*/
}
averageRacetime=sum/(double)n;
/*Calculating
average race time*/
System.out.println("Your average race time is " + averageRacetime+
" seconds");
System.out.print("Do you want to start a new average race
time?");
choice=scnr.next();
/*Asking user to
continue or not*/
if(choice.equals("yes"))
{
continue;
}
else
{
break;
}
}
}
}
Output:
Indentation: