You are to write a program to compute statistics on a list of exam scores, the Exam Statistics Program (ESP). The input is the name of a text file that contains the number of scores followed by the list of scores. (See the example below.) You should then display the following information:
a. The number of scores
b. The minimum, maximum, and average scores
c. The number of As, Bs, Cs, Ds, and Fs, using a 90-80-70-60 scale.
My problem is: I don't know how to have variable grade take numbers.
When I run this program, it gives me this error:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at IntegersFromFile.main(IntegersFromFile.java:60)
Here is my code:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class IntegersFromFile
{
public static void main(String[] args)
{
Scanner file = null;
int grade = 0;
int min = 100;
int max = 0;
ArrayList<Integer> grades = new ArrayList<Integer>();
int a, b, c, d, f;
a = 0;
b = 0;
c = 0;
d = 0;
f = 0;
double aA, aB, aC, aD, aF;
aA = 0;
aB = 0;
aC = 0;
aD = 0;
aF = 0;
System.out.println("***Welcome to the Exam Statistics Program!!***");
System.out.println("Please enter the name of your data file:");
Scanner input = new Scanner(System.in);
String file_name = input.nextLine();
try
{
file = new Scanner(new File(file_name));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
while (file.hasNext())
{
if (file.hasNextInt())
{
grades.add(file.nextInt());
}
else
file.next();
}
do
{
grade = file.nextInt();
if (grade >= 0)
{
grades.add(grade);
if (grade < 60)
{
f++;
aF += grade;
}
else if (grade < 70)
{
d++;
aD += grade;
}
else if (grade < 80)
{
c++;
aC += grade;
}
else if (grade < 90)
{
b++;
aB += grade;
}
else
{
a++;
aA += grade;
}
if (grade < min)
min = grade;
if (grade > max)
max = grade;
}
}
while (grade >= 0);
if (aA > 0)
aA /= a;
if (aB > 0)
aB /= b;
if (aC > 0)
aC /= c;
if (aD > 0)
aD /= d;
if (aF > 0)
aF /= f;
double avg = 0;
for (int i = 0; i < grades.size(); i++) {
avg += grades.get(i);
}
avg /= grades.size();
System.out.println("Total Number of Scores: " + grades.size());
System.out.println("Total As: " + a);
System.out.println("Total Bs: " + b);
System.out.println("Total Cs: " + c);
System.out.println("Total Ds: " + d);
System.out.println("Total Fs: " + f);
System.out.println("Average A: " + aA);
System.out.println("Average B: " + aB);
System.out.println("Average C: " + aC);
System.out.println("Average D: " + aD);
System.out.println("Average F: " + aF);
System.out.println("The highest grade was " + max);
System.out.println("The lowest grade was " + min);
System.out.println("The average grade was " + avg);
}
}
The problem is that when the execution of the program reaches line 60, the input for the scanner is "exhausted". You should re-initialize the file variable (recommend you to rename it to scanner or similar) just before beginning with the do- cycle.
Not quite sure of the logic of the application, especially whether the do- cycle should be inside the while- cycle or not, but I would recommend you to use brackets even if the control structure has only one statement. This you will outline your intention better and will reduce the possibility for errors which are hard to find.
Related
Can someone please tell me why my code is not providing the correct output? Here aare the instructions "
I need to write a program that reads student scores, gets the best
score, and then assigns grades based on the following scheme:
1) Grade is A if score is >= best - 10
2) Grade is B if score is >= best - 20;
3) Grade is C if score is >= best - 30;
4) Grade is D if score is >= best - 40;
5) Grade is F otherwise.
The program prompts the user to enter the total number of students, then prompts the user to enter all of the scores, and concludes by displaying the grades. My problem comes from pulling the grades from an array, this is what I have so far:
// Here is my code. Thank You
import java.util.Scanner; // imports the scanner function
public class NBpractice { //class is formed
public static void main(String []args) { // main method
// user input is asked for the number of students
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int studentNum = input.nextInt();
//user input is asked for students scores
Scanner input2 = new Scanner(System.in);
System.out.print("Enter " + studentNum + " scores: ");
int scores = input2.nextInt();
int best = 80;
char letterGrade;
int scoresArray[] = new int[studentNum]; // array is created and holds the # of place values as students
for (int i = 0; i < scoresArray.length; i++) { // for loop created
scoresArray[i] = input2.nextInt(); //array values are assigned to user's input
best = scoresArray[0];
if (best < scoresArray[i]) {
best = scoresArray[i];
}
//-----------------------------------------------------------------------------
if (scores >= (best - 10)) {
letterGrade = 'A';
}
else if (scores >= (best - 20)) {
letterGrade = 'B';
}
else if (scores
>= (best - 30)) {
letterGrade = 'C';
}
else if (scores >= (best - 30)) {
letterGrade = 'D';
}
else {
letterGrade = 'F';
}
System.out.println("Student " + i + " Score is " + scoresArray[i] + " and grade is: " + letterGrade );
}
//------------------------------------------------------------
}
}
Some pointers...
This: System.out.print("Enter " + studentNum + " scores: "); and int scores = input2.nextInt(); need to go in the for loop body.
Use the for loop to populate the array.
Once that the for loop is executed, find the best (highest) score in the array.
Use another for loop to sort out the grades.
As is, your program will only ask for the grades and pretty much assumes that the best grade is 80, which might not always be the case.
You'll need two separate for loops. One to read the grades, and get the best, and the second for loop to normalize the grades.
int[] scores = new int[amount];
int best = -1;
for(int i = 0; i < amount; i++)
{
scores[i] = in.nextInt();
if(scores[i] > best)
best = scores[i];
}
System.out.println(Arrays.toString(scores));
// Now that we have the best, we can normalize
// the rest of the scores based on the best
// and assign the corresponding letter grade.
String[] grades = new String[amount];
for(int i = 0; i < amount; i++)
{
int score = scores[i] * 100 / best;
if(score >= 90)
grades[i] = "A";
else if(score >= 80)
grades[i] = "B";
else if(score >= 70)
grades[i] = "C";
else if(score >= 60)
grades[i] = "D";
else
grades[i] = "F";
scores[i] = score;
}
System.out.println(Arrays.toString(scores));
System.out.println(Arrays.toString(grades));
Test input 80 60 75 83 67 outputs:
[80, 60, 75, 83, 67]
[96, 72, 90, 100, 80]
[A, C, A, A, B]
I would recommend using a Student class and not work with parallel lists or arrays. A Student class can for example look like this:
class Student {
int score;
String grade; // could also be an Enum
public int getScore() {
return this.score;
}
public void setScore(int score) {
this.score = score;
}
public String getGrade() {
return this.grade;
}
public void setGrade(String grade) {
this.grade = grade;
}
#Override
public String toString() {
return "Student{" + "score=" + score + ", grade='" + grade + '\'' + '}';
}
}
You can then make instance of the Students and add them to an ArrayList in you public static void main.
I think you have to use two loops because you cannot know beforehand what the best grade will be. In your main you can make enter the students add them to a List and compare their grades;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the number of students: ");
int highScore = 0;
int numOfStudent = input.nextInt();
List<Student> studentList = new ArrayList<>();
for (int i = 1; i <= numOfStudent; i++) { // you might want to add Exception handling here, by surrounding it with a try / catch or do more checks than only i <= numOfStudent
System.out.printf("please fill in the score of student no %d \n", i);
int score = input.nextInt();
Student student = new Student();
student.setScore(score);
if (score > highScore) {
highScore = score;
}
studentList.add(student);
}
System.out.println("these are the scores and grades of the Students");
for (Student s : studentList) {
if (s.getScore() >= highScore - 10) {
s.setGrade("A");
}
else if (s.getScore() >= highScore - 20) {
s.setGrade("B");
}
else if (s.getScore() >= highScore - 30) {
s.setGrade("C");
}
else if (s.getScore() >= highScore - 40) {
s.setGrade("D");
}
else {
s.setGrade("F");
}
System.out.println(s);
}
}
package Chapter7;
import java.util.Scanner;
public class Exercise7_1 {
public static void main(String[] args) {
// Assign grades
Scanner input = new Scanner(System.in);
int numStudents;
int[] scores;
int best;
System.out.println("Enter the number of students: ");
numStudents = input.nextInt();
scores = new int[numStudents];
System.out.println("Enter " + numStudents + " scores: ");
for (int i = 0; i < numStudents; i++) {
scores[i] = input.nextInt();
}
displayGrades(findBestScore(scores), scores);
}
public static int findBestScore(int[] scores) {
int best = scores[0];
for (int i = 1; i < scores.length-1; i++) {
if (scores[i] > best)
best = scores[i];
}
return best;
}
public static void displayGrades(int best, int[] scores ) {
char grade = ' ';
for (int i = 0; i < scores.length; i++) {
if (scores[i] >= best-10)
grade = 'A';
else if (best - 10 > scores[i] && scores[i] >= best - 20)
grade = 'B';
else if (best - 20 > scores[i] && scores[i] >= best -30)
grade = 'C';
else if (best - 30 > scores[i] && scores[i] >= best -40)
grade = 'D';
else if (best - 40 > scores[i])
grade = 'F';
System.out.println("Student " + i + " score is " + scores[i] + " and grade is " + grade);
}
}
}
This program is supposed to find the maximum, minimum, and average of grades. User inputs int inputGrade and the program displays letter it is. It's supposed to do this how however many students are needed. I'm having trouble writing the method where it finds the max and min. (yes I've talked to my teacher if anyone's wondering...) I pasted the methods below (they don't work). Just like IN GENERAL, does anyone know how to find the maximum and minimum of a set of entered numbers? (not using arrays, lists, or any unusual imports other than scanner) ** note I've updated this a lot...
import java.util.Scanner;
public class GetLetterGrade
{
static int inputGrade; // input grade
public static void main(String [] args)
{
Scanner reader = new Scanner(System.in);
int classAverage;
int classMin; // class's minimum grade
int classMax; // class's maximum grade
while (inputGrade != -1) // while user is entering grades
{
System.out.println("Welcome to the grade calculator. \nPlease enter a
numeric grade. After the last student in the class, enter a grade of
-1.");
inputGrade = reader.nextInt();
letterGrade(inputGrade); // calls letter grade method
findMaxAndMin();
result();
}
}
// find letter grade
public static String letterGrade(int numGrade)
{
String gradeMessage = "";
{
if (numGrade >= 96 && numGrade <= 100) // if numeric grade is 96-100 then
it's A+
{
gradeMessage = "That's an A+.";
result();
// DOES THIS FOR GRADES A+ TO F, NOT SHOWN, too much to paste!
}
}
}
return gradeMessage;
}
public static int findCharGrade(int numGrade)
{
char letter;
if (numGrade >= 90 && numGrade <= 100) // A
{
letter = 'A';
}
else if (numGrade >= 80 && numGrade < 90) // B
{
letter = 'B';
}
else if (numGrade >= 70 && numGrade < 80) // C
{
letter = 'C';
}
else if (numGrade >= 60 && numGrade < 70) // D
{
letter = 'D';
}
else if (numGrade < 60) // F
{
letter = 'F';
}
}
// finds maximum and minimum grades
public static int findMaxAndMin(int inputGrade)
{
int max = Math.max(inputGrade, max);
int min = Math.min(inputGrade, min);
if (inputGrade < max)
{
inputGrade = max;
findCharGrade(inputGrade);
}
else if (inputGrade > min)
{
inputGrade = min;
findCharGrade(inputGrade);
}
}
public static void calcAverage(int sumOfGrades, int numOfStudents)
{
// something goes here
}
// finds results
public static void result()
{
int min = findMaxAndMin(inputGrade);
int max = findMaxAndMin(inputGrade);
System.out.println("Please enter a numeric grade");
int inputGrade = reader.nextInt();
letterGrade(inputGrade);
if (inputGrade == -1)
{
System.out.println("You entered " + numOfStudents + " students. Class
Average: " + average + " Class Minimum: " + min + " Class maximum: " + max
+ " \nThanks for using the class grade calculator!");
}
}
here is a more simplistic way of doing it not using Lists or arrays
double sum = 0; // use double so that you do not do integer arithmetic
int count = 0;
int min = Integer.MAX_VALUE; // set to very high value
int max = Integer.MIN_VALUE; // set to bery low value
Scanner scan1 = new Scanner(System.in);
System.out.println("enter numbers (-1 to quit");
while (scan1.hasNextInt()) {
int i = scan1.nextInt(); // get the number (assuming only int value)
if (i == -1) break;
min = Math.min(i, min);
max = Math.max(i, max);
sum += i;
count++;
}
if (count > 0) {
System.out.println("min " + min);
System.out.println("max " + max);
System.out.println("avg " + sum / count);
}
disclaimer
This code will not handle wrong type of input e.g. Strings
edit
If you want the average to be calculated in a separate method you can have a method like
double calcAvg (double sum, int count) {
return sum / count;
}
this can then be called as
if (count > 0) {
System.out.println("min " + min);
System.out.println("max " + max);
System.out.println("avg " + calcAvg (sum, count));
}
You can (and should) divide your problem into the smaller methods.
I'll drop the code, and you read and study it.
I admit I haven't pay to much attention of this simple quest, but still...
Here you are:
import java.util.List;
public class Answer {
public static void main(String[] args) {
//test with some grades (integers)
Answer answer = new Answer();
List<Integer> someGrades = List.of(12, 66, 34, 96, 3, 77, 2);
System.out.println("max = " + answer.findMaxGrade(someGrades));
System.out.println("min = " + answer.findMinGrade(someGrades));
System.out.println("avg = " + answer.findAverageGrade(someGrades));
}
private int findMaxGrade(List<Integer> grades) {
int max = Integer.MIN_VALUE;
for (int grade : grades) {
if (grade > max) max = grade;
}
return max;
}
private int findMinGrade(List<Integer> grades) {
int min = Integer.MAX_VALUE;
for (int grade : grades) {
if (grade < min) min = grade;
}
return min;
}
private double findAverageGrade(List<Integer> grades) {
double average = 0;
for (int grade : grades) {
average += grade;
}
return average / grades.size();
}
}
package example;
import java.util.Scanner;
class Example {
public static void main(String[] args) {
Scanner r = new Scanner(System.in);
int m = 1, total = 0, max = 0, min = 100;
double avg = 0;
while (m <= 5) {
System.out.print("Input marks " + m + " = ");
int inp = r.nextInt();
total += inp;
m++;
min=min<inp?min:inp;
max=max<inp?inp:max;
}
avg = (double)(total) / 5;
System.out.println("Total : " + total);
System.out.println("Max : " + max);
System.out.println("Min : " + min);
System.out.println("Average : " + avg);
}
}
import java.util.Scanner;
public class BA4 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Hello Drews, how many total grades do you want to process?");
int numberOfGrades = keyboard.nextInt();
int[] storeGrades = new int[numberOfGrades];
for (int i = 0; i < numberOfGrades; i++) {
System.out.println("Please enter grade " + (i + 1) + ": ");
storeGrades[i] = keyboard.nextInt();
}
System.out.println("Total score is: " + (getTotalScore(storeGrades)));
System.out.println("Lowest score is: " + (getLowestScore(storeGrades)));
System.out.println("Highest score is: " + (getHighestScore(storeGrades)));
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
}
public static int getTotalScore(int[] storeGrades) {
int sum = 0;
for (int i = 0; i < storeGrades.length; i++) {
sum += storeGrades[i];
}
return sum;
}
public static int getLowestScore(int[] storeGrades) {
int getLowestScore = 0;
for (int i = 0; i > storeGrades.length; i++) {
getLowestScore = storeGrades[i];
}
return getLowestScore;
}
public static int getHighestScore(int[] storeGrades) {
int getHighestScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
getHighestScore = storeGrades[i];
}
return getHighestScore;
}
public static double averageScore(double[] storeGrades) {
double averageScore = 0;
for (int i = 0; i < storeGrades.length; i++) {
averageScore = (double) storeGrades[i];
}
return averageScore;
}
public static int printGrade(int[] storeGrades) {
int printGrade;
if (printGrade > 89) {
String gradeSoFar = "A";
System.out.println("Your grade so far is an " + gradeSoFar);
}
else if ((printGrade > 79) && (printGrade < 90)) {
String gradeSoFar = "B";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 69) && (printGrade < 80)) {
String gradeSoFar = "C";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 59) && (printGrade < 70)) {
String gradeSoFar = "D";
System.out.println("Your grade so far is a " + gradeSoFar);
}
else if ((printGrade > 0) && (printGrade < 60)) {
String gradeSoFar = "F";
System.out.println("Your grade so far is an " + gradeSoFar);
}
return printGrade;
}
}
I am trying to figure out where I am going wrong. I have a couple of errors which leads me to believe I really just don't understand methods as well as I thought I did.
The goal is to create 5 methods displaying to the user the total, lowest, highest and average scores, and then to print the letter grade. Thank you for your assistance to this noobie java coder! :)
You are passing in a String when you should be passing in a Double[] into averageScore function in this line:
System.out.println("Average score is: " + (averageScore(String.format("%.2f", storeGrades))));
and you did not initialize the printGrade variable inside the printGrade function, you need to give it an initial value if you are going to use it in a comparison.
That's all the errors that
I've been trying to get this program to work for hours now. I managed to get the Fahrenheit to Celsius conversion to work, but for the life of me I can't do the same for the Celsius to Fahrenheit. I'm going to ask my teacher when school starts up again, but as of now I would appreciate some help. Here's my code.
import java.util.Scanner;
public class TempConvert {
public static void main(String[] args) {
//variables
double number;
int maxFahrenheit = 52;
int maxCelsius = 20;
Scanner keyboard = new Scanner(System.in);
//user input
System.out.println("Please enter 1 to convert from Fahrenheit to" +
" Celsius");
System.out.println("Please enter 2 to convert from Celsius to" +
" Fahrenheit");
number = keyboard.nextDouble();
//if else
if (number == 1) {
System.out.println("Celsius\t\tFahrenheit");
System.out.println("---------------------------");
int i;
double c;
for (i = 0, c = 0; i <= maxCelsius; i++, c++) {
System.out.println(i + "\t\t" + 9 * (i + 32) / 5);
} //end for
} //end if
else if (number == 2) {
System.out.println("Fahrenheit\t\tCelsius");
System.out.println("-----------------------------------");
int i;
double f;
for (i = 32, f = 32; i <= maxFahrenheit; i++, f++) {
System.out.println(i + "\t\t" + 5 * (f - 32) / 9);
} //end for
} //end else if
else {
System.out.println("Entry is invalid");
} //end else
} //end main
} //end TempConvert
You need to use a DecimalFormat df = new DecimalFormat("#.####");
Look i changed your code like this:
public static void main(String[] args) {
//variables
double number;
int maxFahrenheit = 52;
int maxCelsius = 20;
Scanner keyboard = new Scanner(System.in);
//user input
System.out.println("Please enter 1 to convert from Fahrenheit to" +
" Celsius");
System.out.println("Please enter 2 to convert from Celsius to" +
" Fahrenheit");
number = keyboard.nextDouble();
//if else
if(number == 1) {
System.out.println("Celsius\t\tFahrenheit");
System.out.println("---------------------------");
int i;
double c;
for(i = 0, c = 0; i <= maxCelsius; i++, c++) {
System.out.println(i + "\t\t" + 9 * (i + 32) / 5);
}//end for
}//end if
else if(number ==2) {
System.out.println("Fahrenheit\t\tCelsius");
System.out.println("-----------------------------------");
int i;
double f;
DecimalFormat df = new DecimalFormat("#.####");
for(i = 32, f = 32; i <= maxFahrenheit; i++, f++) {
System.out.println(i + "\t\t" + df.format(5 * (f - 32) / 9));
}//end for
}//end else if
else {
System.out.println("Entry is invalid");
}//end else
}//end main
}//end TempConvert
Look it works better like google and if you post this in google you will see 42 fahrenheit to celsius
42 = 5.55556
just as your tool =)
I am currently working on a java program that has to do with taking classes and the amount of credits for each class. I have everything set up how I need it, except the order.
I would like it to ask for a class, then how many credits that class is, then ask for the next class, and those credits, and so on. Right now, it will ask for all of the classes, then all of the credits. Here's the code I have:
//Jake Petersen
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.println("Please enter a course:");
courseArray[i] = scan.nextLine();
}
int creditArray[] = new int[courses];
for (int i = 0; i < creditArray.length;) {
System.out.println("Please enter how many credits "+ courseArray[i] + " is:");
int input = scan.nextInt();
if (input >= 1 && input <= 4) {
creditArray[i++] = input;
}
}
int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Do all the prompts in a single for loop:
import java.util.Scanner;
public class test1{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.print("How many courses are you going to list?");
int courses = Integer.parseInt(scan.nextLine());
String courseArray[] = new String[courses];
int creditArray[] = new int[courses];
for (int i = 0; i < courseArray.length; i++){
System.out.print("Please enter a course:");
courseArray[i] = scan.nextLine();
System.out.print("Please enter how many credits "+ courseArray[i] + " is:");
String credits = scan.nextLine();
int input = Integer.parseInt(credits);
if (input >= 1 && input <= 4) {
creditArray[i] = input;
}
else {
creditArray[i] = 0;
}
} int sum = 0;
for (int i : creditArray){
sum += i;
}
for (int i = 0; i < courseArray.length; i++) {
System.out.print(courseArray[i] + " is a " + creditArray[i] + " credit class. \n");
}
print(sum);
}
public static void print(int sum){
if(sum >= 12 && sum <= 18){
System.out.println("You are taking " + sum + " total credits, which makes you a full time student.");
}else if(sum < 12){
System.out.println("You are taking " + sum + " total credits, which makes you not a full time student.");
}else{
System.out.println("You are taking " + sum + " total credits, which means you are overloaded");
}
}
}
Of course this assumes that the 2 arrays have the same size. Perhaps you want to prompt for a class count first, to know how large to make the arrays, or grow them dynamically.