How would i create a user input exit code for this type of program?
import java.util.Scanner;
public class Testprogram{
public static void main(String[] args){
System.out.println("Enter any test score between 0 and 100");
Scanner keyboard = new Scanner(System.in);
while(true){
double myScore=Double.parseDouble(keyboard.next());
for(double x=0; x<=100;){
char grade;
if (myScore>= 90){
grade = 'A';
}
else if (myScore>=80){
grade = 'B';
}
else if (myScore>=70){
grade = 'C';
}
else if (myScore>=60){
grade = 'D';
}
else {
grade = 'F';
}
System.out.println("Grade = " + grade);
break;
}
}
}
}
To return exit code from a Java program you should use System.exit(int).
You can do it by changing this:
double myScore=Double.parseDouble(keyboard.next());
To this:
String code = keyboard.next();
if(code == "exit") //if user types 'exit' then exit the while loop
break;
double myScore = Double.parseDouble(code);
Related
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);
}
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'm new to Java and attempting this question where I'm supposed to input a pair of values (two strings one at a time) which is meant to loop until I've exited using ctrl z. Only the grade will be used for the switch; the name is just a dummy value.
My expected output will be:
Enter name: (Name is then entered)
Enter grade: (Grade is then entered)
Code repeats until EOC is hit.
What is the most effective way to implement a working loop using while (.hasNext())? The code I've tried to make is very flawed, as seen below.
public static void main(String[] args) {
int ACount = 0;
int BCount = 0;
int CCount = 0;
int DCount = 0;
Scanner input = new Scanner(System.in);
while(input.hasNext()) {
System.out.print("\nEnter name: ");
String nameInput = input.next();
System.out.print("Enter grade: ");
String gradeInput = input.next();
switch (gradeInput) {
case "A":
ACount++;
break;
case "B":
BCount++;
break;
case "C":
CCount++;
break;
case "D":
DCount++;
break;
}
}
System.out.printf("%n%nGrade report%n%nA: %d%nB: %d%nC: %d%nD: %d%n", ACount, BCount, CCount, DCount);
}
I think this solution is what you are looking for, it switches between asking for the name and grade until you cancel it with ctrl + z. Personally I have been coding java for 4 years and never used a switch, so I just used simple if-else statements, also by using just print, not println, the phrase was getting into the var, which is the reason of me using println.
public static void main(String[] args) {
int ACount = 0;
int BCount = 0;
int CCount = 0;
int DCount = 0;
Scanner input = new Scanner(System.in);
boolean askingForName = false;
boolean first = true;
System.out.println("Enter name: ");
while(true) {
if (first) {
String nameInput = input.nextLine();
first = false;
continue;
}
if (askingForName) {
System.out.println("Enter name: ");
String nameInput = input.nextLine();
askingForName = false;
}else {
System.out.println("Enter grade: ");
String gradeInput = input.nextLine();
if (gradeInput.equalsIgnoreCase("A")) {
ACount++;
}else if (gradeInput.equalsIgnoreCase("B")) {
BCount++;
}else if (gradeInput.equalsIgnoreCase("C")) {
CCount++;
}else if (gradeInput.equalsIgnoreCase("D")) {
DCount++;
}
askingForName = true;
}
if (!input.hasNextLine())
break;
}
System.out.printf("%n%nGrade report%n%nA: %d%nB: %d%nC: %d%nD: %d%n", ACount, BCount, CCount, DCount);
}
program is intended to take input as an integer and return a grade as well as a grade point. By default it keeps outputting the last if statement. Any help is appreciated as I am a complete beginner to this.
import java.util.Scanner;
public class gradePoint {
int grade;
String x;
public void getGrade() {
int x = grade;
if (x>90 && x<100) {
System.out.println("A+ ; GradePoint 9");
}else if(x>80 && x<89){
System.out.println("A ; GradePoint 8");
}else if(x>75 && x<79){
System.out.println("B+ ; GradePoint 7");
return;
}else if (x>70 && x<74){
System.out.println("B ; GradePoint 6");
}else if (x>65 && x<69){
System.out.println("C+ ; GradePoint 5");
}else if (x>60 && x<64){
System.out.println("C ; GradePoint 4");
}else if (x>55 && x<59){
System.out.println("D+ ; GradePoint 3");
}else if (x>50 && x<54){
System.out.println("D ; GradePoint 2");
}else if (x>48 && x<49){
System.out.println("E ; GradePoint 1");
}else if (x<47){
System.out.println("F ; GradePoint 0");
}
}
public static void main (String[] args){
System.out.println("enter grade");
Scanner sc = new Scanner (System.in);
int grade = sc.nextInt();
gradePoint g = new gradePoint();
g.getGrade();
}
}
output:
enter grade
90
F ; GradePoint 0
You never pass the input grade into your gradePoint object.
Therefore the instance member int grade; remains 0 by default, so after int x = grade;, x is also 0.
You can use a constructor to initialize the grade variable:
public gradePoint (int grade)
{
this.grade = grade;
}
and
gradePoint g = new gradePoint(grade);
g.getGrade();
Or you can pass the grade directly to your getGrade() method:
public void getGrade(int grade) {
if (grade>90 && grade<100) {
...
}
and
gradePoint g = new gradePoint();
g.getGrade(grade);
Your program keeps printing F ; GradePoint 0 because field grade of gradePoint class is zero. Variable grade inside main is local. It does not matter what its value is, because grade inside getGrade does not change.
You should make a few changes to your program to fix this problem:
Rename the class to GradePoint to follow Java naming guidelines,
Rename getGrade to printGrade, and make it a static method,
Give printGrade a grade parameter of type int,
Remove field grade from the class,
Pass variable grade from main to printGrade.
After the modification your main should look like this:
public static void main (String[] args){
System.out.println("enter grade");
Scanner sc = new Scanner (System.in);
int grade = sc.nextInt();
printGrade(grade);
}
I wrote this program to convert a number grade into a letter grade but I keep getting the same errors. Could someone help me figure out what I'm doing wrong?
import static java.lang.System.*;
import java.util.Scanner;
public class Grade
{
private int numGrade;
public Grade()
{
Grade test;
}
public void setGrade(int grade)
{
numGrade = grade;
if (grade >= 90)
{
System.out.println("A");
}
{
System.out.println("B");
}
public String getLetterGrade( ) {
String letGrade="A";
if (grade>= 90)
{
return letGrade;
}
public String toString(){
return numGrade + " is a " + getLetterGrade() + "\n";
}
}
Seems like you tried to attack the same thing from many different positions.
first of lets start with converting numerical grades into letter grades, so before engaging to inputs, start with asking the kind of grade the user wishes to convert
char choise;
choise = reader.nextChar(); //ask for N or L for numerical or letter
next i'll show a sample code for letter to numerical convertion
public int getNGrade(char grade)
{
if (grade == 'A')
return 90;
else if (grade == 'B')
return 80; //and so on
}
same way can be used for the numerical to letter convertion
in the main class u call the function:
charGrade = reader.nextChar();
System.out.println("Your grade in numbers is " + getNGrade(charGrade));
i'm guessing that's what u meant, hope i was helpful.
Your code can be this and it works perfectly:
public class Grade {
private int numGrade;
public Grade(int grade) {
numGrade = grade;
}
public int getGrade() {
return numGrade;
}
public void setGrade(int grade) {
numGrade = grade;
}
public String getLetterGrade() {
if(numGrade <0 || numGrade > 100) throw new IllegalArgumentException("No such a grade!");
else if(numGrade>=90) return "A";
else if (numGrade >= 80) return "B";
else if(numGrade >= 70) return "C";
else if(numGrade >= 60) return "D";
else return "F";
}
public String toString(){
return numGrade + " is a " + getLetterGrade() + "\n";
}
}
You can include in the same class a main method or create a separate class for testing:
public static void main(String[] args) {
Grade g = new Grade(75); //you can enter the grade manually or simply using a Scanner object
System.out.println(g);
}
The syntax used is incorrect.
Attached is a sample code to do the conversion
public class Grade {
private int numGrade;
public void setGrade(int grade) {
numGrade = grade;
if (grade >= 90) {
System.out.println("A");
} else {
System.out.println("B");
}
}
public String getLetterGrade() {
String letGrade = "B";
if (numGrade >= 90) {
return "A";
}
return letGrade;
}
public String toString() {
return numGrade + " is a " + getLetterGrade() + "\n";
}
}
import java.util.Scanner;
class Tutorial {
public static void main(String args[]){
Scanner input = new Scanner(System.in); // calling Scanner method
String restart = "Y"; //initialising the restart variable
while (restart.equals("Y")) // testing the conditon(if Y is equals then it continues)
{
int grade;
System.out.println("WELCOME TO ABD GRADING SYSTEM.");
System.out.println("Enter your Score(between 1 - 100) : "); // Displaying a message on screen
grade = input.nextInt(); // Accept Input from the user
if(grade<=39)
System.out.println("Your grade is F9");
else if(grade==40 || grade<=49)
System.out.println("Your grade is D7");
else if(grade==50 || grade<=59)
System.out.println("Your grade is C6");
else if(grade==60 || grade<=69)
System.out.println("Your grade is C5");
else if(grade==70 || grade<=79)
System.out.println("Your grade is B2");
else if(grade==80 || grade<=100)
System.out.println("Your grade is A1");
else
{
System.out.println("Input Correct score between (1 - 100).");
}
System.out.println("THANK YOU.");
System.out.println("Would you like to Calculate again? Y/N ");
restart = input.next();
}
}
}