do while loop is not breaking properly java - java

public class DoWhile1 {
private static int grade, total, sum, average;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please enter a grade b/w 0-100:");
grade = sc.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum = sum + grade;
System.out.println("Please enter another grade or 999 to break:");
} else {
System.out.println("Incorrect value, please reenter grade:");
}
} while (grade != 999);
average = sum/total;
}
}
This loop is suppose to break when 999 is entered, but when entered before breaking it output error message from the else inside the loop. It's not suppose to output anything before breaking.
we tried moving the while part of the loop, but it did not affect anything. We can't see any other problems with it.

Your do-while is working correctly - the course of action is the following:
In a do-while, the statements are always executed at least once. So you enter the do { }, and fall into the else condition, since 999 is greater than 0 and not smaller than 100.
You then evaluate the expression grade != 999 -> this is false, since grade == 999.
You don't do the do { } again and come out of the do-while.
To achieve the behavior that you want, you will need to add an additional statement inside the do { }, e.g:
...
if (grade == 999) {
break; //or print statement
}
else if (grade >= 0 && grade <= 100) {
...

You could wrapp the message by another if that checks if the number is not 999.
else
{
if (grade != 999) {
System.out.println("Incorrect value, please reenter grade:");
}
}

Change else to else if (grade != 999) when you are displaying the error.
Do it as follows:
import java.util.Scanner;
public class Main {
private static int grade, total, sum, average;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
do {
System.out.println("Please enter a grade b/w 0-100:");
grade = sc.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum = sum + grade;
System.out.println("Please enter another grade or 999 to break:");
} else if (grade != 999) {
System.out.println("Incorrect value, please reenter grade:");
}
} while (grade != 999);
average = sum / total;
}
}
A sample run:
Please enter a grade b/w 0-100:
24
Please enter another grade or 999 to break:
Please enter a grade b/w 0-100:
999

You could check input value for grade == 999 and exist in case it equals to:
public static double getAverage() {
try (Scanner scan = new Scanner(System.in)) {
int total = 0;
int sum = 0;
int average = 0;
while (true) {
System.out.print("Please enter a grade b/w 0-100 (or 999 to exit): ");
int grade = scan.nextInt();
if (grade >= 0 && grade <= 100) {
total++;
sum += grade;
} else if (grade == 999)
break;
else
System.out.println("Incorrect value\n");
}
return (double)sum / total;
}
}

Related

Outputting a condition I didn't mean to get, probably code blocks are not managed properly

New to Java, having hard time with the blocks, the output should be only "Error invalid numbers" when inputting sum = 9 , examGrade = 105 and average = 105.
Output is now :
"Error invalid numbers"
100
100.00
It's somehow gets to the else condition , didn't succeed to manage it, thank you for help in advance :)
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int examGrade = 0, sum;
double average = 0;
System.out.println("Please enter your Exam Grade");
examGrade = input.nextInt();
System.out.println("Please enter your homework average");
average = input.nextDouble();
System.out.println("Please enter number of exercise");
sum = input.nextInt();
if (sum > 8 || examGrade > 100 || average > 100) {
System.out.println("Error invaild numbers");
}
if (sum <= 4) {
System.out.println("Your Final grade is zero");
}
if (sum == 5 || sum == 6) {
if (examGrade >= 55) {
System.out.println(examGrade*0.8 + average*0.2);
}
}
else {
System.out.println(examGrade);
}
if (sum == 7 || sum == 8) {
if(examGrade <= 54) {
if(average >= 80) {
System.out.println(examGrade*0.75 + average*0.25);
}
else if(average < 80) {
System.out.println(examGrade*0.8 + average*0.2);
}
}
}
else {
System.out.println(examGrade*0.7 + average*0.3);
}
}
You probably want to not do all the other checks if you have an "invalid numbers" condition. To do that, you need to wrap all of them into an else like this:
if (sum > 8 || examGrade > 100 || average > 100 ) {
System.out.println("Error invaild numbers");
} else {
if (sum <= 4 ) {
System.out.println("Your Final grade is zero");
}
// and so on with all the other ifs
} // finish the "not invalid" block

Having Java be able to read one line from a text file and print it

With this, I'm trying to figure out a way in order to have the program read from my "grades.txt" text file and print each line one by one when the input is matched from the user.
So for example, if the grade entered is "93" it will print out "A" from the text file.
I have tried the fileByteStream, BufferedReader, readAllLines, and Scanner. I did end up being able to print the "grades.txt" but not the actual content of the file.
Here is my code:
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Scanner;
public class Main {
private static Object Paths;
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
Scanner txtscanner = new Scanner(new File("grades.txt"));
//grades {0.0, 60.0, 70.0, 77.0, 80.0, 83.0, 87.0, 90.0, 93.0, 100.0};
//letter grades {"F", "D", "C", "C+", "B-", "B", "B+", "A-", "A"};
while (txtscanner.hasNextLine()) {
System.out.println("What is your grade?");
int grade = scnr.nextInt();
if (grade > 100) {
System.out.println("Invalid input");
System.out.println("Please enter another number");
}
else if ((grade >= 93.00 && grade < 100)) {
String line9 = Files.readAllLines(Paths.get("file.txt")).get(9);
System.out.println(9);
break;
}
else if (grade >= 90.0 && grade < 93) {
System.out.print("Your grade is ");
break;
}
else if (grade >= 87.0 && grade < 90) {
System.out.print("Your grade is ");
break;
}
else if (grade >= 83.0 && grade < 87) {
System.out.print("Your grade is ");
break;
}
else if (grade >= 80 && grade < 83) {
System.out.print("Your grade is ");
break;
}
else if (grade >= 77 && grade < 80) {
System.out.print("Your grade is ");
break;
}
else if (grade >= 70 && grade < 77) {
System.out.print("Your grade is ");
break;
}
else if (grade >= 60 && grade < 70) {
System.out.print("Your grade is ");
break;
}
else if (grade <= 59 && grade > 0) {
System.out.print("Your grade is ");
break;// write your code here
}
}
}
}
You don't put a break to end an if clause, the completed curly braces take care of that. The breaks that you have added are causing it to pop out of the while loop. Since you have one on every path of your if .. else if .. else, then you will never process more than the first line.

How can I prevent the user from entering the same text twice

This program basically calculates the gpa, by letting the user enter the number of courses and course code, with the relevant credit and marks. If the course code is entered twice, a message will show (the course is already registered), and it will keep looping until the user has entered all courses with a different course code
I have created two methods. One to check if the code is already registered and the other for calculating the gpa, the first method that checks the user input, I'm not sure about it. Because if I entered the course code twice it will only show the message and would allow me to calculate the rest
public static boolean checkCourse(String[] courseList, String code){
boolean check = false;
for(int i=0 ; i < courseList.length; i++){
if(code.equals(courseList[i]))
check = true;
else
check = false;
}
return check;
}
public static double gradeValue(double marks){
double grade = 1.0;
if(marks >=95){ grade = 5.0;}
else if (marks >= 90) { grade = 4.75;}
else if (marks>=85) { grade = 4.5;}
else if (marks >= 80) { grade = 4.0;}
else if (marks >= 75) { grade = 3.5; }
else if (marks >= 70) { grade = 3.0;}
else if (marks >= 65) {grade = 2.5 ;}
else if (marks >= 60) { grade = 2;}
else if (marks < 60) { grade =1 ;}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit=0;
int sumOfmarks =0;
for(int i =0; i<Courses.length;i++){
System.out.print("Enter a course code: ");
Courses[i] = input.next();
if(checkCourse(Courses,Courses[i])){
System.out.println("the course already registered");
i--;
}
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks +=marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks /sumOfcreadit;
System.out.println("The GPA is: "+gradeValue(TotalMarks));
}
I made some changes in your code and now it works. Changes are described in below code. There was 3 important changes.
I tried to make as less changes as possible to make your code work as expected
public static boolean checkCourse(String[] courseList, String code) {
boolean check = false;
for (int i = 0; i < courseList.length; i++) {
if (code.equals(courseList[i])) { // equals instead of == to compare strings
check = true;
break; // you have to break loop if it is true because else statement before returned false even if there was the same course code due to null values in next array elements which was not filled yet
}
}
return check;
}
public static double gradeValue(double marks) {
double grade = 1.0;
if (marks >= 95) {
grade = 5.0;
} else if (marks >= 90) {
grade = 4.75;
} else if (marks >= 85) {
grade = 4.5;
} else if (marks >= 80) {
grade = 4.0;
} else if (marks >= 75) {
grade = 3.5;
} else if (marks >= 70) {
grade = 3.0;
} else if (marks >= 65) {
grade = 2.5;
} else if (marks >= 60) {
grade = 2;
} else if (marks < 60) {
grade = 1;
}
return grade;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter number of courses: ");
int n = input.nextInt();
String[] Courses = new String[n];
int sumOfcreadit = 0;
int sumOfmarks = 0;
for (int i = 0; i < Courses.length; i++) {
System.out.print("Enter a course code: ");
String code = input.next();
if (checkCourse(Courses, code)){
System.out.println("the course already regestered ");
i--;
continue; // continue is neccessary to let user write value again if it already exists
}
Courses[i] = code;
System.out.print("Enter a credit: ");
int credit = input.nextInt();
System.out.print(" Enter a marks: ");
int marks = input.nextInt();
sumOfcreadit += credit;
sumOfmarks += marks * credit;
}
double TotalMarks;
TotalMarks = sumOfmarks / sumOfcreadit;
System.out.println("The GPA is: " + gradeValue(TotalMarks));
}
Use a set kind of structure to store all the course code visited, It will avoid unnecessary iteration on your course array
this method can be enhanced to
public static boolean checkCourse(HashSet<String> courses, String code){
boolean check = false;
if(courses.contains(code)){
check = true;
else
check = false;
}
return check;
}
Initialise the hashset courses and if the checkCourses method returns false add the course code in courses.
Initialize before loop like this
HashSet<String> courseSet = new HashSet<String>();
your if condition inside loop
if(checkCourse(courseSet,courses[i])){ // check for variable name , name should always start with lower case letter
System.out.println("the course already regestered ");
i--;
// You can use continue if you don't want processing for it
// it will skip the loop iteration and it will go next iteration
}else{
courseSet.add(courses[i]);
}

Struggling to exclude certain numbers from my count?

My programs purpose is to calculate the average, maximum, and minimum of the test scores entered by a user.
Here is the problem I keep running into: My program is built to deny test scores entered that are either below zero or above 100, which it does, but for example, if the user inputed 108, it would say "ERROR: Not a valid test score. " BUT even when the score is denied, it still adds that score to the count, and 108 would be the maximum. If an invalid score is entered, I need for it to be completely excluded from the program.
Can anyone explain how to fix this?
Here is my code.
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class hw {
public static void main(String[] args) {
int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;
int count = 0;
int total = 0;
final int SENTINEL = -1;
int score;
Scanner scan = new Scanner(System.in);
System.out.println("To calculate the class average, enter each test
score.");
System.out.println("When you are finished, enter a -1.");
System.out.print("Enter the first test score > ");
score = scan.nextInt();
while (score != SENTINEL)
{
total += score;
//add one to the count
count++;
//calculate the maximum and the minimum
if (score > maxGrade) {
maxGrade = score;
}
if (score < minGrade) {
minGrade = score;
}
if (score < 0 || score> 100)
System.out.print("ERROR: Not a valid test score. ");
System.out.println(" Enter the next test score > ");
score = scan.nextInt();
}
if (count != 0) {
DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
System.out.println("\nThe class average is "
+ oneDecimalPlace.format((double) (total) / count));
System.out.println("The minimum value is " + minGrade);
System.out.println("The maximum value is " + maxGrade);
} else {
System.out.println("\nNo grades were entered");
}
}
}
You have to add to total, calculate max and min only if 0 < input < 100
import java.util.Scanner;
import java.io.*;
import java.text.DecimalFormat;
public class hw {
public static void main(String[] args) {
int maxGrade = Integer.MIN_VALUE;
int minGrade = Integer.MAX_VALUE;
int count = 0;
int total = 0;
final int SENTINEL = -1;
int score;
Scanner scan = new Scanner(System.in);
System.out.println("To calculate the class average, enter each test score.");
System.out.println("When you are finished, enter a -1.");
System.out.print("Enter the first test score > ");
score = scan.nextInt();
while (score != SENTINEL)
{
if (score < 0 || score> 100)
{
System.out.print("ERROR: Not a valid test score. ");
}
else
{
//add one to the count
count++;
//calculate the maximum and the minimum
if (score > maxGrade) {
maxGrade = score;
}
if (score < minGrade) {
minGrade = score;
}
total += score;
}
System.out.println(" Enter the next test score > ");
score = scan.nextInt();
}
if (count != 0) {
DecimalFormat oneDecimalPlace = new DecimalFormat("0.0");
System.out.println("\nThe class average is "
+ oneDecimalPlace.format((double) (total) / count));
System.out.println("The minimum value is " + minGrade);
System.out.println("The maximum value is " + maxGrade);
} else {
System.out.println("\nNo grades were entered");
}
}
}
Because if you enter 108 as your first input it will go into While Loop as 108!=sentinel and will add 108 to total.
To avoid this just add this as first statement inside While Loop :
If(score>108 || score <0)
{
System.out.println("Invalid score");
continue;
}
So if the score is invalid it will ignore the subsequent lines of code and return to start of While Loop again .

Multiple conditions for a Do..While Loop in Java

right basically I am implementing a do while loop. A user is asked to enter a value, and a value is returned back - this is using nested If statements within the do loop. At the end of the loop I am asking whether they want to enter another value, yes or no basically. Here is my code below, I essentially need a way of when the question is asked at the end to perform like...
"Would you like to enter another value?" - "no" - terminates
"Would you like to enter another value?" - "yes" - loop around
"Would you like to enter another value?" - any other value e.g. "maybe" - ask the question again.
The code:
import java.util.Scanner;
public class More_Grades {
public static void main (String [] args) {
Scanner scan = new Scanner(System.in);
String A = "Your grade is: ";
int grade = 0;
String y;
do {
System.out.println("Please Enter Your Grade: ");
grade = scan.nextInt();
if (grade < 40) {
System.out.println(A+"Fail");
}
else if (grade >= 40 && grade <= 49) {
System.out.println(A+"3rd");
}
else if (grade >= 50 && grade <= 59) {
System.out.println(A="2/2");
}
else if (grade >= 60 && grade <= 69) {
System.out.println(A+"2/1");
}
else if (grade >= 70 && grade < 100) {
System.out.println(A+"1st");
}
else if(grade >100) {
System.out.println("Invalid grade,Enter a value below 100.");
}
System.out.println("Would you like to Enter Another? Y/N");
y = scan.next();
}while (y.equals("yes"));
scan.close();
System.out.println("Thank-You.");
}
}
You just need another do-while inside your current loop to repeat the question:
do {
...
do {
System.out.println("Would you like to enter another? (yes/no)");
answer = scan.next();
} while (!Arrays.asList("yes", "no").contains(answer));
} while (answer.equals("yes");

Categories

Resources