A while loop that stops after a certian number is entered - java

I am trying to write a program that takes in grades numbers from the user, and stops when -1 is entered. But, every time I enter -1 the while loop continues to run, how do I stop it from running?
import java.util.Scanner;
public class getLetterGrade {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
int count = 0;
while (count >= 0)
getGrade();
count++;
System.out.println("You entered" + " " + count + " " + "Student(s)");
}
public static void getGrade() {
Scanner reader = new Scanner(System.in);
double grade;
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
grade = reader.nextDouble();
if (grade >= 90)
System.out.println("That's an A");
else if (grade >= 80 && grade < 90)
System.out.println("That's an B");
else if (grade >= 70 && grade < 80)
System.out.println("That's an C");
else if (grade >= 60 && grade < 70)
System.out.println("That's an D");
else if (grade <= 50 && grade > 0)
System.out.println("That's an F");
if (grade == -1)
System.out.println("");
}
}

A few things that need to be changed... First, your loop keeps looping because you never set count to less then 0, so the condition is always true. You also create 2 Scanner objects, but only ever use the second one (in getGrade()).
Try this code, and have a look at the comments to see everything that's changed:
public class getLetterGrade {
static Scanner reader; //Add reader as member variable
public static void main(String[] args) {
//Scanner reader = new Scanner(System.in); //Remove this unused Scanner
int count = 0;
reader = new Scanner(System.in);
while (getGrade()) //Change the condition here so the loop will continue while getGrade() returns true.
count++;
reader.close(); //Close the Scanner
System.out.println("You entered" + " " + count + " " + "Student(s)");
}
public static boolean getGrade() { //getGrade() returns a boolean...
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
double grade = reader.nextDouble(); //Consider using a try/catch block here.
if (grade >= 90)
System.out.println("That's an A");
else if (grade >= 80 && grade < 90)
System.out.println("That's an B");
else if (grade >= 70 && grade < 80)
System.out.println("That's an C");
else if (grade >= 60 && grade < 70)
System.out.println("That's an D");
else if (grade <= 50 && grade > 0)
System.out.println("That's an F");
else if(grade != -1)
System.out.println("Invaled input!"); //Print if 'grade' is something other then the above statements.
if (grade == -1) { //Add brackets
System.out.println("");
return false; //return false if -1 was entered...
}
return true; //else return true
}
}

You could move the loop down into the other method, make it an "endless" loop, and use return to exit from it. You can then return the count from that method and show it in main.
It might then look like this. Note that I've simplified your branching logic too, and removed the double entendre from the output message.
I have also used a try-with-resources block, which is one way of making sure you always close the scanner, and avoid resource leaks. Not strictly needed in this case, but still a good habit to get into.
Edit As the Scary Wombat has pointed out, you could add an else clause to deal with the case where the user inputs an invalid grade if you really wanted to.
import java.util.Scanner;
public class GetLetterGrade {
public static void main(String[] args) {
int count = getGrades();
System.out.println("You entered " + count + " grade(s)");
}
public static int getGrades() {
try(Scanner reader = new Scanner(System.in)) {
int count = 0;
while(true) {
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
double grade = reader.nextDouble();
if (grade >= 90) {
System.out.println("That's an A");
} else if (grade >= 80 ) {
System.out.println("That's a B");
} else if (grade >= 70) {
System.out.println("That's a C");
} else if (grade >= 60) {
System.out.println("That's a D");
} else if (grade >= 0) {
System.out.println("That's an F");
} else if (grade == -1) {
return count;
}
count++;
}
}
}
}

import java.util.Scanner;
public class GetLetterGrade {
public static void main(String[] args) {
int count = 0;
while (getGrade() >= 0.0){
count++;
System.out.println("You entered" + " " + count + " " + "Student(s)");
}
}
public static double getGrade() {
Scanner reader = new Scanner(System.in);
double grade;
System.out.println("Welcome to the grade calculator. \n Please enter a numeric grade. \n After the last student in the class, enter a grade of -1.");
grade = reader.nextDouble();
if (grade >= 90)
System.out.println("That's an A");
else if (grade >= 80 && grade < 90)
System.out.println("That's an B");
else if (grade >= 70 && grade < 80)
System.out.println("That's an C");
else if (grade >= 60 && grade < 70)
System.out.println("That's an D");
else if (grade <= 50 && grade > 0)
System.out.println("That's an F");
if (grade == -1)
System.out.println("");
return grade ;
}
}

Your while loop always takes the 0 value and get in to while loop thats why it didn't stop..
import java.util.Scanner;
public class getLetterGrade {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Welcome to the grade calculator. \n After the last student in the class, enter a grade of -1.");
int count = 0;
int no = -1;
while (count != -1) {
no++;
System.out.println("Please enter the value:-");
count = reader.nextInt();
if (count >= 90) {
System.out.println("That's an A");
} else if (count >= 80 && count < 90) {
System.out.println("That's an B");
} else if (count >= 70 && count < 80) {
System.out.println("That's an C");
} else if (count >= 60 && count < 70) {
System.out.println("That's an D");
} else if (count <= 59 && count > 0) {
System.out.println("That's an F");
}
if (count == -1) {
break;
}
}
count++;
System.out.println("You entered" + " " + no + " " + "Student(s)");
}
}

Related

I have to classify a certain grade into (A,B,C,D,F), but error message doesn't show up

When the final grade is above 200, i want an error message to show up but it doesn't, i tried to structure my loop that way but it just doesnt work.
import java.util.Scanner;
import java.util.Formatter;
public class Lab3 {
public static void main(String[] args) {
double midtermGrade = 50.0;
double homeworkGrade = 0.0;
double finalExamGrade = 50.0;
double finalGrade = 0.0;
char letterGrade = ' ';
Scanner scan = new Scanner(System.in);
System.out.println("Enter homework grade: ");
homeworkGrade = scan.nextDouble();
System.out.println("Enter midterm exam grade: ");
midtermGrade = scan.nextDouble();
System.out.println("Enter final exam grade: ");
finalExamGrade = scan.nextDouble();
if ((!(homeworkGrade >= 0) || !(homeworkGrade <= 100))) return;
if (((midtermGrade >= 0) && (midtermGrade <= 100)))
if ((((!(finalExamGrade > 0) || !(finalExamGrade < 200))))) {
finalGrade = (finalExamGrade / 200) * 50 + (midtermGrade * .25) + (homeworkGrade * .25); //.25 denotes 25%
}
System.out.println("Invalid input. Homework and midterm grades should be between 0 and 100 and the final grade should be between 0 and 200");
if (finalGrade >= 50) {
letterGrade = 'P';
} else if (finalGrade < 50) {
letterGrade = 'F';
}
if (letterGrade == 'P') {
System.out.println("Student passed the class");
} else if (letterGrade == 'F') {
System.out.println("Student failed the class");
}
}
}
When i put the obnoxiously large numbers, i don't get any message. The debug ends.
I think the ! is interfering with the final grade
i change your code and now it works. here it is:
package test;
import java.util.Scanner;
public class Testing {
public static void main(String[] args) {
double midtermGrade = 50.0;
double homeworkGrade = 0.0;
double finalExamGrade = 50.0;
double finalGrade = 0.0;
char letterGrade = ' ';
Scanner scan = new Scanner(System.in);
System.out.println("Enter homework grade: ");
homeworkGrade = scan.nextDouble();
if (!(homeworkGrade >= 0) || !(homeworkGrade <= 100)) {
System.out.println("Invalid input.Homework grades should be between 0 and 100");
return;
}
System.out.println("Enter midterm exam grade: ");
midtermGrade = scan.nextDouble();
if (!(midtermGrade >= 0) && !(midtermGrade <= 100)){
System.out.println("Invalid input.midterm grades should be between 0 and 100");
return;
}
System.out.println("Enter final exam grade: ");
finalExamGrade = scan.nextDouble();
if ((!(finalExamGrade > 0) || !(finalExamGrade < 200))) {
System.out.println("Invalid input. final grade should be between 0 and 200");
return;
}
finalGrade = (finalExamGrade / 200) * 50 + (midtermGrade * .25) + (homeworkGrade * .25); //.25 denotes 25%
if (finalGrade >= 50) {
letterGrade = 'P';
} else if (finalGrade < 50) {
letterGrade = 'F';
}
if (letterGrade == 'P') {
System.out.println("Student passed the class");
} else if (letterGrade == 'F') {
System.out.println("Student failed the class");
}
}
}
You just need to change your package name and class name.
Note:
- its better to check each input, after the scan. And check if the value is right or not. if the input data is not right, you should return and terminate the program.

Negative numbers are not recognized

import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
Scanner quest = new Scanner(System.in);enter code here
System.out.println("How old are you?: ");
int num = quest.nextInt();
if (num <= 12){
System.out.println("You are too young to be on the computer!!!!");
} else if (num >=13 && num <= 17){
System.out.println("Welcome young teen");
} else if (17 < num && num <= 60){
System.out.println("Welcome adult");
} else if (60 < num){
System.out.println("Welcome senior citizen!!");
} else{
System.out.println("Invalid age.");
}
}
}
When I enter a negative number it just falls under the "You are too young to be on the computer!!!!" instead of displaying "Invalid age." I have tried changing the condition but it id not seem to work.
Because a negative number is less than 12, you could simplify your chain of if-else blocks by testing for negative values and eliminating your && checks by relying on the previously checked conditions. Like,
int num = quest.nextInt();
if (num < 0) { // <-- negative values.
System.out.println("Invalid age.");
} else if (num <= 12) { // <-- (0, 12)
System.out.println("You are too young to be on the computer!!!!");
} else if (num <= 17) { // <-- (13, 17)
System.out.println("Welcome young teen");
} else if (num <= 60) { // <-- (18, 60)
System.out.println("Welcome adult");
} else { // <-- greater than 60
System.out.println("Welcome senior citizen!!");
}
You should have made it your first condition with the if(Condition) { //Code } statement. Well I did a run on the code and kinda make a little adjustment to your code.
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
// Prints "Hello, World" in the terminal window.
Scanner quest = new Scanner(System.in); //enter code here
System.out.println("How old are you?: ");
int num = quest.nextInt();
if (num <= 0) {
System.out.println("Invalid age.");
} else if (num <= 12){
System.out.println("You are too young to be on the computer!!!!");
} else if (num >=13 && num <= 17){
System.out.println("Welcome young teen");
} else if (17 < num && num <= 60){
System.out.println("Welcome adult");
} else if (60 < num){
System.out.println("Welcome senior citizen!!");
}
}
}

How do I end the console if the user inputs an integer than doesn't comply with my condition?

I'm currently create a simple grade calculator, however I want the console not to continue with the next line when the user doesn't enter a number between 0 and 20. Even if the user enters the wrong one the next line is executed. Also feel free to suggest ways of making my program simpler.
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter grade for Exam 1:>");
int exam1 = scanner.nextShort();
while (exam1 > 20 || exam1 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
System.out.println("Enter grade for Exam 2:>");
int exam2 = scanner.nextShort();
while (exam2 > 20 || exam2 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
System.out.println("Enter grade for Exam 3:>");
int exam3 = scanner.nextShort();
while (exam3 > 20 || exam3 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
System.out.println("Enter grade for Exam 4:>");
int exam4 = scanner.nextShort();
while (exam4 > 20 || exam4 < 0) {
System.out.println("Error! Not within mark range!");
break;
}
int average = exam1 + exam2 + exam3 + exam4;
average /= 4;
System.out.println("You average grade is: " + average + "\n");
average *= 5;
System.out.println("Your score is" + average + "%!\n");
if (average > 70) {
System.out.println("You get an A overall");
} else if (average > 60 || average <= 70) {
System.out.println("You get a B overall");
} else if (average > 40 || average <= 60) {
System.out.println("You get a C overall");
} else {
System.out.println("You have failed the module!");
}
}
}
System.exit(0);
This is probably what you're looking for, instead of the break statements.
Replace the break statements in your code with System.exit(0)

Java using if statement, for loop and method call

In main, create a for loop that will ask for the numeric grade and uses the getLetterGrade method to print out the letter grade, until the user enters a -1. so practically i have to ask the user to enter the grade between 0 and 100 and it will look in the method and print the appropriate grade? correct??? so here's the code
System.out.println("Please enter you grade total: ");
Scanner Keyboard = new Scanner(System.in);
studentGrade = Keyboard.nextInt();
for(studentGrade = 0; studentGrade < 1; ++studentGrade){
System.out.print(getLetterGrade);
Create a method called getLetterGrade. The getLetterGrade method takes a grade between 0-100 and then prints out the corresponding letter grade. The grade ranges are A: 100-90 B: 80-89 C: 70-79, D: 60-69, F: 0-59. In main, create a for loop that will ask for the numeric grade and uses the getLetterGrade method to print out the letter grade, until the user enters a -1."
Here's my code: I wrote using if,else if condition. what i don't understand is that do i have to write the condition in main or the method. Usually i dont have a problem with coding but this thing has me puzzled. I though about using case but if, else if conditions seems alot more straight forward.
import java.util.Scanner;
public class getLetterGrade {
public static void getLetterGrade(String getLetterGrade){
int studentGrade = 0;
if(studentGrade >= 90) getLetterGrade("A");
else if(studentGrade >= 80) getLetterGrade("B");
else if(studentGrade >= 70) getLetterGrade("C");
else if(studentGrade >= 60) getLetterGrade("D");
else if(studentGrade >= 0) getLetterGrade("F");
else
System.out.println("you have entered incorrect integer");
int i = 0;
for (i = 0; i < 1; i++){
System.out.print(studentGrade + " ");
}
System.out.println();
}
public static void main(String[] args) {
int studentGrade = 0;
getLetterGrade("A");
getLetterGrade("B");
getLetterGrade("C");
getLetterGrade("D");
getLetterGrade("F");
System.out.println("Please enter you grade total: ");
Scanner Keyboard = new Scanner(System.in);
studentGrade = Keyboard.nextInt();
for(studentGrade = 0; studentGrade < 1; ++studentGrade){
System.out.print(studentGrade);
}
}
}
i know i have to print getLetterGrade but when i try to print getLetterGrade it throws errors, i dont get it.....
thanks for any and all help!!
Your getLetterGrade method is recursive. In the method, you set studentGrade=0, so the method calls getLetter("A"). This repeats, which results in a stackoverflow error.
I think this is what you want instead:
public static void getLetterGrade (int studentGrade) {
if (studentGrade >= 90) System.out.println("A");
else if (studentGrade >= 80) System.out.println("B");
else if (studentGrade >= 70) System.out.println("C");
else if (studentGrade >= 60) System.out.println("D");
else if (studentGrade >= 0) System.out.println("F");
else System.out.println("You have entered an incorrect integer.");
}
In your main method, I think this is what you want:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int studentGrade = keyboard.nextInt();
while (studentGrade != -1) {
getLetterGrade(studentGrade);
studentGrade = keyboard.nextInt();
}
}
In the main method, you can't use a for loop because you don't know in advance how many times the user wants to input. The while loop, on the other hand, checks that the input is not -1 and then prints out the grade for each iteration.
You might need to see a tutorial about for loops though. In a for loop, the variable is just an index. It doesn't have the value of whatever it is you assign to it previously.
try this .
package com.health;
import java.util.Scanner;
public class Test {
public static void getLetterGrade(int studentGrade) {
// int studentGrade = 0;
if (studentGrade >= 90)
System.out.println("A");
else if (studentGrade >= 80)
System.out.println("B");
else if (studentGrade >= 70)
System.out.println("C");
else if (studentGrade >= 60)
System.out.println("D");
else if (studentGrade >= 0)
System.out.println("E");
else
System.out.println("you have entered incorrect integer");
// int i = 0;
//
// for (i = 0; i < 1; i++) {
// System.out.print(studentGrade + " ");
// }
//
// System.out.println();
}
public static void main(String[] args) {
int studentGrade = 0;
// getLetterGrade("A");
// getLetterGrade("B");
// getLetterGrade("C");
// getLetterGrade("D");
// getLetterGrade("F");
while (true) {
System.out.println("Please enter you grade total: ");
Scanner Keyboard = new Scanner(System.in);
studentGrade = Keyboard.nextInt();
if (studentGrade == -1) {
break;
} else {
getLetterGrade(studentGrade);
}
}
// for (studentGrade = 0; studentGrade < 1; ++studentGrade) {
// System.out.print(studentGrade);
// }
}
}

How do I create a window to run my letter grade program in?

I am a beginner in Java and I decided to write a letter grade checker program for people if they want to convert their grades in whole number form to a letter grade. I want to know how I can create a window for this to run in with a dialogue box and space for a photo/logo for the program.
import java.util.Scanner;
public class noname {
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int gradescore;
System.out.println("Please enter your score and round the decimals");
gradescore = user_input.nextInt();
if((gradescore >= 94) && (gradescore <= 100)) {
char grade = 'A';
System.out.println("Your grade is an "+grade);
gradescore = user_input.nextInt();
} else if ((gradescore >=90) && (gradescore <= 93)) {
char grade = 'A';
System.out.println("Your grade is an " +grade +"-");
gradescore = user_input.nextInt();
} else if ((gradescore >= 87) && (gradescore <=89)) {
char grade = 'B';
System.out.println("Your grade is a "+grade +"+");
gradescore = user_input.nextInt();
} else if ((gradescore >= 83) && (gradescore <= 86)) {
char grade = 'B';
System.out.println("Your grade is a "+grade);
gradescore = user_input.nextInt();
} else if ((gradescore >= 80) && (gradescore <= 82)) {
char grade = 'B';
System.out.println("Your grade is a "+grade +"-");
gradescore = user_input.nextInt();
} else if ((gradescore >= 77) && (gradescore <= 79)) {
char grade = 'C';
System.out.println("Your grade is a " +grade +"-");
gradescore = user_input.nextInt();
} else if ((gradescore >= 73) && (gradescore <= 76)) {
char grade = 'C';
System.out.println("Your grade is a " +grade);
gradescore = user_input.nextInt();
} else if ((gradescore >= 70) && (gradescore <= 72)) {
char grade = 'C';
System.out.println("Your grade is a " +grade +"-");
gradescore = user_input.nextInt();
} else if ((gradescore >= 67) && (gradescore <= 69)) {
char grade = 'D';
System.out.println("Your grade is a " +grade +"+");
gradescore = user_input.nextInt();
} else if ((gradescore >= 63) && (gradescore <=66)) {
char grade = 'D';
System.out.println("Your grade is a " +grade);
gradescore = user_input.nextInt();
} else if ((gradescore >= 60) && (gradescore <= 62)) {
char grade = 'D';
System.out.println("Your grade is a " +grade +"-");
gradescore = user_input.nextInt();
} else if (gradescore < 60) {
char grade = 'F';
System.out.println("Your grade is an " +grade);
}
}
}
You can use java swing to do this.
It is a very basic example to create a window using swing:
import java.awt.EventQueue;
import javax.swing.JFrame;
public class SimpleExample extends JFrame {
public SimpleExample() {
setTitle("Simple example");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
SimpleExample ex = new SimpleExample();
ex.setVisible(true);
}
});
}
}
You can follow this tutorial:
http://zetcode.com/tutorials/javaswingtutorial/firstprograms/
Hope it helps.
There is a part of java called swing, which handles windows:
https://docs.oracle.com/javase/tutorial/uiswing/
If you dont like that you could try javafx which uses an xml for storing the UI:
https://docs.oracle.com/javafx/2/get_started/jfxpub-get_started.htm

Categories