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);
}
Related
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;
}
}
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();
I am wishing to prompt the user again if a double outside of the accepted range (0-100) is input, until the input is valid. When the input is considered valid, I am wanting to return correct input value, yet, returned instead is the first incorrect value. How can I return the correct input, as accepted by the if statement?? Many thanks!
public class examscore {
public static void main (String[] args) {
Scanner console = new Scanner(System.in);
double sumfin = finalscore(console);
System.out.println(sumfin); // if user input is initially invalid, but then corrected, the first, incorrect, value is printed
}
public static double finalscore (Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
while(!console.hasNextDouble()) { //prompts the user, if invalid input, to input again, until a valid value is input
System.out.println("Please input a mark between 0 and 100. ");
console.next();
}
double examscore = console.nextDouble();
if (examscore >=0 && examscore<= 100) {
System.out.println();
System.out.println("Exam Score = "+examscore);
} else {
System.out.println("Error:");
finalscore (console);
}
return examscore; //an attempt to return the VALID exam score: fails
}
}
A do-while loop would be a perfect fit. Example:
Scanner console = new Scanner(System.in);
double userInput = 0;
do {
System.out.println("Please input a mark between 0 and 100. ");
try {
userInput = console.nextDouble();
} catch (InputMismatchException e) {
System.out.println("Your input could not be interpreted as a floating-point number.");
}
} while (userInput <= 0D || userInput >= 100D);
You missed to assign result of finalscore(console) to examscore inside the else block.
if (examscore >= 0 && examscore <= 100) {
System.out.println();
System.out.println("Exam Score = " + examscore);
} else {
System.out.println("Error:");
examscore = finalscore(console);
}
You can either use a loop or a recursive call to accomplish this. I prefer a recursive call:
private static double getValidScore(Scanner console) {
System.out.println();
System.out.println("Input final exam score: ");
try {
double score = Double.parseDouble(console.nextLine());
if (score >= 0 && score <= 100) {
return score;
}
} catch (NumberFormatException nfe) {}
System.out.println("Please input a mark between 0 and 100.");
return getValidScore(console);
}
I have this short snippet of code where I have to check a string to see if it contains integers and possibly a decimal. The string is an amount of money (12.34) so as well it can not go past the fourth index.
My question is I'm being told to use charAt() (and in my code I used matches() and contains() which is wrong) to check for integers and decimals so that this routine will return a boolean that is true if the string works with those parameters, however I'm confused at how to go about converting this to use charAt() instead of matches() and contains().
As well, I'm sorry if I formatted this wrong, or worded something wrong, or the code looks awful, I'm in my first semester of Java and it's my very first programming class I've ever taken so I'm a bit rough.
import java.util.Scanner;
public class Auction
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if(price.matches("[0-9]*") && price.length() <= 5)
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else if(price.matches("[0-9]*") && price.length() <= 5 && price.contains("."))
{
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f", f);
System.out.println();
}
else
{
System.out.println("Invalid input");
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if(quantity.contains("."))
{
System.out.println("Invalid input");
}
}
}
I am typing this from a phone. So excuse the mistakes please. have u been asked by your professor to use charAt instead of regex and matches?
if (inpString!= null && !inpString.isEmpty () && inpString.length() <= 5){
int periodCount = 0;
for (int i=0; i < inpString.length (); i++){
char c = inpString.charAt (i);
if (c == '.'){
periodCount++;
}else if (c >= '0' && c <= '9'){
}else {
System.out.println("invalid output");
break;
}
if(periodCount > 1){
System.out.println("too may periods. Invalid output");
break;
}
}
}else {
System.out.println ("invalid input");
}
Can you comment if u need to check that there are no thousandth digit i.e 1.234? If yes make sure
inpString.substring
(inpString.lastIndexOf
(".")).length < 3
with all the null and indexOutOfBounds checks
How about this way?
import java.util.Scanner;
public class Auction {
private static final String numberRegex = "^\\d*(\\.\\d+)?$";
private static final String integerNumber = "^\\d*$";
private static final int MAX_LENGTH = 5;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String price;
String quantity;
System.out.print("How much money are you willing to bet on this item?: $");
price = keyboard.next();
if (price.length() <= MAX_LENGTH && price.matches(numberRegex)) {
Float f = Float.parseFloat(price);
System.out.printf("$%5.2f\n", f);
} else {
System.out.println("Invalid input");
return;
}
System.out.print("What quantity do you want to bid on?: ");
quantity = keyboard.next();
if (!quantity.matches(integerNumber)) {
System.out.println("Invalid input");
}
}
}
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);
// }
}
}