I have a question where I am asked to get a user to input a sequence of speeds a
ID: 3926380 • Letter: I
Question
I have a question where I am asked to get a user to input a sequence of speeds and I have to return a summary of the sequence, including # of readings, # over speed limit, max speed and average speed. Here is my code:
import java.util.Scanner;
public class Speed {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int numReadings = 0;
int maxSpeed = 0;
int speedLimit = 0;
int fastDrivers = 0;
int totalSpeed = 0;
System.out.println("Enter speed limit: ");
speedLimit = scan.nextInt();
System.out.println("Enter sequence of speeds terminated with negative value: ");
int newSpeed=scan.nextInt();
while (newSpeed > 0) {
newSpeed = scan.nextInt();
if (newSpeed > speedLimit) {
fastDrivers++;
}
if (newSpeed > maxSpeed) {
maxSpeed = newSpeed;
}
numReadings++;
totalSpeed = totalSpeed + newSpeed;
}
int averageSpeed = totalSpeed/numReadings;
System.out.println(numReadings + " readings: " + fastDrivers + " over the speed limit, Maximum speed = "
+ maxSpeed + ", average speed = " + averageSpeed);
}
}
//end of code
The problem is that I get the wrong average speed so clearly the total speed is being calculated incorrectly. Here is my sample output:
User-MacBook-Air:Lab4 User$ java Speed
Enter speed limit:
100
Enter sequence of speeds terminated with negative value:
80 95 120 115 101 98 130 -1
7 readings: 4 over the speed limit, Maximum speed = 130, average speed = 94
//end of code
Correct answer should be:
7 readings: 4 over the speed limit, Maximum speed = 130, average speed = 105
Explanation / Answer
import java.util.*;
public class testloop {
public static void main(String[] args) {
Scanner scan = new Scanner (System.in);
int numReadings = 0;
int maxSpeed = 0;
int speedLimit = 0;
int fastDrivers = 0;
int totalSpeed = 0;
int value=0;
System.out.println("Enter speed limit: ");
speedLimit = scan.nextInt();
System.out.println("Enter sequence of speeds terminated with negative value: ");
int newSpeed=scan.nextInt();
while (newSpeed > 0) {
value=newSpeed;
newSpeed = scan.nextInt();
if (newSpeed > speedLimit) {
fastDrivers++;
}
if (newSpeed > maxSpeed) {
maxSpeed = newSpeed;
}
numReadings++;
totalSpeed+=value;
}
int averageSpeed = totalSpeed/numReadings;
System.out.println(numReadings + " readings: " + fastDrivers + " over the speed limit, Maximum speed = "
+ maxSpeed + ", average speed = " + averageSpeed);
}
}
output:
Enter speed limit:
100
Enter sequence of speeds terminated with negative value:
80
95
120
115
101
98
130
-1
7 readings: 4 over the speed limit, Maximum speed = 130, average speed = 105
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.