I'm a new Java student(self studying at home), and I made this average calculator which works perfect, but I wanted to add a condition that prevents the user from typing in a number bigger then 100, because grades usually end at 100, I'm struggling a bit on what is the right way of doing so.
Here is my code:
import java.util.Scanner;
class books{
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
int total = 0;
int grade = 0;
int average;
int counter = 0;
System.out.println("Please enter all your grades:");
while(counter < 12){
grade = userInput.nextInt();
total = total + grade;
counter++;
if(grade > 100){
System.out.println("Please enter a valid grade");
}
}
average = total/12;
System.out.println("You average is " + average);
}
}
Thanks.
Before using the entered grade value, you should validate it and if it's not valid, to continue with the loop:
while(counter < 12){
grade = userInput.nextInt();
if (grade > 100) {
System.out.println("Please enter a valid grade");
} else {
total = total + grade;
counter++;
}
}
Also, when calculating the average of multiple values, it's not that good idea to do integer division, because you can get wrong results. Better do:
double average = 0d;
...
average = total / 12.0;
The solution is:
import java.util.Scanner;
class books{
public static void main(String args[]){
Scanner userInput = new Scanner(System.in);
int total = 0;
int grade = 0;
int average;
int counter = 0;
System.out.println("Please enter all your grades:");
while(counter < 12){
grade = userInput.nextInt();
if(grade > 100 || grade < 0){
System.out.println("Please enter a valid grade again!");
}else{
total = total + grade;
counter++;
}
}
average = total/12;
System.out.println("You average is " + average);
}
}
Credit goes to Kocko ;)
Related
I am new to java and having issues with my first project. I can't seem to get the variables in the correct scope and am unsure about the scanner methods. If anyone can help me with making it work it would be very helpful, thank you!
Create a new program called LetterGrade. Prompt the user to enter their name.
Create a method called calculateAvg(). Method should use a cumulative sum algorithm to prompt the user to enter 3 scores and calculate the average. Then, return that value to main.
Once the average is returned, Print the student's name and their average using printf() command. Create another method called printLetter(). Method should pass a parameter (average grade).
Use if … else if … else statements to print whether the student has an ‘A’, ‘B’, ‘C’, ‘D’, or ‘F’ average grade.
Grade Scale:
90-100 - A
80-89 - B
70-79 - C
60-69 - D
0-59 - F
Here is what I have so far:
import java.util.*;
public class LetterGrade {
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
Scanner console = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
return total;
}
public static double printLetter(int total) {
double total = console.nextDouble();
if (total < 60) {
System.out.print("You're grade is an F.");
} else if (total < 70) {
System.out.print("You're grade is a D.");
} else if (total < 80) {
System.out.print("You're grade is a C.");
} else if (total < 90) {
System.out.print("You're grade is a B.");
} else if (total <= 100) {
System.out.print("You're grade is an A.");
} else {
System.out.print("You have input an invalid number.");
}
}
}
public static double calculateAverage() {
double sum = 0.0;
for (int i = 0; i < 3; i++) {
System.out.print("Please enter score #" + (i+1) + ": ");
double next = console.nextDouble();
sum += next;
}
double total = (sum / 3);
return total;
}
public class LetterGrade{
private static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("This program will calculate 3 scores to find the");
System.out.println("average score and letter grade.");
System.out.println();
System.out.println("Enter your name: ");
String name = console.nextLine();
final double total = calculateAverage();
System.out.printf("Name: %s/nAverage: %f",name, total);
printLetter(total);
}
public static double calculateAverage() {
double sum = 0.0;
double total = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
double next = console.nextDouble();
sum += next;
}
total = (sum / 3);
return total;
}
public static void printLetter(double total){
if (total < 60) {
System.out.print("You're grade is an F.");
}
else if (total < 70){
System.out.print("You're grade is a D.");
}
else if (total < 80){
System.out.print("You're grade is a C.");
}
else if (total < 90){
System.out.print("You're grade is a B.");
}
else if (total <= 100){
System.out.print("You're grade is an A.");
}
else{
System.out.print("You have input an invalid number.");
}
}
}
The immediate issue is that your for statement:
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + "? ");
double next = console.nextDouble();
sum += next;
double total = (sum / 3);
return total;
}
does, not actually "loop" since you return during the very first iteration from it.
You probably want to move the last two lines where you calculate the total outside of it.
Other than that there were a few minor typos:
import java.util.Scanner;
class LetterGrade {
private static final int NUM_SCORES = 3;
public static void main(String[] args) {
System.out.printf("This program will calculate the average from %d scores and give you a letter grade.%n%n",
NUM_SCORES);
try (Scanner scanner = new Scanner(System.in)) {
System.out.print("Enter your name: ");
String name = scanner.nextLine();
double average = calculateAverage(scanner);
System.out.printf("%nReport:%n");
System.out.printf("Name: %s%nAverage: %.2f%n", name, average);
printLetterGrade(average);
}
}
private static double calculateAverage(Scanner scanner) {
double total = 0;
for (int i = 1; i <= NUM_SCORES; i++) {
double next = getDoubleInput(scanner, String.format("Please enter score #%d: ", i), 0, 100);
total += next;
}
return total / NUM_SCORES;
}
private static void printLetterGrade(double average) {
if (average < 60) {
System.out.println("Your grade is a F.");
} else if (average < 70) {
System.out.println("Your grade is a D.");
} else if (average < 80) {
System.out.println("Your grade is a C.");
} else if (average < 90) {
System.out.println("Your grade is a B.");
} else {
System.out.println("Your grade is an A.");
}
}
private static double getDoubleInput(Scanner scanner, String prompt, double minValue, double maxValue) {
System.out.print(prompt);
double validDouble = -1;
while (scanner.hasNext()) {
if (scanner.hasNextDouble()) {
validDouble = scanner.nextDouble();
if (validDouble >= minValue && validDouble <= maxValue) {
break;
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue,
maxValue);
System.out.print(prompt);
}
} else {
System.out.printf("Error: Please enter a double between %.0f and %.0f inclusive%n", minValue, maxValue);
System.out.print(prompt);
scanner.next();
}
}
return validDouble;
}
}
Example Usage:
This program will calculate the average from 3 scores and give you a letter grade.
Enter your name: Megan
Please enter score #1: -100
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 105
Error: Please enter a double between 0 and 100 inclusive
Please enter score #1: 99
Please enter score #2: 98
Please enter score #3: 100
Report:
Name: Megan
Average: 99.00
Your grade is an A.
Try it out here.
this problem is with your foor loop which with every iteration it reset its value. you can also write much simple code as below:
public static double calculateAverage() {
double sum = 0.0;
for (int i = 1; i <= 3; i++) {
System.out.print("Please enter score #" + i + ": ");
sum += console.nextDouble();
}
return (sum / 3);
}
I'm having issues getting this to run.
I can't manage to get the return value to work properly. I'm a few weeks into this course and I'm learning a lot but this project has been a little bit of a struggle for me.
I'm collecting data, creating an average and then using that average to output the corresponding letter grade.
Any help would be appreciated.
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
calculateAvg();
double avgScore;
printLetter(double);
}
public static void calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
for (double i = 0; i >0; i++)
{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
}
}
public static void printLetter(double avgScore)
{
Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
There are several errors in your program.
I have corrected the program with comments:
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore= calculateAvg();
printLetter(avgScore); //pass variable name here not datatype
}
public static double calculateAvg() //must have return type
{
Scanner console = new Scanner(System.in);
double avgScore;
// for (double i = 0; i 0; i++)
//{
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
// avgScore = console.nextInt();
System.out.printf( "%s, your average test score is: %.1f",name,avgScore);
return avgScore;
// }
}
public static void printLetter(double avgScore)
{
//Scanner console = new Scanner(System.in);
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
OUTPUT:
Enter your full name.
manisha
Enter test score 1
12
Enter test score 2
14
Enter test score 3
15
manisha, your average test score is: 13.7With that average, your grade is: F
You made many mistakes.
In the main method you should save the calculated average into the variable and pass it to the printLetter method like this
double avgScore = calculateAvg();
printLetter(avgScore);
The calculateAvg method return type should be double so you have to declare it like this
public static double calculateAvg()
Also the for loop inside calculateAvg is wrong and unnecessary so just remove it. And assigning the scanner.nextInt() value to the avgScore will discard the properly calculated value. so the calculateAvg method should be like this
The printLetter method is correct but contains unnecessary lines like
Scanner console = new Scanner(System.in); //Could be removed
The resulting code is
import java.util.*;
public class LetterGrade
{
public static void main(String args[])
{
double avgScore = calculateAvg();
printLetter(avgScore);
}
public static double calculateAvg()
{
Scanner console = new Scanner(System.in);
double avgScore;
System.out.println("Enter your full name.");
String name = console.nextLine();
System.out.println("Enter test score 1");
double score1 = console.nextDouble();
System.out.println("Enter test score 2");
double score2 = console.nextDouble();
System.out.println("Enter test score 3");
double score3 = console.nextDouble();
avgScore = (score1 + score2 + score3) / 3;
System.out.printf( "%s, your average test score is: %.1f\n", name, avgScore);
return avgScore;
}
public static void printLetter(double avgScore)
{
char grade;
if (avgScore >= 90)
{
grade = 'A';
}
else if (avgScore >= 80)
{
grade = 'B';
}
else if (avgScore >= 70)
{
grade = 'C';
}
else if (avgScore >= 60)
{
grade = 'D';
}
else
{
grade = 'F';
}
System.out.println("With that average, your grade is: " + grade);
}
}
Checkout your main function. You have to assign the variable correctly to the return value of the calculateAvg method. Try this out:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
Also notice: double is the type of the variable, not the name. You have to give the name into the printLetter() method.
Another issue I just found is the doubled assigning of the avgScore variable which you have in your calculateAvg() method. Remove this line:
avgScore = console.nextInt();
This would force the user to again type in a value, which gets then assigned to the variable avgScore. This is not necessary.
Try to change the main method to this:
public static void main(String args[]) {
double avgScore = calculateAvg();
printLetter(avgScore);
}
There are some comments that I hope to be useful for you:
1- change the code in the main method to be like that
double avgScore = calculateAvg();
printLetter(avgScore);
2- check the use of the for loop (maybe you need a do while loop)
3- remove the scanner in "printLetter" method
4- also as #NiklasLehnfeld suggest to remove avgscore = console.nextInt();
Good afternoon, or whenever you are reading this. I am trying to figure out how I can find the minimum, highest, and average of test scores that a user enters.
I have a loop that keeps track of a sentinel value, which in my case is 999. So when the user enters 999 it quits the loop. I also have some level of data validation by checking if the user entered over 100 or under 0 as their input. However, my question is, how can I implement a way to get this code to find the values I need for my user inputs. My code is as follows:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore;
int highScore;
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
System.out.println(scoreString);
System.out.println(counter + " valid test score(s)");
}
}
While keeping your code pretty much the same, you could do it like this:
import java.util.Scanner;
public class TestScoreStatistics
{
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
int testScore;
double totalScore = 0;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int lowScore = 100; //setting the low score to the highest score possible
int highScore = 0; //setting the high score to the lowest score possible
String scoreString = "";
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT)
{
if (testScore < 0 || testScore > 100 )
{
System.out.println("Incorect input field");
}
else
{
scoreString += testScore + " ";
counter++;
//getting the new lowest score if the testScore is lower than lowScore
if(testScore < lowScore){
lowScore = testScore;
}
//getting the new highest score if the testScore is higher than highScore
if(testScore > highScore){
highScore = testScore;
}
totalScore += testScore; //adding up all the scores
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
double averageScore = totalScore / counter; //getting the average
}
This will check if the testScore is higher or lower than the highest and lowest scores. This program will also add all the scores together and divide them by the counter (which is how many tests there are) to get the average.
This is how I would do this.
// defines your prompt
private static String PROMPT = "Please enter the next number> ";
// validation in a separate method
private static int asInteger(String s)
{
try{
return Integer.parseInt(s);
}catch(Exception ex){return -1;}
}
// main method
public static void main(String[] args)
{
Scanner scn = new Scanner(System.in);
System.out.print(PROMPT);
String line = scn.nextLine();
int N = 0;
double max = 0;
double min = Integer.MAX_VALUE;
double avg = 0;
while (line.length() == 0 || asInteger(line) != -1)
{
int i = asInteger(line);
max = java.lang.Math.max(max, i);
min = java.lang.Math.min(min, i);
avg += i;
N++;
// new prompt
System.out.print(PROMPT);
line = scn.nextLine();
}
System.out.println("max : " + max);
System.out.println("min : " + min);
System.out.println("avg : " + avg/N);
}
The validation method will (in its current implementation) allow any integer number to be entered. As soon as anything is entered that can not be converted into a number, it will return -1, which triggers a break from the main loop.
The main loop simply keeps track of the current running total (to calculate the average), and the maximum and minimum it has seen so far.
Once the loop is exited, these values are simply printed to System.out.
With minimal changes of your code:
public class Answer {
public static void main(String[] args) {
Scanner scn = new Scanner(System.in);
int testScore;
final int QUIT = 999;
final String PROMPT = "Enter a test score >>> ";
int maxScore = Integer.MIN_VALUE;
int minScore = Integer.MAX_VALUE;
double totalScore = 0;
double avgScore = 0.0;
int counter = 0;
System.out.print(PROMPT);
testScore = scn.nextInt();
while (testScore != QUIT) {
if (testScore < 0 || testScore > 100) {
System.out.println("Incorect input field");
} else {
counter++;
System.out.println("The number of scores you entered is " + counter);
//test for minimum
if(testScore < minScore) minScore = testScore;
System.out.println("Current minimum score = " + minScore);
//test for maximum
if(testScore > maxScore) maxScore = testScore;
System.out.println("Current maximum score = " + maxScore);
//calculate average
totalScore += testScore;
avgScore = totalScore / counter;
System.out.println("Current average score = " + avgScore);
}
System.out.print(PROMPT);
testScore = scn.nextInt();
}
}
}
this one just is hurting my brain. http://programmingbydoing.com/a/adding-values-in-a-loop.html
Write a program that gets several integers from the user. Sum up all the integers they give you. Stop looping when they enter a 0. Display the total at the end.
what ive got so far:
Scanner keyboard = new Scanner(System.in);
System.out.println("i will add");
System.out.print("number: ");
int guess = keyboard.nextInt();
System.out.print("number: ");
int guess2 = keyboard.nextInt();
while(guess != 0 && guess2 != 0)
{
int sum = guess + guess2;
System.out.println("the total so far is " + sum);
System.out.print("number: ");
guess = keyboard.nextInt();
System.out.print("number: ");
guess2 = keyboard.nextInt();
System.out.println("the total so far is " + sum);
}
//System.out.println("the total so far is " + (guess + guess2));
}
Declare the int sum variable outside of the while loop and only have one guess = keyboard.nextInt() inside the loop. Add the user's guess to the sum in the loop as well.
Then after the loop output the user's sum.
I.e.:
int sum;
while(guess != 0)
{
guess = keyboard.nextInt();
sum += guess;
}
System.out.println("Total: " + sum");
Edit: also remove the guess2 variable, as you will no longer need it.
The code will be as below :
public static void main(String[] args) throws Exception {
Scanner keyboard = new Scanner(System.in);
int input = 0;
int total = 0;
System.out.println("Start entering the number");
while((input=keyboard.nextInt()) != 0)
{
total = input + total;
}
System.out.println("The program exist because 0 is entered and sum is "+total);
}
Programming by Doing :)
int x = 0;
int sum = 0;
System.out.println("I will add up the numbers you give me.");
System.out.print("Number: ");
x = keyboard.nextInt();
while (x != 0) {
sum = x + sum;
System.out.println("The total so far is " + sum + ".");
System.out.print("Number: ");
x = keyboard.nextInt();
}
System.out.println("\nThe total is " + sum + ".");
import java.util.Scanner;
public class AddingInLoop {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int number, total = 0;
System.out.print("Enter a number\n> ");
number = keyboard.nextInt();
total += number;
while (number != 0) {
System.out.print("Enter another number\n> ");
number = keyboard.nextInt();
total += number;
}
System.out.println("The total is " + total + ".");
}
}
You first prompt the user to enter a number. Then you store that number into total (total += number OR total = total + number). Then, if the number entered wasn't 0, the while loop executes. Every time the user enters a nonzero number, that number is stored in total ( the value in total is getting bigger) and the while loops asks for another number. If and when a user enters 0, the while loop breaks and the program displays the value inside total. :D I myself am a beginner and had a bit of an issue with the logic before figuring it out. Happy coding!
I'm writing a program that takes user input of five students and four test scores per student and puts them into arrays. It then averages the student's scores and gives a letter grade. The program also needs an input validation that doesn't accept scores under 0 and over 100.
So far my program validates the user and tells them that they've input an invalid number, but I would also like for it to prompt the user to start over after they've input an invalid number. I've tried a couple of different options as you will see below (in the enterData method), but none of which force the user to start over. Any suggestions?
import java.util.Scanner;
public class GradeBook {
private String[] names = new String[5];
private char[] grades = new char[5];
private double[] scores1 = new double[5];
private double[] scores2 = new double[5];
private double[] scores3 = new double[5];
private double[] scores4 = new double[5];
private double[] scores5 = new double[5];
int studentData = 0;
int studentCount = 0;
Scanner keyboard = new Scanner(System.in);
public void enterData() {
do {
System.out.println("Enter the student's name:");
String student = keyboard.nextLine();
System.out.println("Enter the student's first test score");
double score1 = Double.parseDouble(keyboard.nextLine());
if (score1 > 0 || score1 < 100) {
} else {
System.out.println("Invalid number");
continue;
}
System.out.println("Enter the student's second test score");
double score2 = Double.parseDouble(keyboard.nextLine());
if (score2 > 0 || score2 < 100) {
} else {
System.out.println("Invalid number");
System.out.println("Please start over");
continue;
}
System.out.println("Enter the student's third test score");
double score3 = Double.parseDouble(keyboard.nextLine());
if (score3 < 0 || score3 > 100)
System.out.println("Invalid number");
System.out.println("Enter the student's fourth test score");
double score4 = Double.parseDouble(keyboard.nextLine());
if (score4 < 0 || score4 > 100)
System.out.println("Invalid number");
addStudent(student, score1, score2, score3, score4);
studentData++;
} while (studentData < 5);
}
public String toString() {
StringBuilder printout = new StringBuilder();
for (int i = 0; i < names.length; i++) {
if (names[i] == null)
continue;
printout.append("Student name: " + names[i] + "\t" + "Average test score: " +
getAverage(i) + "\t" + "Grade: " + grades[i] + "\n");
}
return printout.toString();
}
private void addStudent(String inName, double scr1, double scr2, double scr3, double scr4) {
names[studentCount] = inName;
scores1[studentCount] = scr1;
scores2[studentCount] = scr2;
scores3[studentCount] = scr3;
scores4[studentCount] = scr4;
grades[studentCount] = getLetterGrade(studentCount);
studentCount++;
}
private double getAverage(int index) {
double score1 = scores1[index];
double score2 = scores2[index];
double score3 = scores3[index];
double score4 = scores4[index];
double average = (score1 + score2 + score3 + score4) / 4.0;
return average;
}
private char getLetterGrade(int index) {
double average = getAverage(index);
char grade;
if (average >= 90)
grade = 'A';
else if (average >= 80)
grade = 'B';
else if (average >= 70)
grade = 'C';
else if (average >= 60)
grade = 'D';
else
grade = 'F';
return grade;
}
}
I made this more difficult than needed. This works just fine.
System.out.println("Enter the student's third test score");
double score3 = Double.parseDouble(keyboard.nextLine());
while (score3 < 0 || score3 > 100)
{
System.out.println("Invalid score, plese reenter");
System.out.println("Enter the student's third test score");
score3 = Double.parseDouble(keyboard.nextLine());
}
Well I know of a way to do this using JOptionPanes:
int n = JOptionPane.showConfirmDialog(null,
"Would you like to start over?",
"Incorrect Input",
JOptionPane.YES_NO_OPTION);
if(n == JOptionPane.YES_OPTION)
{
//start over
}
else
{
System.exit(0);
}
I guess whatever the equivalent this would be in the System class.
What you want to do is flow control. The easiest ways are:
1) Make your method return a boolean. If the method exits correctly (all data entered) return true, if the method has to exit in error (as in this case), return false (in this case, from inside the if that controls the condition.
2) Throw an exception if the method finds an error.
In both cases, the logic calling your method will have to check for the return value/exception thrown and call again the method if it is needed.
System.out.println("Enter the student's third test score");
double score3 = Double.parseDouble(keyboard.nextLine());
while (score3 < 0 || score3 > 100)
{
System.out.println("Invalid score, plese reenter");
System.out.println("Enter the student's third test score");
score3 = Double.parseDouble(keyboard.nextLine());
}