Java finding the minimum value from Scanner input always resulting in zero - java

This is my first Java program. It is supposed to allow a user to enter int grades between 0 and 100. If the user enters a negative value, data entry ceases and statistics are displayed. I cannot incorporate static methods, math, or arrays.
I am having an issue with finding the minimum grade, minGrade. Regardless of what values are entered when the program is running, minGrade always results in zero. I have been tinkering with this for a while now to no avail.
The other issue I am having is that when I run the program, and I enter a bunch of int, but then enter some alphabet letters to test the error-checking, the program parses the user twice, instead of once.
"Please enter a numeric grade between 0 and 100, inclusive, and press Enter:"
The respective code is:
import java.util.Scanner;
public class Grades {
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter the Course Code and and press Enter:");
String courseCode = keyboard.nextLine();
System.out.println("You entered: " + courseCode + "\n");
int grade = 0;
int numberOfGrades = 0;
int maxGrade = 0;
int minGrade =0;
double avgGrade = 0;
int sumGrades = 0;
int sentinel = 0;
do
{
**System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");**
while(!keyboard.hasNextInt())
{
System.out.println("Please enter a numeric grade between 0 and 100, inclusive, and press Enter:");
keyboard.nextLine();
}
grade = keyboard.nextInt();
if((grade <=100) && (grade >= 0))
{
numberOfGrades++;
sumGrades += grade;
sentinel = 0;
if(maxGrade < grade)
maxGrade = grade;
**if(minGrade > grade)
minGrade= grade;**
}
else if(grade > 100)
{
System.out.println("The entered number was greater than 100. Please enter a number between 0 and 100 inclusive, "
+ "or input a negative number to exit Grade entry");
sentinel = 0;
}
else if(grade <0)
{
grade = 0;//maybe?
sentinel = -1;
}
}
while((grade >100) || (sentinel == 0));
avgGrade = (sumGrades/numberOfGrades);
System.out.println("You entered: " + "\ngrade: " + grade + "\n" + "sentinel: "+ sentinel +
"\nSum of Grades: " + sumGrades +"\nNumber of Grades: "+ numberOfGrades +"\nAverage Grades: " + avgGrade
+ "\nMaxium Grade: "+ maxGrade+"\nMinimum Grade: "+minGrade);
}
}
Any input on this, the form of my code for my first java program, or anything else would be greatly appreciated.
The last issue I am having is that the average grade always has a tenth place of zero. How can I get the tenth place to not be zero and the actual average amount?

Your problem with minGrade is that you initialize it to 0. This is already the min value, hence no other values will be less than this. (You in fact ensure this even more so by setting negative grades to 0.) Initialize it to the max value (100).
It looks like your "double prompt" issue is a common one with nextLine and nextInt. The solution seems to be using only nextLine and then parsing the return value of that for an Integer object. (And printing out your "invalid input" text on a NumberFormatException.
Finally, your avgGrade is always xx.0 as you are dividing two integers, which always gives an integer back. You need to cast one to a double to get a double back:
avgGrade = ((double)sumGrades/numberOfGrades);

minGrade will never be set to anything other than 0 because 0 will never be greater than the grade entered, so this check fails if(minGrade > grade). Try initializing minGrade to Integer.MAX_VALUE.

Related

Not obtaining desired output

Basically, I have ask the user to input two exam scores (which are doubles). If the two exam scores average out to more than 90, then a message is outputted on the screen that they got an A, and so on for other average scores.
No matter what combination I enter, it always outputs that the user has obtained a 'C' grade even though they did not.
What is the issue here?
There were no compiler errors.
package test;
import java.util.Scanner;
class test3 {
public static void main(String args[]) {
Scanner zino = new Scanner(System.in);
double score1 = 0;
double score2 = 0;
double average = 0;
average = (score1 + score2) / 2 ;
System.out.println("Enter score 1 ");
score1 = zino.nextDouble();
System.out.println("Enter score 2 ");
score2 = zino.nextDouble();
if(average > 90)
{
System.out.println(average);
System.out.println("You got an A!");
}
else if(average > 80)
{
System.out.println(average);
System.out.println("You got a B.");
}
else
{
System.out.println(average);
System.out.println("You got a C.");
}`
}
}
If the user inputs two scores that are both 100, the output should be:
100
You got an A!
This is what I am getting:
0.0
You got a C.
Place the code average=(score1+score 3)/2; after you finished getting user inputs.
Your code should looks like this :
System.out.println("Enter score 1 ");
score1 = zino.nextDouble();
System.out.println("Enter score 2 ");
score2 = zino.nextDouble();
average=(score1+score 3)/2;
Your problem is that you're calculating the average before you're reading the values of the two scores.
average = (score1 + score2) / 2 ;
When you run this line, score1 and score2 are both zero, so you're setting average to ( 0 + 0 ) / 2, which of course is zero.
Later in your program, you have
score1 = zino.nextDouble();
...
score2 = zino.nextDouble();
which sets score1 and score2 to the values entered by the user. But you never calculate average again - so it stays at zero.
What you need to do is move the line average = (score1 + score2) / 2; downwards, so that it runs after the two lines that set score1 and score2.

What code can I use for min, max and average for java programming without arrays?

I'm doing a project for my programming class and I'm stuck. I've written the code but I can't figure out how to implement the min, max and average into the class. We haven't learned about arrays yet and I just need a good nudge in the right direction. Please help!
The exercise reads: Write an application that allows a user to enter any number of student test scores until the user enters 999. If the score entered is less than 0 or more than 100, display an appropriate message and do not use the score. After all the scores have been entered, display the number of scores entered, the highest score, the lowest score, and the arithmetic average.
import java.util.Scanner;
public class TestScoreStatistics {
public static void main(String[] args)
{
double score;
double max;
double min;
double average;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter in test scores: ");
score = keyboard.nextDouble();
while(score >= 0 || score <= 100) {
if(score >= 101 || score <= 0.9)
System.out.println("The score must be between 0 - 100");
else
System.out.println("Please enter in test scores or type 999 to calculate final scores: ");
score = keyboard.nextDouble();
if(score == 999)
System.out.println("The maximum score is - " + max + ".");
System.out.println("The minimum score is - " + min + ".");
System.out.println("The average score is - " + average + ".");
}
}
}
I'm not looking for the direct answer, I just want confirmation that I'm using the right type of loop and what code should I use for the math part. Thank you in advance.
To calculate an average, you just need two variables, one for the sum of all the scores, and one for the number of scores. That shouldn't require arrays. Also, the min and max score values can be updated each time a score is input.

Java keeping highest number

int number = 0;
int score = 0;
while (true) {
Scanner input=new Scanner(System.in);
System.out.println("Please enter mark :");
number = input.nextInt();
Scanner mark=new Scanner(System.in);
score = mark.nextInt();
if (number > score ) {
System.out.println("Highest mark:" + number);
}
else if (number > 100) {
System.out.println("Invalid enter number 0-100");
}
else if
(number < 0){
System.out.println("Invalid enter number 0-100");
if(input.equals("quit")){
break;
Greetings, I would like to know how to keep the highest mark and the lowest mark after the student enters the number. and only to allow to enter numbers between 0-100. Thank you
You'll need two variables to keep track of the highest and lowest marks. Since you want your marks to be between 0 and 100, you can give starting values of the two variables -1 and 101 respectively:
int max = -1;
int min = 101;
-1 is not a reachable value and is lower than all the reachable values so any value in the given range is bigger than it which makes it perfect for a starting value for the max variable. If it starts from 101, no value in the range is bigger so the variable won't change. If the variable is 50 for exmaple, the values in the range 0-50 aren't bigger than 50 and they will be missed. The same logic can be done to see why I chose the value of 101 for the min variable.
Now you can enter marks and keep track of the highest and lowest one:
Scanner sc = new Scanner(system.in);
while (true) {
int mark = sc.nextInt();
if (mark > max) {
max = mark;
}
if (mark < min) {
min = mark;
}
}
Now the highest and lowest marks will be kept in the max and min variables respectively.
To implement the exit logic you can have the user to input a value outside the range and this will exit from the loop:
if (mark < 0 || mark > 100) {
break;
}
This if statement has to be put before the checking for highest and lowest mark because you don't mant to keep trak of such values.
This is the final code:
int max = -1;
int min = 101;
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a value between 0 and 100. If the number is outside this range, the entering will stop.");
int mark = sc.nextInt();
//Exit logic
if (mark < 0 || mark > 100) {
//Closing the Scanner object (Not necessary but recommended)
sc.close();
break;
}
//Comapring
if (mark > max) {
max = mark;
}
if (mark < min) {
min = mark;
}
}
To update the score you just need to update your score.
if (number > score ) {
score = number; //update your score
System.out.println("Highest mark:" + number);
}
You should be able to solve this yourself tho.

getting the average of values that the user has entered issues with code/logic

this is my task: Prompt the user to enter as many values as they want. The user should enter the sentinel value 99999 to indicate that they are done entering input. Display the average of only the positive values. Completely ignore any negative values when computing the average. Also ignore the 99999 value.
the output I am trying to get is :
Enter a series of values (enter 99999 to quit):
93 ­4 18 19 ­2 41 17 99999
The average of the positive values is 37.6
my code so far:
I think I need a loop, but not sure what kind of loop and how to implement it. any ideas?
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter a series of values (type 99999 to quit)");
int number = in.nextInt();
int valuesIn = number++;
double average = number/ valuesIn;
if(number == 99999)
{
System.exit(-1);
}
else
{
System.out.println(average);
}
}
}
You can simply implement a do-while loop:
Scanner in = new Scanner(System.in);
int number, valuesIn;
double average = 0;
do {
number = in.nextInt();
if(number > 0 && number != 99999) {
valuesIn++;
average += number;
}
} while(number != 99999)
average /= valuesIn;

Java how to compute average scores using loops

I need to write a program in Java that computes the average score for 4 students. The student will put in their 4 scores, and once they are done they will input -1 to compute the average. Once this is done the program needs to move onto student 2 and so on. At the end it is supposed to display the highest average from the 4 student average test scores. Here is what it should look like when it is run:
Student 1
Enter your score: 100
Enter your score: 90
Enter your score: 80
Enter your score: 70
Enter your score: -1 * once the student enters -1 it should compute average
Average Score = 85.
Student 2
Enter your score: 90
ETC
ETC
The problem with my code is that the average is only correct for the first student. When I input -1 to get the average for the second student, the calculation is incorrect. We are only allowed to use loops. The only hints I was given were that we are supposed to write an outer loop that iterates 4 times, write an inner loop that loops as long as the student has scores to enter, inside the inner loop prompt the user to enter their last score or -1 to compute average. I don't want you guys to do the project for me but to just set me in the right direction. I feel like I am not using the right loop.
import java.util.Scanner;
public class TestScore
{
public static void main(String[]args)
{
double score = 0;
double totalScore = 0;
double count = 0;
double average = 0;
Scanner input = new Scanner(System.in);
System.out.println("Student 1");
System.out.printf("Enter Your Score: ");
score = input.nextDouble();
while (score != -1){
System.out.printf("Enter Your Score: ");
totalScore = totalScore + score;
score = input.nextDouble();
count++;
average = totalScore / count;
if (score == -1){
System.out.printf("Average Score = %.2f\n ",average);
count = 0;
score = 0;
totalScore = 0;
average = 0;
System.out.println("Student 2");
System.out.printf("Enter Your Score: ");
score = input.nextDouble ();
count++;
average = totalScore / count;
}
}
}
}
You haven't explicitly asked a question so I'll try and comply to the "set me in the right direction" part.
I'd suggest re-formatting the loop structure to a cleaner one, like this:
double total;
for(int student = 1; student <= 4; student++) {
System.out.printf("Student %d\n", student);
double sum = 0, count = 0;
while(true) {
System.out.printf("Enter your score: ");
double input = scanner.nextDouble();
if(input == -1) break;
sum += input;
count++;
}
total += sum;
System.out.printf("Average: %.2f\n", sum / count);
}
System.out.printf("Total: %.2f\n", total);
Hope that's enough to give you some pointers.
edit: forgot to take care of total
So, you wish to iteratively go through all the input and just remember the maximum one. Make an integer variable max and after each student, just change it if needed. (It's zero by default jn Java)
As for the calculation for each student, you shouldn't be checking for the failed " score != - 1" condition in each iteration. Instead, you should do the final calculations after the while loop. (average, possible update of the maximum, resetting the variables, etc. )
You also need the outer loop (in the stated code, these calculations are done for one student only) which you would control in a different manner.
Also, if you need to use only 4 grades, you might want to consider using the for loop.
You can try with this :D
public static void main (String[] args) throws java.lang.Exception
{
double average = 0;
double i = 0;
int student = 0;
boolean flag = true;
Scanner input = new Scanner(System.in);
while(flag)
{
System.out.printf("Student: ");
System.out.println(student);
System.out.print("Enter Your Score: ");
double score = input.nextDouble();
if(score!=-1){
average=average+score;
i=i+1;
}
if(score==-1){
System.out.printf("Average: ");
System.out.println(average/i);
//reset values
average = 0;
i = 0;
student=student+1;
}
if(score==-2){
//you need break the while in some moment.
flag = false;
}
}
}

Categories