getting an average of students graded test scores - java

Read in information for ALL students before doing any calculations or displaying any output. Verify
that the 3 exam scores are between 0-50 points and that the final is between 0-100 as they are entered.
Declared minimums and maximums as constant so that they can easily be updated, as needed. If invalid,
display an error message and allow the user to re-enter that invalid score. Once all student info is read
in, display each student’s name in the format LASTNAME, FIRSTNAME (all uppercase), the student’s
exam percentage (total of all exams plus final / total possible) to 1 decimal and the student’s final grade,
based on the following percentages:
90-100 A, 80-89.9 B, 70-79.9 C, 60-60.9 D, Below 60 F
This is what i have typed out already but its giving me some errors and I'm not sure I'm assigning the values correctly.
import java.util.*;
import java.text.*;
public class Proj4 {
public static void main(String[] args){
Scanner s= new Scanner(System.in);
String input;
String again = "y";
int [] exams = new int[4];
int student = 1;
do
{
String [] names = new String[student];
System.out.print("PLease enter the name of student" + student );
names[student-1] = s.nextLine();
for ( int i = 1; i < exams.length; i++){
if(i==4){
System.out.print("Please enter score for Final Exam: ");
}
System.out.print("Please enter score for Exam" + i);
exams[i] = s.nextInt();
if((exams[1]<0||exams[1]>50)||(exams[2]<0||exams[2]>50)||(exams[3]<0||exams[3]>50)){
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
else if(exams[4]<0||exams[4]>100){
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
System.out.println("do you wish to enter another?");
again = s.nextLine();
student++;
}while (again.equalsIgnoreCase ("y"));
}
}
This is the error message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at Proj4.main(Proj4.java:32)
But its confusing because line 32 is just a } so i really don't know exactly what it means,
i know i probably need to reduce the length of one of the inputs for the arrays but I'm not sure which or if there's even more wrong than that.
EDIT:
Sorry here is my question, Would you guys help me figure out the problem and/or tell me if or what i am doing wrong to get the output required of me?

Array exams has 4 elements only but you try to access 5th element with index 4 here exams[4]<0. First index of array is 0 (not 1).

Does the below work for you?
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String again = "y";
int[] exams = new int[4];
int student = 1;
do {
String[] names = new String[student];
System.out.print("PLease enter the name of student" + student);
names[student - 1] = s.nextLine();
for (int i = 0; i < exams.length; i++) {
System.out.println(i + " i");
if (i == 3) {
System.out.print("Please enter score for Final Exam: ");
exams[i] = s.nextInt();
if (exams[3] < 0 || exams[3] > 100) {
System.out.println("Invalid enter 0-100 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
} else {
System.out.print("Please enter score for Exam " + i);
exams[i] = s.nextInt();
if ((exams[i] < 0 || exams[i] > 50)) {
System.out.println("Invalid enter 0-50 only...");
System.out.print("Please re-enter score: ");
exams[i] = s.nextInt();
}
}
}
System.out.println("do you wish to enter another?");
again = s.next();
student++;
} while (again.equalsIgnoreCase("y"));
}

Related

How can I avoid my loop to take the previous answer of the user?

I am making a program that will take a user's input on how many numbers he wants and determine the highest number between the given. After that the user will be prompt with a Yes or no question. If the user decides to say yes, the program will loop again and if not, the program will end. Now my question is why does it take the highest number from the previous run?
import java.util.Scanner;
public class IT_VILLAFLOR_Lab1_Prog2
{
public static void main(String[] Args){
int num=1,num2,Largest=0,max;
char YN;
Scanner sc = new Scanner(System.in);
System.out.print("Enter the Max Number = ");
max = sc.nextInt();
for(num=1; num<=max; num++)
{
System.out.print("Enter Number " + num + ": ");
num2 = sc.nextInt();
if(Largest<num2)
{
Largest=num2;
}
else if(num==max)
{
System.out.println("The Biggest number is " + Largest );
System.out.print( "Do you want to try again? Y/N ");
YN = sc.next().charAt(0);
if(YN =='Y'|| YN =='y')
{
num=0;
System.out.print('\f');
System.out.print("Enter the Max Number " );
max = sc.nextInt();
}
else
{
System.exit(0);
}
}
}
}
}
If the user wants to continue, you are resetting num to 0. Along with this, Largest also needs to be reset to 0.
num=0;
Largest=0; //new code
By the way, you need to change the line else if(num==max) to if(num==max) . Try the test case with max of 2 and values as 12 ,23.

Assigning a double through scanner isn't reading the first input

I'm currently writing a program for a class. The goal is to be able to have the user enter an integer, and initialize an array with that entered size. Afterwards, the program prompts the user for inputs going to each of those array slots ( grades as seen below ). We're also supposed to utilize a while loop when an input isn't valid. My issue is that when asking for the first grade, it requires two number inputs to loop through.
import java.util.Scanner;
public class ForWhile {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int arraySize;
System.out.print("Gpa Calculator");
System.out.print("\nEnter total classes: ");
arraySize = scanner.nextInt();
double[] grades = new double[arraySize];
for (int i = 0; i < arraySize; i++) {
System.out.println("Enter grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
}
}
}
This is currently what I have written, but in the console I would expect for an input of 2:
GPA Calculator
Enter grade for class 1: 90
Enter grade for class 2: 85
What needs to happen for it to progress is:
GPA Calculator
Enter a grade for class 1: 90
90
Enter a grade for class 2: 85
I've tried using scanner.hasNextLine() but not to much success, what am I missing? I also think my while loop condition isn't looping correctly, any input would be much appreciated!
You are currently checking if there is a double to read after you have read the double. This,
grades[i] = scanner.nextDouble();
while (!scanner.hasNextDouble()) {
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
grades[i] = scanner.nextDouble();
}
should be
while (!scanner.hasNextDouble()) {
scanner.nextLine(); // consume the thing that isn't a double
System.out.println("Percentage grades only please!");
System.out.println("Enter a grade for class " + (i + 1) + ": ");
}
grades[i] = scanner.nextDouble();

Input Mismatch Exceptions

I've been instructed to create a code that takes a user's first 5 inputs (doubles) and finds the average. My only problem is creating an exception if a user inputs anything other than a number. Could someone show how I can add this exception to my code?
import java.util.*;
public class Test1
{
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
System.out.println("Please enter a number: ");
double first = numbers.nextInt();
System.out.println("Please enter a number: ");
double second = numbers.nextInt();
System.out.println("Please enter a number: ");
double third = numbers.nextInt();
System.out.println("Please enter a number: ");
double fourth = numbers.nextInt();
System.out.println("Please enter a number: ");
double fifth = numbers.nextInt();
System.out.println("The average is\t" + ((first + second + third + fourth + fifth)/5)+"\t");
}
}
This will handle the user typing non Integers.
It also removes the static Scanner userInput which isn't being used.
public class HelloWorld
{
public static void main(String[] args)
{
Scanner numbers = new Scanner(System.in);
int total =0;
int numberOfQuestion = 5;
for (int i = 0; i < numberOfQuestion ; i ++) {
System.out.println("Please enter a number: ");
while (!numbers.hasNextInt()) {
System.out.println("Input was not a number, please enter a number: ");
numbers.next();
}
total = total + numbers.nextInt();
}
System.out.println("The average is\t" + (total/numberOfQuestion)+"\t");
}
}

how can i get java if statment promopt a user with error message when a number out of the range

i am newbie working on my assignment, the criteria is as follow :
- use conditional statement to check if the grade is outside the range of 0-101 and print error message.
-else if the grade is the range 0-101 then add the grade to the total and work out the average
of grades.
i have the code below, which works fine but when i input a number outside the range of 0-101
no error message comes up.
can anyone help me in what i am doing wrong, any help is appreciated.
here is my code:
import java.util.Scanner;
public class GradeCalculator {
public void readGrade() {
// 1. Creatin a Scanner using the InputStream available.
Scanner keyboard = new Scanner( System.in );
// 2. Using the Scanner to read int from the user.
// 3. returns the next double.
}
public void WorkOutGrade(){
Scanner keyboard = new Scanner(System.in);
//declaring the variables.
int testScoreA;
int testScoreB;
int testScoreC;
int testScoreD;
int testScoreE;
double sum;
double average;
//
do{
System.out.println("welcome to the grade calculator , please Enter a grade between 0-101 ");
System.out.print("And press enter key on your keyboard to type the next score, ");
System.out.println("please Enter your first test score: ");
testScoreA = keyboard.nextInt();
if (testScoreA >= 0 && testScoreA < 101 );
else if (testScoreA < 0 && testScoreA > 101 )
System.out.print("wront input ");
System.out.print("Enter your second test score: ");
testScoreB = keyboard.nextInt();
System.out.print("Enter your third test score: ");
testScoreC = keyboard.nextInt();
System.out.print("Enter your fourth test score: ");
testScoreD = keyboard.nextInt();
System.out.print("Enter your fifth test score: ");
testScoreE = keyboard.nextInt();
keyboard.nextLine();
sum =(testScoreA+testScoreB+ testScoreC+ testScoreD+ testScoreE/2);
average=sum/4;
System.out.println(" your grades are: "+" grade 1 = "+testScoreA+
" grade 2 = " +testScoreB+ " grade 3 = "+ testScoreC+ " grade 4 = "+ testScoreD+ " grade 5 = "+ testScoreE);
System.out.println("your grade average is :"+ average+".");
} while (testScoreA >= 0 && testScoreA < 101 );
if (testScoreA < 0 && testScoreA > 101 )
System.out.print("wront input ");
else System.out.println();
keyboard.close();
}
}
Here is an example, where you read 5 grades (repeating if they are not correct) and print the average:
import java.util.Scanner;
public class GradeCalculator {
//Maximum number of grades
private static final int NUM_SCORES = 5;
public void readGrade() {
Scanner keyboard = new Scanner(System.in);
// declaring the variables.
int sum = 0;
System.out.println("Welcome to the grade calculator , please Enter a grade between 0-101 ");
System.out.println("And press enter key on your keyboard to type the next score:");
for (int i = 0; i < NUM_SCORES; i++) {
int testScore;
do {
System.out.println("Please enter your test score:");
testScore = keyboard.nextInt();
//if the score is not correct: Output Error
if (testScore < 0 || testScore > 101)
System.err.println("Wront input. Inpute the test score again!");
else{
//if the score is correct, then add the score to the sum
sum += testScore;
}
//repeat if the score is not correct, to get a correct score
}while (testScore < 0 || testScore > 101);
}
//The average is the sum of the scores divided by the number of scores
System.out.println("Your grade average is :" + sum/NUM_SCORES);
keyboard.close();
}
public static void main(String[] args) {
new GradeCalculator().readGrade();
}
}
You should use an or instead of an and for your error condition:
So instead of:
else if (testScoreA < 0 && testScoreA > 101 )
You should use:
else if (testScoreA < 0 || testScoreA > 101 )
With your first line, you are checking for a number that is smaller than 0 and bigger than 101. As far as I know, that is impossible.
So if you use an or (||) you will check if the number is smaller than 0 or bigger than 101

array display method difficulty

newbie here. So i'm testing out arrays, it's the next topic in the tutorial that i have been reading. I made a simple program to specify how many numbers to get or to input. The problem is on the getArray() method, i can't seem to display it. It's giving me an exception in thread error. Any help and advice is much appreciated. :) Sorry for the newbie question. :))
So here's the code.
import java.util.Scanner;
public class ArrayNumbers {
Scanner input = new Scanner(System.in);
int totalNum, counter, count = 0, display;
double arrayNum[];
public void setArrayNum() {
System.out.print("How many numbers?: ");
totalNum = input.nextInt();
double arrayNum[] = new double[totalNum];
for (counter = 0 ; counter < arrayNum.length ; counter++) {
System.out.print("Num "+(count = counter + 1)+": ");
arrayNum[counter] = input.nextInt();
}
}
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
}
import java.util.Scanner;
public class MainProgram {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Numbers NumbersObject = new Numbers();
ArrayNumbers ArrayNumbersObject = new ArrayNumbers();
String name;
int choice;
System.out.print("Enter name: ");
name = input.nextLine();
System.out.println("Menu");
System.out.println("1. Math Operations");
System.out.println("2. Grade Computation");
System.out.println("3. Counting Numbers");
System.out.println("4. Array Numbers");
System.out.print("Enter choice: ");
choice = input.nextInt();
switch(choice) {
case 1:
System.out.println("Choose Operation");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter choice: ");
choice = input.nextInt();
NumbersObject.setNum();
if (choice == 1)
System.out.println("The answers is "+(NumbersObject.getNum1() + NumbersObject.getNum2()));
else if (choice == 2)
System.out.println("The answers is "+(NumbersObject.getNum1() - NumbersObject.getNum2()));
else if (choice == 3)
System.out.println("The answers is "+(NumbersObject.getNum1() * NumbersObject.getNum2()));
else if (choice == 4)
System.out.println("The answers is "+(NumbersObject.getNum1() / NumbersObject.getNum2()));
else
System.out.print("Invalid Input!");
break;
case 2:
NumbersObject.setNum();
System.out.println("Your average grade is "+((NumbersObject.getNum2() + NumbersObject.getNum2()) / 2));
break;
case 3:
System.out.println("Welcome to Counting Numbers!");
System.out.println("Enter 2 numbers to start and end!");
NumbersObject.setNum();
for (int counter = (int) NumbersObject.getNum1() ; counter <= NumbersObject.getNum2() ; counter++) {
System.out.println(counter);
}
System.out.println("End!");
break;
case 4:
ArrayNumbersObject.setArrayNum();
ArrayNumbersObject.getArray();
break;
default:
System.out.println("Mr/Ms "+name+" you entered an Invalid Choice!");
break;
}//end of switch
}// end of main
}// end of class
Sorry about that, for not including the main.
And here's the error:
Exception in thread "main" java.lang.NullPointerException
at ArrayNumbers.getArray(ArrayNumbers.java:23)
at MainProgram.main(MainProgram.java:67)
Guys, the only i problem i have is in the getArray()
It asks for what number in the array i want to see but when i input it, it gives an exception in the thread error. The only problem is how am i going to display the array[number i specified]? Sorry for the newbie questions.
It throws an exception because you create an array of size display and you try to print the element at the display position but arrays are 0 base indexed in Java.
This figure should be useful :
So imagine that display = 10 :
double arrayNum[] = new double[display]; //create an array that can holds 10 elements
System.out.print(arrayNum[display]); //try to access at the 10th element of the array but it doesn't exists !
You don't have to create a new array because you want to display the number in the arrayNum you created in your class.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
System.out.print(arrayNum[display]);
}
Also you need to check if display is in the correct bounds range [0,...,displayNum.length-1] before trying to access its elements.
Edit :
In setArrayNum() replace double arrayNum[] = new double[totalNum]; by arrayNum = new double[totalNum];
Arrays are 0-based. So if you create an array of size display you can access indexes 0..display-1
You are creating local array double arrayNum[] = new double[display]; within getArray() method.
You need to remove double arrayNum[] = new double[display]; from getArray() method.
After that your method like below.
public void getArray() {
System.out.print("What number to display?: ");
display = input.nextInt();
if(display >0 && display <=arrayNum.length){
System.out.print(arrayNum[display-1]);
}else{
System.out.print(display + " is out of range");
}
}

Categories

Resources