CS 1073 Introductory Programming
|
import java.io.*;
public class Scores {
// getNextChar: fetches next char
public static char getNextChar() {
char ch;
try {
ch = (char)System.in.read();
}
catch (Exception exception)
{
System.out.println("Error reading character");
ch = ' ';
}
return ch;
}
// getNextInt: fetches next int.
public static int getNextInt() {
char ch = ' '; // = ' ' to keep compiler happy
int num; // the number to convert
int sign = 1; // gives sign of answer
ch = getNextChar();
// skip over initial blanks and newlines
while (ch == ' ' || ch == '\n')
ch = getNextChar();
// check for + or - sign
if (ch == '+') ch = getNextChar();
if (ch == '-') {
sign = -1;
ch = getNextChar();
}
// read digits, construct input integer;
// (same as the method "Integer.parseInt()" )
num = 0;
while (Character.isDigit(ch)) {
num = num*10 + (ch - '0');
ch = getNextChar();
}
return sign * num;
}
public static void main(String[] args) {
int n = 0; // number of scores
int[] s = new int[10]; // array, room for up to 10 scores
for (;;) { // infinite loop, terminated by break inside
int score = getNextInt();
if (score == -1) break;
s[n] = score;
n++;
}
for (int i = 0; i < n; i++) // loop to print scores
System.out.print(s[i] + " ");
}
}
Here are results of runs with with two different sets of scores boldface is data entered):
80 90 100 -1 80 90 100
72 85 92 87 -1 72 85 92 87
import java.io.*;
public class Scores {
// functions getNextChar and getNextInt here
public static void main(String[] args) {
int n = 0; // number of scores
int[] s = new int[10]; // array, room for up to 10 scores
for (;;) { // infinite loop, terminated by break inside
int score = getNextInt();
if (score == -1) break;
s[n] = score;
n++;
}
for (int i = 0; i < n; i++) // loop to print scores
System.out.print(s[i] + " ");
System.out.println();
double average;
int sum = 0; // needed for average
for (int i = 0; i < n; i++) // loop to calculate average
sum = sum + s[i];
average = (double)sum/n;
System.out.println("Average score: " + average);
int minScore = s[0];
int maxScore = s[0];
for (int i = 1; i < n; i++) { // loop to calculate min and max
if (s[i] > maxScore) maxScore = s[i];
else if (s[i] < minScore) minScore = s[i];
}
System.out.println("Max score: " + maxScore + ", Min score: " + minScore);
}
}
Here are results of runs with with two different sets of scores boldface is data entered):
80 100 90 -1 80 100 90 Average score: 90.0 Max score: 100, Min score: 80
98 75 83 95 71 88 65 -1 98 75 83 95 71 88 65 Average score: 82.14285714285714 Max score: 98, Min score: 65