Java using if statement, for loop and method call - java

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);
// }
}
}

Related

How do I continue to loop until the user wants to quit?

Java
How do I continue to loop until the user wants to quit? I have tried inserting a do while loop but no matter where I put it, it doesn't seem to work. it keeps giving me an error message. I want to loop this until the user doesn't want to enter a score anymore. so it will continue to prompt for another letter grade until they type a "Y" or "N". Thank you!
import java.util.Scanner;
public class gradeConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score = 0;
int minimum = 0;
int maximum = 100;
int grade = 0;
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score,1,100))
{
System.exit(0);
}
getLetterGrade(score);
}
private static boolean isValidNumber(int number, int minimum, int maximum)
{
return number > minimum && number<=maximum;
}
private static String getLetterGrade(int score)
{
String grade=null;
if(score >=80 && score <90) {
System.out.println("B");//java code tells you that your letter grade is a B if you input a score that is between and includes 90 and 80
grade = "B";
}
else if(score <= 100 && score >= 90) {
System.out.println("A");//java code tells you that your letter grade is a A if you input a score that is between and includes 100 and 90
grade = "A";
}else if(60>score){
System.out.println("F");
grade = "F";
}
return grade;
}
}
You can simply use while loop until the user wants to quit. Add a condition on user prompt input and if the user tries to quit, just break the loop.
Also, you're exiting the system if the user gives invalid input. What you can do is, you can continue the program to make the user give a valid input.
while (true) {
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score, minimum, maximum)) {
System.out.println("The input is not in valid range!");
continue;
}
letterGrade = getLetterGrade(score);
System.out.println("The corresponding letter grade is: " + letterGrade);
if (!doContinue(scan)) {
break;
}
}
The do continue function just checks whether the user wants to continue or not. Returns a boolean:
private static boolean doContinue(Scanner sc) {
System.out.println("Do you want to continue? (y/n): ");
String input = sc.next();
return input.toLowerCase().equals("y");
}
Also, instead of printing the grades while checking condition, you can just return it, just as I've done in the above segment:
private static String getLetterGrade(int score) {
if (score >= 80 && score < 90) {
return "B";
} else if (score >= 90 && score <= 100) {
return "A";
} else if (score < 60) {
return "F";
} else {
return "Unknown Grade";
}
}
And I guess you can change the min max range too, for a proper practical input:
private static boolean isValidNumber(int number, int minimum, int maximum) {
return number >= minimum && number <= maximum;
}
import java.util.Scanner;
public class gradeConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
char opt;
int score = 0;
int minimum = 0;
int maximum = 100;
int grade = 0;
do {
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score, 1, 100)) {
System.exit(0);
}
getLetterGrade(score);
System.out.println("Do yu wish to continue?: ");
opt = Character.toLowerCase(scan.next().charAt(0));
} while (opt == 'y');
}
private static boolean isValidNumber(int number, int minimum, int maximum) {
return number > minimum && number <= maximum;
}
private static String getLetterGrade(int score) {
String grade = null;
if (score >= 80 && score < 90) {
System.out.println("B");// java code tells you that your letter grade is a B if you input a score that
// is between and includes 90 and 80
grade = "B";
} else if (score <= 100 && score >= 90) {
System.out.println("A");// java code tells you that your letter grade is a A if you input a score that
// is between and includes 100 and 90
grade = "A";
} else if (60 > score) {
System.out.println("F");
grade = "F";
}
return grade;
}
}
The do ... while loop works for this but you might want to refactor your variable declarations to change with newer scores being inputted.
I refactored your code a bit, and added the possibility to say a grade or N in the same field.
I also added the possibility to loop until an incorrect value or a N value is typed, using a simple while condition
Just have a look and feel free to modify it again
import java.util.Scanner;
public class gradeConverter {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int minimum = 1;
int maximum = 100;
String grade;
boolean keep_going = true;
while(keep_going) {
System.out.println("Enter letter grade 0-100: ");
grade = scan.nextLine();
if (!isValidChoice(grade, minimum, maximum)) {
System.out.println("Invalid choice!");
keep_going = false;
break;
}
if(grade.toLowerCase().equals("n"))
keep_going = false;
else
getLetterGrade(Integer.parseInt(grade));
}
}
private static boolean isValidChoice(String value, int minimum, int maximum)
{
if(value.toLowerCase().equals("n"))
return true;
try {
int letter = Integer.parseInt(value);
return letter > minimum && letter<=maximum;
} catch (NumberFormatException e) {
return false;
}
}
private static String getLetterGrade(int score)
{
String grade=null;
if(score >=80 && score <90) {
System.out.println("B");//java code tells you that your letter grade is a B if you input a score that is between and includes 90 and 80
grade = "B";
}
else if(score <= 100 && score >= 90) {
System.out.println("A");//java code tells you that your letter grade is a A if you input a score that is between and includes 100 and 90
grade = "A";
}else if(60>score){
System.out.println("F");
grade = "F";
}
return grade;
}
}
You can scan in a loop and check the entered data for the need to exit it.
I also changed the type of the input value to support this check.
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String input;
int minimum = 0;
int maximum = 100;
int grade = 0;
System.out.println("Enter letter grade 0-100: ");
input = scan.nextLine();
while (!input.equals("y") || !input.equals("n")) {
int score = Integer.parseInt(input);
if (!isValidNumber(score,1,100)) {
getLetterGrade(score);
}
input = scan.nextLine();
}
System.exit(0);
}

having to use this layout, how do I get the grade to print?

java. having to use this layout, how can I get the grade to print. my professor wants us to use these three different methods and I'm not sure how to print it. I can get the program to prompt for the number score but then it stops
import java.util.Scanner;
public class gradeConverter
{
public static void main (String [] args)
{
Scanner scan = new Scanner(System.in);
int score = 0;
int minimum = 0;
int maximum = 100;
int grade = 0;
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (score < 0)
{
System.exit(0);
}
}
private static boolean isValidNumber(int number, int minimum, int maximum)
{
boolean isValidNumber = false;
//Do something with number or test it for a condition
if( number > 0 )
isValidNumber = false;
if ( minimum > 0 )
isValidNumber = true;
if (maximum < 100);
isValidNumber = false;
return isValidNumber;
}
private static String getLetterGrade (int score)
{
if(score >=80 && score <90)
System.out.println("B");//java code tells you that your letter grade is a B if you input a score that is between and includes 90 and 80
if(score <= 100 && score >= 90)
System.out.println("A");//java code tells you that your letter grade is a A if you input a score that is between and includes 100 and 90
if(60>score)
System.out.println("F");
return getLetterGrade(0);
}
}
Code get stopped because you are not doing anything after reading the score.
Another issue in the code is getLetterGrade method is calling recursively.
Please use below attached code:
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int score = 0;
int minimum = 0;
int maximum = 100;
int grade = 0;
System.out.println("Enter letter grade 0-100: ");
score = scan.nextInt();
if (!isValidNumber(score,1,100))
{
System.exit(0);
}
getLetterGrade(score);
}
private static boolean isValidNumber(int number, int minimum, int maximum)
{
return number > minimum && number<=maximum;
}
private static String getLetterGrade(int score)
{
String grade=null;
if(score >=80 && score <90) {
System.out.println("B");//java code tells you that your letter grade is a B if you input a score that is between and includes 90 and 80
grade = "B";
}
else if(score <= 100 && score >= 90) {
System.out.println("A");//java code tells you that your letter grade is a A if you input a score that is between and includes 100 and 90
grade = "A";
}else if(60>score){
System.out.println("F");
grade = "F";
}
return grade;
}
}

How to let the user attempt many times?

import java.util.Scanner;
import java.util.Random;
/*
* 1) the user can attempt many times and you need to display the number of successful attempt
* 2) the range of random number 1..49
* 3) output >> You successfully guess the number in 16 attempts
* 4) output >> Do you want to play again?
* */
public class GuessingGame {
public static void main(String[] args) {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count=0;
String in;
char again;
System.out.println("Welcome to Guessing Game");
do {
number = randNum.nextInt(50); // random number in the range of 1..50
for(int i=0; i<5; i++)
{
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
if(guessNumber > number)
{
System.out.println("Too big");
}else if(guessNumber < number)
{
System.out.println("Too small");
}else
{
System.out.println("Success");
count+=1;
return;
}
}
System.out.println("You successfully guess the number in "+count);
System.out.println("Do you want to play again? ");
in = uInput.nextLine();
again = in.charAt(0); //again will hold the first character from in var
}while(again =='Y'|| again =='y');
System.out.println("Guessing game terminate, thank you");
}
}
public static void main(String[] args) {
System.out.println("Welcome to Guessing Game");
guessNumber();
System.out.println("Guessing game terminate, thank you");
}
private static void guessNumber() {
Scanner uInput = new Scanner(System.in);
Random randNum = new Random();
int guessNumber, number, count = 0;
String in;
char again;
boolean isCorrect = false;
number = randNum.nextInt(50); // random number in the range of 1..50
while (!isCorrect) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt(); // get guess number from user
count += 1;
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
isCorrect = true;
}
}
System.out.println("You successfully guess the number in " + count + " attempts");
System.out.println("Do you want to play again? yes/no");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
if (again == 'Y' || again == 'y') {
guessNumber();
}
}
All you have to do is to replace your do while loop with a while loop. But the point is that you must set an initial value 'Y' to your again char to start the while loop. the condition of the loop will be just the same. The code will be like : char again = 'Y';
while (again == 'Y' || again == 'y') {
System.out.println("Welcome to Guessing Game");
number = randNum.nextInt(50);
for (int i = 0; i < 5; i++) {
System.out.println("Enter a number to guess: ");
guessNumber = uInput.nextInt();
if (guessNumber > number) {
System.out.println("Too big");
} else if (guessNumber < number) {
System.out.println("Too small");
} else {
System.out.println("Success");
count += 1;
break;
}
}
System.out.println("You have successfully guessed the number for " + count + " times");
System.out.println("Do you want to play again? ");
in = uInput.next();
again = in.charAt(0); //again will hold the first character from in var
}
System.out.println("Guessing game terminate, thank you");
I must note that your count variable, contains the number of games which user has guessed the number successfully, and not the number of attempts during a single game. If you want to handle this too, create attempts variable inside the while loop and increase it whenever the user attempts.
Also I changed the line in = uInput.nextLine(); to in = uInput.next(); because I believe your scanner input will be skipped.

A while loop that stops after a certian number is entered

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)");
}
}

String Cannont Be Converted to Char

I do not understand why my program will not allow me to convert my variable into char. Any help would be greatly appreciated!!! I am getting a total of 7 errors all either based around my test score grades or around the test score keyboard entry.
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextLine();
if (testScore < 60)
{
grade =(F);
}
else
{
if (testScore < 70)
{
grade =("D");
}
else
{
if (testScore < 80)
{
grade =("C");
}
else
{
if (testScore < 90)
{
grade =("B");
}
else
{
grade =("A");
}
}
}
}
System.out.print("Test score:"+testScore);
System.out.print("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13
A char constant can be expressed with '' like
grade = 'F';
and
grade = 'D';
and
grade = 'C';
and
grade = 'B';
and
grade = 'A';
char can only hold a single character, which is defined using single quotes, as in 'C'
Insted of keyboard.nextLine() use keyboard.nextInt() and for character value assignment directly use character with single quota like 'A' instead of ("A")
import java.util.Scanner;
public class lab13
{
public static void main(String[] args)
{
// declare variables
int average;
int sum;
int i;
char grade;
int testScore;
//Create a Scanner Object
Scanner keyboard= new Scanner(System.in);
sum = 0;
i = 1;
while (i <= 4)
{
System.out.print("Enter a test score:");
testScore=keyboard.nextInt();
if (testScore < 60)
{
grade ='F';
}
else
{
if (testScore < 70)
{
grade ='D';
}
else
{
if (testScore < 80)
{
grade ='C';
}
else
{
if (testScore < 90)
{
grade ='B';
}
else
{
grade ='A';
}
}
}
}
System.out.println("Test score:"+testScore);
System.out.println("Letter grade:"+grade);
sum = sum + testScore;
i = i + 1;
}
average = sum / 4;
System.out.print("Test score average = " + average);
} // close main
} // close lab13

Categories