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");
Related
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;
}
}
I am incredibly new to Java and this is actually my first project. I've been googling and reading and trial and error-ing things for days and I am still stuck on two things.
I'm sure they're incredibly easy questions and I feel dumb for asking, but I'm getting frustrated!
1) I need to do a conditional statement that is joined by a short circuit && that will result in any input under 0 and over 100 being an error. However I don't see how this is possible since a number can't be less than 100 AND over 100. Am I missing something?
2) I'm not sure what I have to do to be able to assign a String variable the value of 'error'. I feel like this should be super easy but I can't get it...I just know I can't have it be a print statement.
Thank you so much for any input/advice, I really appreciate it!
import java.util.Scanner;
public class Project {
public static void main(String[] args) {
char letter;
Scanner input = new Scanner(System.in);
System.out.print("Please input your score.");
int score = input.nextInt();
if (score >= 90)
{
System.out.println("You have earned the letter grade: A");
}// end if for age >=90
else if (score >= 80)
{
System.out.println("You have earned the letter grade: B");
} // end else if for >=80
else
{
if (score >= 70)
{
System.out.println("You have earned the letter grade: C");
}// end if for age >=70
else
{
if (score >= 60)
{
System.out.println("You have earned the letter grade: D");
}// end if for >=60
else
{
System.out.println("You have earned the letter grade: F");
}
}
}
}
}
1) You have to use the correct operator ||.
if (score < 0 || score > 100) { ... }
2) In Java single quotes '' are used for chars and double quotes "" are used for Strings.
String s = "error";
do {
loop = false;
if (userInput.equalsIgnoreCase("Score")){
System.out.println("You have chose to input a score.\nEnter your score here: ");
score = kbInput.nextDouble();
System.out.println("What was the best possible score?");
total = kbInput.nextDouble();
finalScore = score / total * 100;
percent = (finalScore + "%");
if (finalScore >= 90){
grade = 'A';
} else if (finalScore >= 80){
grade = 'B';
} else if (finalScore >= 70){
grade = 'C';
} else if (finalScore >= 60){
grade = 'D';
} else {
grade = 'F';
}
System.out.println("You got " + percent + ". Which is a letter grade '" + grade + "'.");
loop = false;
} else if (userInput.equalsIgnoreCase("Percent")) {
System.out.println("You have chosen to input a percent.\nEnter your percent here: ");
finalScore = kbInput.nextDouble();
if (finalScore >= 90){
grade = 'A';
} else if (finalScore >= 80){
grade = 'B';
} else if (finalScore >= 70){
grade = 'C';
} else if (finalScore >= 60){
grade = 'D';
} else {
grade = 'F';
}
System.out.println("You got a letter grade '" + grade + "'.");
loop = false;
} else {
System.out.println("Sorry, I don't understand that.");
loop = true;
}
} while (loop = true);
I am fairly new to Java and I have been taking a class and doing mini projects on my own. My plan was to have the code loop back to the beginning whenever you reached the final if statement due to entering an invalid string (i.e. anything besides Score and Percent). I can't seem to figure out what is wrong, it only loop sections of the if / else statements.
You have made a classic mistake that Java newbies make. You intended to use ==, but accidentally miss-typed it as =. You could fix the typo, but there is a BETTER solution that will avoid this problem in the future.
You should not use == to test booleans. Instead, you should rewrite your code as per the following pattern:
while (loop = true) { // BUG!!!
while (loop == true) { // WRONG
while (loop) { // CORRECT
while (loop = false) { // BUG!!
while (loop == false) { // WRONG
while (!loop) { // CORRECT
This advice applies to pretty much every use of == with boolean operands. (The exception is op1 == op2 where neither op1 or op2 are boolean literals.)
UPDATE
There are also problems with the way you get input from the user.
You are not reading userInput within the loop. That might be a problem, depending on the requirements, and on whether / how it was initialized prior to the start of the loop.
If the user enters a bad floating point number, you will get an exception. This includes the case where the user enters something like "100.0 points".
You don't validate the inputs; e.g. test for negative scores, scores greater than the maximum, percentages outside of the range 0..100.
Finally, the way you are terminating the loop is clunky. It would be better to do something like this:
while (true) {
// do stuff
if (...) {
// we want to terminate the loop
break; // <<------
}
// do more stuff
}
Since you are still struggling to understand, here is a "sample solution" to the programming problem:
import java.util.Scanner;
import java.util.NoSuchElementException;
public class Example {
public static void main(String[] args) {
Scanner kbdInput = new Scanner(System.in);
String mode = "";
double percent = -1;
while (true) {
System.out.println("Enter 'score' or 'percent': ");
mode = kbdInput.next().toLowerCase();
kbdInput.nextLine();
if (mode.equals("score") || mode.equals("percent")) {
break;
}
System.out.println("I don't understand that. Try again.");
}
while (true) {
try {
if (mode.equals("score")){
System.out.println("You chose to input a score.");
System.out.println("Enter it here: ");
double score = kbdInput.nextDouble();
kbdInput.nextLine();
System.out.println("What is the best score?");
double total = kbdInput.nextDouble();
kbdInput.nextLine();
percent = score / total * 100;
if (score >= 0.0 && total > 0.0 &&
percent >= 0.0 && percent <= 100.0) {
break;
}
System.out.println("The score / best score you " +
"gave make no sense.");
} else if (mode.equals("percent")) {
System.out.println("You chose to input a percent.");
System.out.println("Enter it here: ");
percent = kbdInput.nextDouble();
kbdInput.nextLine();
if (percent >= 0.0 && percent <= 100.0) {
break;
}
System.out.println("The percent you gave is not " +
"between 0 and 100.");
}
} catch (NoSuchElementException ex) {
kbdInput.nextLine();
System.out.println("You entered an invalid number.");
}
System.out.println("Try again.");
}
if (percent >= 0.0 && percent <= 100.0) {
char grade;
if (percent >= 90){
grade = 'A';
} else if (percent >= 80){
grade = 'B';
} else if (percent >= 70){
grade = 'C';
} else if (percent >= 60){
grade = 'D';
} else {
grade = 'F';
}
System.out.println("You got " + percent +
"%. Which is a letter grade '" + grade + "'.");
}
}
}
The things to note:
I have split this into two loops. One to request and validate the "mode" of inputting the scores. And the second to actually input them. (I have inferred this was a requirement from your code. That may not be correct.)
There is a lot more validation of the inputs than in your version.
I have used kbdInput.nextLine() to "consume" unwanted input in a few places. Note that the next methods leave any input characters that they don't want or can't recognize in the input buffer. If you are not careful, the next call to nextXxxx will attempt to parse the same characters all over again.
I explicitly catch and deal with errors in entering numbers; see the exception handler.
I have moved common code to calculate and display the grade to the end.
I have changed your multi-line println statements into separate statements. There is a good reason for this.
"\n" is not always the correct way to output a line break. It depends on the execution platform
println will do it correctly, assuming that the output is destined for the same machine that the code is running on.
See also: System.out.println() vs \n in Java
Finally, this code will NOT deal with the case where the user enters an END-OF-FILE at the keyboard (e.g. ^D on Linux).
Exercise: See what happens if you do that. Work out what happens, and find an appropriate fix for it.
My Goal: To make a program that can check if the number you guessed is correct. It will tell you if it's too high/low. It needs to continue giving you chances until you guess correctly. Also, it needs to be able to resume from the start after you finish if you want to.
Problem: My if statements are stuck in an infinite loop, and attempting to restart the program at the end does not work at all.
import java.util.Random;
import java.util.Scanner;
public class driver {
public static void main (String [] args) {
// Output number of guesses.
Scanner scan = new Scanner(System.in);
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(100) + 1;
System.out.println(randomInt);
System.out.println("Welcome to my guessing game. What is your first guess that is between 1 and 100?");
int userInput = scan.nextInt();
String playAgain = "Y";
int guesses = 0;
System.out.println(randomInt);
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
// Too low
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
// Too high
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
// I want to be able to resume from the top if the user says Y.
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
The last two lines should be inside your while loop, the problem is with your braces
while (playAgain == "Y") {
if (userInput > 0 && userInput < 100) {
if (userInput == randomInt){
guesses++;
System.out.println ("Right! Guesses: " + guesses);
playAgain = "f";
}
else if (userInput < randomInt) {
guesses++;
System.out.println ("Your guess was too LOW.");
}
else {
System.out.println ("Your guess was too HIGH.");
guesses++;
}
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
The bottom part should look like:
guesses++;
}
}
System.out.println("Would you like to play again?(Y/N)");
playAgain = scan.next();
}
}
The way it was means that the condition of your while is never updated. I assume you want it to update after each input from the user.
Sorry if the code looks a bit messy from here. It's my first time posting, and wasn't sure how to format it for the site as I'm under a time constraint.
I'm in quite a bind here. I've been trying to figure this out for quite a number of hours now, but can't seem to get around to solve it. I'm new to Java, so don't mind the code if it's a bit out of order, messy, or if it's a bit too long for what it does. My problem lies in the first few lines, under:
"Scanner input = new Scanner(System.in);"
I was able to get the if statements working properly under the condition a number above or below 0 / 99 was entered, but if a number in between those two are entered, nothing happens. I searched in my textbook (Intro to Java Programming Comprehensive 10th edition), and can't seem to pinpoint the issue. Is there a way to have the program continue past the "if" statements and onto the lines of code that involve "input2"?
Thanks in advance!
package lab03;
import java.util.Scanner;
public class Lab03 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer between 0-99: ");
int input1 = input.nextInt();
if (input1 < 0 || input1 > 99)
System.out.println(" Outside range. Please enter an integer between 0-99: ");
input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
System.out.println("Next, please enter another integer between 0-99: ");
int input2 = input.nextInt();
if (input2 < 0 || input2 > 99)
System.out.println(" Outside range. Please enter an integer between 0-99: `enter code here`");
input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
I would put them in a while(scanner.hasNextInt()) loop and then if the condition is met call continue and it will go back to the beginning of the while loop.
The problem is that those statements aren't reachable because you call System.exit(). if statements execute the next line beneath them OR everything inside the braces. As you can see you have an open brace, but you don't actually post the code where the brace closes. That means that everything below the following line will execute, including System.exit().
if (input1 < 0 || input1 > 99) {
Your current program can be simplified to
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter an integer between 0-99: ");
int input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: ");
}
input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
// everything below this will never execute
}
}
I think you are missing curly braces that define the scope of what happens as a result of your first if statement. You probably mean something like this
if (input1 < 0 || input1 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: ");
input1 = input.nextInt();
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
}
}
but what is actually happening is that the program is waiting for a second try to input input1.
Basically, you've wrapped your "continued" condition within your "failed" condition if block...
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
// This is included within the failed block
// but will never execute because of the previous statement
System.out.println("Next, please enter another integer between 0-99: ");
int input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: `enter code here`");
}
input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
}
}
You should have a else condition which you want to execute when the if condition "fails" to be meet
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
} else {
// This is included within the failed block
// but will never execute because of the previous statement
System.out.println("Next, please enter another integer between 0-99: ");
int input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: `enter code here`");
}
input2 = input.nextInt();
if (input2 < 0 || input2 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);
}
}
Remember {...} adds context to the code which it surrounds
Depending on what you want to achieve, you can also use a do-while loop to "trap" the user in a input loop, until they enter the correct value...
int input1 = -1;
do {
System.out.println("Please enter an integer between 0-99: ");
String text = input.nextLine();
try {
input1 = Integer.parseInt(text);
if (input1 < 0 || input1 > 99) {
System.out.print("Outside range. ");
}
} catch (NumberFormatException exp) {
System.out.println(text + " is not a valid numerical value");
}
} while (input1 < 0 || input1 > 99);
Now, remember, this will trap them until they enter a value between 0 and 99 inclusively, so you might want to consider adding a "escape" condition (ie "(type 'e' to exit) and then either break out of the loop or exit the program ;)
Your current code only works for numbers that are greater than 99 and less than 0. You need an else statement for numbers that are between 0 and 99 for the program to continue.
if (input1 < 0 || input1 > 99) {
System.out.println(" Outside range. Please enter an integer between 0-99: ");
input1 = input.nextInt();
}else{
//Continue on with program
}
if (input1 < 0 || input1 > 99) {
System.out.println("Outside range. Program ending.");
System.exit(0);