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.
Related
Create a program that randomly generates a number from 1-100 and asks the user to guess it. If the number the user inputs is to low or to high display a message to tell them so. When the user guesses the random number tell the user how much tries it took him to get that number. After that ask the user if they want to do it again if the user does repeat the process with a new random number generated.
The problem is that I can't seem to figure out how to let the user do it again, it seems to display an error in code when I run the program. If anyone can help me with this issue that would be great. Thank you!
import java.util.Scanner;
import java.util.Random;
public class RandomGuess
{
public static void main(String [] args)
{
Scanner keyboard = new Scanner(System.in);
Random randy = new Random();
//#declaring variables
int num, count = 0;
final int random = randy.nextInt(100);
String input;
char yn;
//#random number
System.out.println("Num = " + random);
//#title or header
System.out.println("Random Number Guessing Game");
System.out.println("===========================");
//#asking user for input
do
{
System.out.print("Guess the random number " +
"from 1 to 100===> ");
num = keyboard.nextInt();
//#if the number the user entered
//#was less than the random number
if(num < random)
{
//#display this message
System.out.println("Your guess is too low try again...");
System.out.println();
}
//#if the number the user entered
//#was less than the random number
if(num > random)
{
//#display this message
System.out.println("Your guess is too high try again...");
System.out.println();
}
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
}
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y');
}
while (num > 1 || num > 100);
}
}
There are a couple of problems with your code without even seeing the error that is displayed (I've put comments in those areas):
count++;
if (num == random)
{
System.out.println("You guessed the random number in " +
count + " guesses!");
break;
} // You should put an else here
do
{
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.charAt(0);
}
while(yn == 'Y' || yn == 'y'); // This will keep asking if you want to try again so long as you enter a "y"
// But it won't actually let you try.
// Why? Because if you enter a y" it will loop back to the question.
}
while (num > 1 || num > 100); // This should probably be (random != num)
}
}
Here is a revised version
count++;
if (num == random) {
System.out.println("You guessed the random number in " +
count + " guesses!");
} else {
yn = 'x'; // can be anything other than y or n
while(yn != 'y' && yn != 'n') {
System.out.print("Continue? (Y or N)==> ");
input = keyboard.nextLine();
yn = input.toLowerCase().charAt(0);
}
}
}
while (num != random && yn == 'y');
}
}
Hopefully this is enough to move you forward.
Also, please post the error message and/or a description of what it is doing wrong along with a description as to what you actually wnt it to do.
As for the exception, the problem is that scanner.nextInt does not consume the newline at the end of the numbe you entered. So, your "continue Y/N" question gets what's left over from the previous line (i.e. a new line => an empty string).
You could try this:
num = -1; // Initialise the number to enable the loop
while (num <= 1 || num >= 100) {
System.out.print("Guess the random number from 1 to 100===> ");
String ans = keyboard.nextline();
try {
num = Integer.parseInt(); // Convert the string to an integer - if possible
} catch (NumberFormatException e) {
// If the user's input can not be converted to an integer, we will end up here and display an error message.
System.out.println ("Please enter an integer");
}
}
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";
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");
//Setting my variables.
Scanner keyboard = new Scanner(System.in); // Initalizing keyboard to scanner input
int quarter;
double balance, intrestRate;
boolean correct = false;
//Loop iterations to resolve error, and determine value for each input.
do{ //Beginning loop for number of quarters, must be between 1-10
System.out.println("Enter a number between 1 and 10 for the amount of quarters");
quarter = keyboard.nextInt();
if(quarter >= 1 && quarter <= 10) //If quarter is between 1 and 10
{
System.out.println("You have " + quarter + " quarters.");
correct = true;
}
else
{
System.out.println("Number of quarters must be between 1 and 10");
correct = false;
}
}while(!correct);
do{ //Second loop for rate of intrest.
System.out.println("Enter intrest rate without percent a sign. Must be greaters than 5% and less than 25%.");
intrestRate = keyboard.nextDouble();
if (intrestRate >= 5 && intrestRate <=25)
{
System.out.println("You have selected a " + intrestRate + "% rate of intrest.");
correct = true;
}
else
{
correct = false;
}
}while(!correct);
}
}
So, this is my code. I'm experimenting with loops, and if-else type statements. I feel like, MY approach is way to complicated and could be easily summarized or revised period. Does anyone know how to approach with, with only declaring one do statement? This code is just in the beginning phases of my experiment and has much work to do. But before I move on, I was hoping for another set of eyes!
Use of infinite loop with break on valid input. Enhanced to handle bad input.
Scanner keyboard = new Scanner(System.in);
int quarter;
while (true) {
System.out.print("Enter number of quarters (1-10): ");
if (keyboard.hasNextInt() && (quarter = keyboard.nextInt()) >= 1 && quarter <= 10)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Number of quarters must be between 1 and 10");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have " + quarter + " quarters.");
double intrestRate;
while (true) {
System.out.print("Enter interest rate (5%-25%), without percent sign: ");
if (keyboard.hasNextDouble() && (intrestRate = keyboard.nextDouble()) >= 5 && intrestRate <= 25)
break;
keyboard.nextLine(); // Discard bad input
System.out.println("Interest rate must be between 5% and 25%");
}
keyboard.nextLine(); // Discard rest of line
System.out.println("You have selected a " + intrestRate + "% rate of interest.");
I took an excerpt of my code that needs working on, I know its standard practice to post all of the code but I dont think its needed here.
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision = sob.next();
if(decision.equals("Y") || decision.equals("y")){
continue;
}else if(decision.equals("N") || decision.equals("n")){
break;
}
}
}
How how I change this statement to either accept a Y or N, as right now if I input anything bar them two character, it will continue as if I have pressed Y.
You should have an else case:
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision = sob.next();
if(decision.equalsIgnoreCase("Y")){
continue;
}else if(decision.equalsIgnoreCase("N")){
break;
}
else
{
//whatever you want to happen if they don't enter either y or n
}
}
}
Maybe in the else have another loop that says please enter a valid input and keep looping until they give a valid input...
Here is how you can change your code to "insist" on the user to enter a Y or a N:
static void readYesOrNo(Scanner input) {
String str;
while (true) {
str = input.next();
if (str.equalsIgnoreCase("y")) {
return true;
}
if (str.equalsIgnoreCase("n")) {
return false;
}
System.out.println("Please enter Y or N");
}
}
I put this code into a static method so that you could reuse it in other places. Now you can use this method in your code like this:
if(playerValue > 10 && playerValue < 21){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
if (readYesOrNo(sob)) {
continue;
}
break;
}
You Can Try This:
if(playerValue > 10 && playerValue < 21){
while(true){
System.out.println("Players Value so far " + playerValue + ", Do you want to draw another card? Y/N");
// input a y or n answer
decision=sob.next();
if(decision!=null && (decision.equalsIgnoreCase("y")||decision.equalsIgnoreCase("n"))){
break;
}
else{
System.out.println("please answer with Either y or n");
continue;
}
}//end of while loop
//put your code here
}