java code not working as I am expecting - java

I am really struggling on getting my java code to work. I have coded a program which determines what grade each score will get once entered in by the user and also finds the largest and smallest score. The program successfully figures out which score belongs in which grade but once I implement the piece of code which tries to find the largest number out of the scores it doesn't seem to work and I'm not sure what it is!
here is the code...
import java.util.Scanner;
public class Grade
{
public static void main(String[] args)
{
int Agrade=0; //different variables used throughout the code
int Bgrade=0;
int Cgrade=0;
int Dgrade=0;
int Fgrade=0;
int count=0;
Scanner in = new Scanner(System.in); //name of Scanner
System.out.println("Please enter the exam grades one after the other ");
System.out.println("Please enter a negative number at the end of the grade list to control the flow and then press enter :");
int score = in.nextInt(); //stores numbers inputted
System.out.println("Please enter the grades again for the largest number: ");
double largest = in.nextDouble();
while (in.hasNextDouble()){
double input = in.nextDouble();
if (input > largest) {
largest = input;
}
}
while(score>0) //start while loop
{
count++;
if(score>=70 && score<=100)
Agrade++;
else if(score>=60 && score<=69)
Bgrade++;
else if(score>=50 && score<=59)
Cgrade++;
else if(score>=40 && score<=49)
Dgrade++;
else if(score>=0 && score<=39)
Fgrade++;
score = in.nextInt();
} //end while
System.out.println("Total number of grades :"+ count);
System.out.println("The largest number :"+ largest);
System.out.println("The number of As :"+ Agrade);
System.out.println("The number of Bs :"+ Bgrade);
System.out.println("The number of Cs :"+ Cgrade);
System.out.println("The number of Ds :"+ Dgrade);
System.out.println("The number of Fs :"+ Fgrade);
} // end main
} // end class
Thank you!

That's probably an exercise so will give just the idea.
Your while loop seems to be fine, just declare two variables before it.
one for holding the max grade initialized with lowest number and another for min grade with highest number.
score = in.nextInt(); do
if ( score > highest ) { highest = score;}
if ( score < lowest ) { lowest = score }
good luck.

The problem is likely that you are declaring the variable input every time the while loop runs. Instead, declare the variable like this:
double input;
and do it before the while loop. Then in the while loop replace that line with:
input = in.nextDouble();
If this isn't the problem, it might be how you've laid out the code. The second while loop, which begins with while (score>0) should be where you have the line int score = in.nextInt() Putting this after the first while loop means that it's executed after that while loop.
As a side note, common variables like Agrade should be written in camelCase, in which the first letter is lowercase and the letter of the next word is uppercase. This would make your variables
int aGrade = 0;
int bGrade = 0;
and so on. This is just proper form and shouldn't effect your program. Also, you should probably declare score and input at the top of your program since you use them in loops. This is also good form and organization. It would look like this:
int score;
double input;

Check comments on code to understanding.
MainClass:
import java.util.Scanner;
public class Grade
{
public static void main ( String [ ] args )
{
/**
* This gradesCount represent the A,B,C,D,E,F counts
*/
int[] gradesCount = {0,0,0,0,0,0};
double inputScore = 0;
double bestScore = 0;
int total = 0;
#SuppressWarnings ( "resource" )
Scanner in = new Scanner(System.in);
System.out.println ( "If you want to end, enter a negative number" );
System.out.print("Enter score: ");
do
{
inputScore = in.nextDouble ( );
//validation for the first iteration
if(inputScore < 0 || inputScore > 100) break;
System.out.print("Enter score: ");
//Add to corresponding grade count
if(inputScore>=70 && inputScore<=100) gradesCount[0]++;
if(inputScore>=60 && inputScore<=69) gradesCount[1]++;
if(inputScore>=50 && inputScore<=59) gradesCount[2]++;
if(inputScore>=40 && inputScore<=49) gradesCount[3]++;
if(inputScore>=0 && inputScore<=39) gradesCount[4]++;
//Add one to total
total++;
//check best score
if(inputScore > bestScore) bestScore = inputScore;
}//This pattern check if its number between 0-100
while ( in.hasNext ( "[0-9][0-9]?|100" ) );
System.out.println ( "Negative number or not valid input. Exited." );
System.out.println("Total number of grades :"+ total);
System.out.println("The best score :"+ bestScore);
System.out.println("The number of As :"+ gradesCount[0]);
System.out.println("The number of Bs :"+ gradesCount[1]);
System.out.println("The number of Cs :"+ gradesCount[2]);
System.out.println("The number of Ds :"+ gradesCount[3]);
System.out.println("The number of Fs :"+ gradesCount[4]);
}
}
Input/Output:
If you want to end, enter a negative number
Enter score: 5
Enter score: 10
Enter score: 15
Enter score: 20
Enter score: 33
Enter score: 99
Enter score: 100
Enter score: 44
Enter score: -3
Negative number or not valid input. Exited.
Total number of grades :8
The best score :100.0
The number of As :2
The number of Bs :0
The number of Cs :0
The number of Ds :1
The number of Fs :5
Documentation:
Scanner
The while and do-while statements (used for iteration)
Pattern (used in do-while)

Related

java loop array using do...while

This program should take a user defined number, create an array of that size and let the user input the elements - which are grades - using a do..while loop. The program then needs to display all grades entered from lowest to highest, accumulate the grades, and find the average.
My output isn't displaying the entered grades correctly (if I enter 10,20,30, it displays 00,10,20) and I can't figure out what I'm doing wrong. Any help, please?
import java.util.Arrays;
import java.util.Scanner;
public class LoopArray
{
public static void main(String[] arg)
{
Scanner keyboard = new Scanner(System.in);
int count = 0;
double totalAverage = 0;
double gradesTotal = 0;
System.out.println("Please input the number of grades you would like to submit for an average: ");
int numberOfGrades = keyboard.nextInt();
int[] studentScores = new int[numberOfGrades];
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Arrays.sort(studentScores);
for(count=0; count < studentScores.length; count++)
{
System.out.println("Grades entered were: " + count + studentScores[count]);
}
totalAverage = gradesTotal / numberOfGrades;
System.out.println("The total of all grades entered is: " + gradesTotal);
System.out.println("The average of grades entered is: " + totalAverage);
}
}
Result
Grades entered were: 00
Grades entered were: 10
Grades entered were: 20
is generated with
System.out.println("Grades entered were: " + count + studentScores[count]);
So last number in each line is pair representing count + studentScores[count]. This means that:
00 -> at position 0 array studentScores stores 0.
10 -> at position 1 array studentScores stores 0
20 -> at position 2 array studentScores stores 0
Which means you didn't fill your studentScores array with values from user.
You are not putting any value inside the array. You need to add this to your do part of the loop studentScores[count] = inputGrade;
Now your do while loop should look like this:
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count] = inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);
Also, inside your last for-loop, you are printing extra info. Just remove that count from System.out.println
System.out.println("Grades entered were: " + studentScores[count]);
Anything you don't understand let me know thanks
Because count start from 0. You should check it.
you forgot to populate the array using the gardes entered
do
{
System.out.println("Please enter grade for averaging: ");
int inputGrade = keyboard.nextInt();
studentScores[count]=inputGrade;
count++;
gradesTotal += inputGrade;
} while (count < numberOfGrades);

getting number from the same line

I was wondering how you can the scanner can pick up all the different numbers on the same line. my assignment has requires us to compute grade averages and he wants it to be like:
Enter the number of grades: 5
Enter 5 grades: 95.6 98.25 89.5 90.75 91.56
The average of the grades is 93.13
I think for the scanner to get those number it requires an array? but we haven't learned those. Any help would be awesome! So far I have:
// number of grades input
do {
System.out.println("Enter number of grades");
// read user input and assign it to variable
if (input.hasNextInt()) {
numGrade = input.nextInt();
// if user enters a negative grade will loop again
if (numGrade <= 0) {
System.out.println("Your number of grades needs to positive! Try again");
continue;
// if grade number > 0 set loop to false and continue
} else {
cont = false;
}
// if user does not enter a number will loop again
} else {
System.out.println("You did not enter a number! Try again");
// get the next input
input.next();
continue;
}
// only not loop when boolean is false
} while (cont);
// user input of grades
do {
// prompt user to enter the grades
System.out.println("Enter the " + numGrade + " grades");
// assign to input
if (input.hasNextDouble()) {
grades = input.nextDouble();
// check if a grade is a negative number
if (grades <= 0) {
// report error to user and loop
System.out.println("Your grades needs to positive! Try again");
continue;
// if user enter acceptable grades then break loop
} else {
cont2 = false;
}
// check if user entered a number
} else {
// if user did not enter number report error
System.out.println("You did not enter a number! Try again");
input.next();
continue;
}
// only not loop when boolean2 is false
} while (cont2);
// average calculation
average = grades / numGrade;
System.out.println(average);
}
I would suggest this
// separates the line you send by spaces if you send the next line
// 95.6 98.25 89.5 90.75 91.56 it will create an array like this
// {"95.6","98.25", "89.5","90.75", "91.56"}
String []grades = input.nextLine().split(' ');
double total=0;
for(int i=0;i<grades.length;i++){
//parse each value to double and adds it to total
total+=Double.parseDouble(grades[i]);
}
double average= total/grades.length;
I think in your assignment the separate spaces means that you should have each number stored in a specific location or variable.
For example:
Enter three number : 1 2 3
int number1 = input.nextInt();
int number2 = input.nextInt();
int number3 = input.nextInt();
now Scanner will read by nextInt() method. if it read space then will finished saving value in that variable.
Another Example that read array elements:
Enter three number: 1 2 3
int[] myArray = new int[3];
for(int i = 0; i < myArray.length; i++){
myArray[i] = input.nextInt();
}
Note that the loop will run 3 times as the length of the array.
Also note in the code that input reference for Scanner class but I didn't declare it.

Java program how to read multiple Doubles in one line?

Alright,so I've got this assignment that requires me to have a method with a variable number of inputs as well as a string input. The inputs all have to be on one line in the scanner, and the method has to return the number of values entered,the average value,the max value,the min value,and the string that was entered.
This is an example of that the terminal window should look like.
Please enter the name of the course: CourseNameHere
Please enter the scores for CSC 201 on a single line and type a -1 at the end
71 02 81 44 84 17 38 11 20 05 93 -1
The course name : CourseNameHere
Number of Scores : 11
The Average Score : 42.37
The Minimum Score : 02
The Maximum Score : 93
The Average score has to be rounded to 2 decimal places(which I think I can handle) The only problem for me is getting the variable number of inputs to be scanned on a single line,and how to have the program count the number of inputs if I'm not hitting enter between the inputs. This is what I have so far.but I have no idea where to go from here. I can get it to ask for sequential values,but they aren't all on the same line
I would also like to know what i would put as my return in the method? im new to java please help
this is my program that calculates the code without reading it with one line but reading them in separate lines all i need is how to read them in the same line:
System.out.println("Please enter the number of courses that you would like to\n" + "calculate the Average Score, the Minimum Score and\n" +"the Maximum Score: "); // prompt the user to enter the number of courses for which the average, min and max neeed to be calculated.
//create a scanner object to read from the keyboard
Scanner input = new Scanner(System.in); //declares a new scanner called input to take input from keyboard
int count = input.nextInt(); // read the user input and store it in the count variable
input.nextLine(); //read the end of the line and throw it away
for (int i = 0; i < count; i++)
{
System.out.println("Please enter the name of the course: "); // prompt user to enter course name
String courseName = input.nextLine(); // stores user input from keyboard into variable courseName
System.out.print("Please enter a score for "+ courseName + " or type -1 to indicate\n" + "that there is no more score for this course: "); // prompt the user to enter a grade in the class
double score = input.nextDouble(); // stores user input for score into variable double
int numberOfScores = 0; // declare integer variable called numberofscored and set value to 0
double total = 0; // declare a double variable called total and set value to 0
double min = 100; // declare double variable called min and set value to 100
double max = 0 ; // declare double called max and set value to 0
while (score!=-1) // start while loop for when score does not equal -1
{
if ( score < min) // start of if statement
{ min = score;
} //end of if //start of if statement
if ( score > max)
{ max = score;
} // end of if statement
total = total + score; // sets the value of variable total equal to itself + score
numberOfScores++; // adds 1 to the variable numberofscores
System.out.print("Please enter a score for "+ courseName + " or type -1 to indicate\n" + "that there is no more score for this course: "); // prompt the user to enter a grade in the class
score = input.nextDouble(); // sets the value of score to the next input double from user
}
double average = total/numberOfScores; // declare variable average and set value to total divided buy the number of scores
System.out.println("The Course Name: " + courseName); //print a messege that shows the user the course name he entered
System.out.println("Number Of Scores: " + numberOfScores); // prints a messege with the number of scores
System.out.printf(" The average score: %.2f" , average); // prints a messege with the average score with only 2 decimal places
System.out.println(); // goes to next line
System.out.printf(" The Minimum score: %.2f" , min);// prints message with minimum score with only 2 decimal places
System.out.println(); // goes to next line
System.out.printf(" The Maximum score: %.2f" , max); // prints messege with maximum score with only 2 decimal places
System.out.println();// goes to next line
input.nextLine(); //read the end of the line and throw it away
}
This code will do the work please ask me if you feel confused :
Scanner input = new Scanner(System.in);
LinkedList<Integer> list = new LinkedList<Integer>();
System.out.println("Please enter the name of the course:");
String course=input.next();
System.out.println("Please enter the scores for CSC 201 on a single line and type a -1 at the end");
int max=0;
int min=Integer.MAX_VALUE;
int sum=0;
int grade;
that: while(true){
grade=input.nextInt();
if(grade==-1)
break that;
list.add(grade);
sum=sum+grade;
if(grade>max)
max=grade;
if(grade<min)
min=grade;
}
System.out.println("The course name: "+ course);
System.out.println("Number of Scores :"+list.size());
System.out.println("The Average Score :"+(double)sum/list.size());
System.out.println("The Minimum Score: "+min);
System.out.println("The Maximum Score :"+max);
PS : Integer.MAX_VALUE is a huge value maybe 100 is good if the limit of the grade is 100.
why using linked list ?
because it's easy to store the values one by one .
I can reach all elements when ever i want.
also the method size of this list is the number of elements it has so I don't need a counter to count how many grades i have .
also you can print them after that if you want because all grades now are stored in this list.
if you don't need these grades in something next , you can ignore the list and do it without it .
Good luck .

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

How do you get your program to repeat if input is invalid instead of continuing with invalid input?

I am trying to validate a user input, cuPerTerm > 12
I get the error message but the program continues and uses the invalid input to run
package gradplanner;
import java.util.Scanner;
public class GradPlanner {
int cuToComp;
int cuPerTerm;
public static void main(String[] args) {
final double COST = 2890.00; //flat-rate tuition rate charged per term
final int MONPERTERM = 6; //number of months per term
int cuToCompTotal = 0;
int numTerm;
int numMonToComp;
double tuition;
//prompt for user to input the number of CUs for each individual course remaining.
Scanner in = new Scanner(System.in);
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
//add all CUs from individual courses to find the Total number of CUs left to complete.
while (cuToComp > 0)
{
cuToCompTotal += cuToComp;
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
cuToComp = in.nextInt();
}
System.out.println("The total number of CUs left is " + cuToCompTotal);
//prompt for user to input how many CUs they plan to take per term.
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm <12) //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
{
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
}
//Calculate the number of terms remaining, if a remain is present increase number of terms by 1.
numTerm = cuToCompTotal/cuPerTerm;
if (cuToCompTotal%cuPerTerm > 0)
{
numTerm = numTerm + 1;
}
System.out.println("The Number of Terms you have left is " + numTerm + " Terms. ");
//Calculate the number of Months left to complete
numMonToComp = numTerm * MONPERTERM;
System.out.println("Which is " + numMonToComp + " Months. ");
//calculate the tuition cost based on the number of terms left to complete.
tuition = numTerm * COST;
System.out.println("Your Total Tuition Cost is: " + "$" + tuition +" . ");
}
}
I need it to continue to re-ask until 12 or something greater is entered. and then continue the program.
You should use a while loop so that you continue looping until cuPerTerm is at least 12. Remember to take the user input again with cuPerTerm = in.nextInt(); inside the while loop.
Here's a simple solution:
int cuPerTerm = -1; // intialize to an invalid value
while (cuPerTerm < 12) {
System.out.print("How many credit units do you intend to take per term? ");
int cuPerTerm = in.nextInt();
if (cuPerTerm <12) { //validate input - Undergraduate Students Must enroll in a minimum of 12 CUs per term
System.out.print("Undergraduate Students must enroll in a Minimum of 12 CUs per Term. ");
}
}
Add this to continue getting input till it satisfies your condition:
while(cuPerTerm <= 12){
//Ask use to provide input
}
It is simple while loop which checks your input condition and continues taking input till it is satisfied.
Edit: -
Initialize your cuPerTerm =0
while(cuPerTerm <= 12)
{
System.out.print("Please enter the number of CUs for each individual course you have remaining, Entering a - number when finished. ");
int cuToComp = in.nextInt();
}
There are pitfalls: Simple doing scanner.nextInt() will give you the next Integer of the CURRENT Line.
If the user types in test, nextInt() will throw an InputMismatchException, you have to handle. Also the int will NOT be consumed
So you have to call scanner.nextLine() in between to Clean the current (mismatched) result.
All together something like this:
do{
try
{
System.out.print("Enter number > 12: ");
System.out.flush();
number = scanner.nextInt();
if (number > 12)
done = true;
}
catch(InputMismatchException e) {
System.out.println("This is not a number");
scanner.nextLine() //!Important!
}
}while(!done);
I think that a do-while loop will best suit your needs:
int val;
do {
val = in.nextInt();
} while (val < 12);

Categories

Resources