My code is supposed to ask the user to input a number between 1 and 10. If they input a number between 1 and 10, then it will say thank you and end there. If not, it should loop and say, Please input a number between 1 and 10, and Please try again. It will then make the user input again. My problem is that after the second input, it automatically ends the loop even if they make an incorrect input the second time. By the way, I am very new to coding so please go easy on me in the comments XD. Someone, please help, thanks.
Here is my code:
import javax.swing.*;
public class LoopLecture {
public static void main(String[] args) {
int MIN = 1;
int MAX = 10;
String rating;
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
int rating2 = Integer.parseInt(rating);
while (rating2 < MIN || rating2 > MAX) {
JOptionPane.showMessageDialog(null, "You must enter a value between " + MIN + "and" + MAX + ".");
JOptionPane.showMessageDialog(null, "Please try again.");
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
if (rating2 >= MIN && rating2 <= MAX)
break;
}
JOptionPane.showMessageDialog(null, "Thank you!");
}
}
Within for loop try assigning the new value to the rating2
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabby
rating2 = JOptionPane.showInputDialog(null, "Please enter your rating of Krabby
while (true) { // creates infinite while loop
break; // ends an infinite loop
}
You have a break; expression in your if statement, so I'm sure you understand how it works, but try just making the loop infinite, like shown above.
more better may to solve it:
parse rating to rating2 in loop
break if number between 1 and 10
catch NumberFormatException, no need do anything, just ignore it
public static void main(String[] args) {
int MIN = 1;
int MAX = 10;
String rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
while (true) {
try {
int rating2 = Integer.parseInt(rating);
if (rating2 >= MIN && rating2 <= MAX) {
break;
}
} catch (NumberFormatException ignored) {
}
JOptionPane.showMessageDialog(null, "You must enter a value between " + MIN + "and" + MAX + ".");
JOptionPane.showMessageDialog(null, "Please try again.");
rating = JOptionPane.showInputDialog(null, "Please enter your rating of Krabbypatties on a scale of"
+ MIN + "to" + MAX + ".With" + MIN + "meaning youhated it and" + MAX + "meaning you loved it.");
}
JOptionPane.showMessageDialog(null, "Thank you!");
}
Related
one problem I noticed is that the program crashes if you enter non digits even though there is a catch statement. can someone help me out? I can't seem to find the problem.
Can you also explain what I'm doing wrong and why it's wrong? Thank you in advance.
//previous code had an issue while I was creating a new scanner. it's correct now.
import java.util.*;
public class HighLow {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int numberOfAttempts = 0;
System.out.println("WIN THE THREE ROUNDS TO WIN THE GAME!.");
int theNumber = (int) (Math.random() * 10 + 1);
System.out.println("Round 1: I am thinking of a number between" + "\n" + "1 and 10, can you guess the number in " + "\n" + "less than 3 attempts?");
System.out.println("Type a number below and press enter.");
int guess = 0;
do {
try {
guess = scan.nextInt();
if (guess != theNumber) {
if (guess < theNumber) {
System.out.println("Sorry " + guess + " is too low, please try again");
}else if (guess > theNumber) {
System.out.println("Sorry " + guess + " is too high, please try again." );
}
numberOfAttempts = numberOfAttempts + 1;
}else {
System.out.println(guess + " is the correct answer. You got it on" + "\n" + "attempt number " + (numberOfAttempts + 1) + ". Proceeding to round 2.");
theNumber = (int) (Math.random() * 100 + 1);
System.out.println("\n" + "Round 2: I am thinking of a number between " + "\n" + "1 and 100, can you guess the number in " + "\n" + "less than 6 attempts?");
numberOfAttempts = 0;
int secondRoundGuess = 0;
do {
try {
secondRoundGuess = scan.nextInt();
if (secondRoundGuess != theNumber) {
if (secondRoundGuess < theNumber) {
System.out.println("Sorry " + secondRoundGuess + " is too low, please try again");
}else{
System.out.println("Sorry " + secondRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}
else {
System.out.println(secondRoundGuess + " is the correct answer. You got it on " + "\n" + "attempt number " + (numberOfAttempts + 1) + "." + "\n" + "Proceeding to round 3.");
System.out.println("\n" + "Round 3: I am thinking of a number between " + "\n" + "1 and 1000, can you guess the number in " + "\n" + "less than 10 attempts?");
theNumber = (int)(Math.random() * 1000 + 1);
numberOfAttempts = 0;
int thirdRoundGuess = 0;
do {
try {
thirdRoundGuess = scan.nextInt();
if (thirdRoundGuess != theNumber) {
if (thirdRoundGuess < theNumber) {
System.out.println("Sorry " + thirdRoundGuess + " is too low, please try again");
}else {
System.out.println("Sorry " + thirdRoundGuess + " is too high, please try again");
}
numberOfAttempts = numberOfAttempts + 1;
}else{
System.out.println(thirdRoundGuess + " is the correct answer.");
System.out.println("You won the game, you are a badass." + "\n" + "I made this game and I cant even beat " + "\n" + "level 3.");
System.out.println("I am a newbie at programming and it's my " + "\n" + "fourth month on this java journey ." + "\n" + "I am looking for fellow newbies who are willing " + "\n" + "to learn and grow together (or advanced programmers " + "\n" + "who will not get annoyed by teaching newbies)." + "\n" + "If you get to this point in the game " + "\n" + "and see this message, hit me up via direct " + "\n" + "messaging, lets create a group where we can learn " + "\n" + "and grow together.");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
thirdRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 10);
System.out.println("Game over, you were so close. Try again");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
secondRoundGuess = scan.nextInt();
}
}while(numberOfAttempts != 6);
System.out.println("Game Over. Try again?");
}
}catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
}while (numberOfAttempts != 3);
System.out.println("Game Over. Try again?");
scan.close();
}
}
The root cause of the problem is using scan.nextInt() inside the catch block. What is happening is guess = scan.nextInt(); just below the try is throwing an exception for non-integer input and the control enters the catch block where it encounters guess = scan.nextInt(); again which tries to consume the Enter from the last input causing the program to crash as Enter is not an int.
How to get rid of it?
You need to make two changes to get rid of the problem:
A. Use guess = Integer.parseInt(scan.nextLine()); in which scan.nextLine() will also consume Enter.
B. Comment out the line, guess = scan.nextInt(); as shown below:
} catch (Exception e) {
System.out.println("Please enter a number.");
//guess = scan.nextInt();
}
This is the exception stack trace you get when you run the code:
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at HighLow.main(HighLow.java:137)
When you handle the exception first time the user types in a non-numeric value, the exception gets handled below:
catch(Exception e) {
System.out.println("Please enter a number.");
guess = scan.nextInt();
}
When it reaches guess = scan.nextInt();, the previous non-numeric value is still present in the scanner. And when it tries to get an integer out of the scanner when it has a non-numeric value, it throws another InputMismatchException inside catch that is not handled.
Having issues with trying to get this to run and ask the user for their guess, then if it's too low, it states too low, or too high, or correct. Then states what the number was. This is the code I have so far.
import javax.swing.JOptionPane;
public class RandomGuess2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int random;
final int MIN = 1;
final int MAX = 10;
int userNum;
String userInput;
userInput = JOptionPane.showInputDialog(null, "Please guess a number between 1 and 10");
random = 1 + (int)(Math.random() * MAX);
userNum = Integer.valueOf(userInput);
int userDiff = (random - userNum);
if (userDiff < 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH");
if (userDiff > 0)
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");
if (userNum == random)
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!");
else
JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!");
}
}
}
Any help would be very much appreciated!
The Reason it wasn't working was because your checking was wrong it needs to be like this
if (userNum == random){
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!");
}
else{
if (userDiff < 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH");
}
if (userDiff > 0)
{
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");
}
JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!");
}
yours was checking first to see if the usernum was too high and if it was then it would check to see if the usernum was correct or to too low but that code only ran if the num was too high.
Your if-else-structure is not right. I guess this is what you want:
if (userDiff < 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO HIGH");
} else if (userDiff > 0) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is TOO LOW");
}
if (userNum == random) {
JOptionPane.showMessageDialog(null, "Your guess of " + userNum + " is correct! Congratulations!");
} else {
JOptionPane.showMessageDialog(null, "The number was " + random + "\nTry again Next time!");
}
I made this program for my class, but when it runs it just randomly sorts the name and does not sorts them in numerical order (ascending). I don't know if I have any mistakes but I'm guessing the problem is in the "ifs" below:
import javax.swing.JOptionPane;
public class RaceOrderApp {
public static void main(String[] args) {
String racer1, racertime1str, racer2, racertime2str, racer3, racertime3str;
int racerTime1, racerTime2, racerTime3;
racer1 = JOptionPane.showInputDialog(null, "Enter the name of racer #1:" );
if (racer1 == null || racer1.length() == 0) {
JOptionPane.showMessageDialog(null, "You did not enter a name. The application will end.");
System.exit(1);}
racertime1str = JOptionPane.showInputDialog(null, "Enter the time of " + racer1 + ":" );
racerTime1 = Integer.parseInt(racertime1str);
if (racerTime1 >= 15 || racerTime1 <= 100) {
JOptionPane.showMessageDialog(null, "You did not enter a valid time. The application will end.");
System.exit(1);}
racer2 = JOptionPane.showInputDialog(null, "Enter the name of racer #2:" );
if (racer2 == null || racer2.length() == 0) {
JOptionPane.showMessageDialog(null, "You did not enter a name. The application will end.");
System.exit(1);}
racertime2str = JOptionPane.showInputDialog(null, "Enter the time of " + racer2 + ":" );
racerTime2 = Integer.parseInt(racertime2str);
if (racerTime2 >= 15 || racerTime2 <= 100) {
JOptionPane.showMessageDialog(null, "You did not enter a valid time. The application will end.");
System.exit(1);}
racer3 = JOptionPane.showInputDialog(null, "Enter the name of racer #3:" );
if (racer3 == null || racer3.length() == 0) {
JOptionPane.showMessageDialog(null, "You did not enter a name. The application will end.");
System.exit(1);}
racertime3str = JOptionPane.showInputDialog(null, "Enter the time of " + racer3 + ":" );
racerTime3 = Integer.parseInt(racertime3str);
if (racerTime3 >= 15 || racerTime3 <= 100) {
JOptionPane.showMessageDialog(null, "You did not enter a valid time. The application will end.");
System.exit(1);}
String firstRacer = racer1 + " " + racerTime1;
String secondRacer = racer2 + " " + racerTime2;
String thirdRacer = racer3 + " " + racerTime3;
if (racerTime1 > racerTime2) {
String temp = firstRacer;
firstRacer = secondRacer;
secondRacer = temp;
}
if (racerTime2 > racerTime3) {
String temp = secondRacer;
secondRacer = thirdRacer;
thirdRacer = temp;
}
if (racerTime1 > racerTime2 ) {
String temp = firstRacer;
firstRacer = secondRacer;
secondRacer = temp;
}
String mensaje="The order of the racers is:\n";
mensaje += "1st. " + firstRacer + "\n";
mensaje += "2nd. " + secondRacer + "\n";
mensaje += "3rd. " + thirdRacer + "\n";
JOptionPane.showMessageDialog(null, mensaje);
}
}
Thanks in advance to anybody who can help!
You've got a problem with you if statements
(racerTime2 >= 15 || racerTime2 <= 100) has something wrong with the signs
It says if bigger than 15 or smaller than 100, it must be bigger than 100 or smaller than 15 as of:
if (racerTime2 <= 15 || racerTime2 >= 100)
All your if statements should end with ; as you are not using else or else if
I am having 2 main issues. the first is I cannot make it loop back around for another persons details to be input. the second is I cannot get the shortestHight or shortestName to be recorded. (This is an assignment, I would like help and not the answer please)
{
System.out.println("Do you want to enter another person? Y/N ");
answer = KB.next();
while ("yes".equals(answer) || "Yes".equals(answer));
System.out.println("Enter a Name ");
name = KB.next();
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
while (hight <= 0.8 || hight >= 2.5)
{
System.out.println(name + "must be between 0.8 and 2.5 meters");
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
}
}
if (hight >= tallestHight)
{
tallestHight = hight;
tallestName = name;
}
else if (hight <= shortestHight)
{
shortestHight = hight;
shortestName = name;
}
System.out.println("The tallest persone is " + tallestName + " at a hight of " + tallestHight);
System.out.println("And The shortest persone is " + shortestName + " at a hight of " + shortestHight);
}
}
What is wrong is this:
while ("yes".equals(answer) || "Yes".equals(answer));
This will not result in waiting for another input. It will hang your program as soon as someone enters Yes or yes. It means while answer is yes do nothing. And it will do nothing forever (as answer won't change when application is doing nothing).
I think it should look like this:
boolean getAnotherPerson = true;
do
{
System.out.println("Enter a Name ");
// and so on.
System.out.println("And The shortest persone is " + shortestName + " at a hight of " + shortestHight);
System.out.println("Do you want to enter another person? Y/N ");
answer = KB.next();
if ("n".equalsIgnoreCase(answer) || "no".equalsIgnoreCase(answer))
{
getAnotherPerson = false;
}
} while (getAnotherPerson);
And as for shortest person: it will not work with only one person inserted because your using if-else. So you either update highest or shortest person info. Remove the else keyword and it should be fine.
Changes are mentioned in comments
String tallestName, shortestName;
double tallestHight = Double.MIN_VALUE, shortestHight = Double.MAX_VALUE;
while (true)
{
System.out.println("Do you want to enter another person? Y/N ");
answer = KB.next();
// this would loop infinitely if "Yes" or "yes" entered
// while ("yes".equals(answer) || "Yes".equals(answer));
// instead you might want this - exit if yes not entered
if (!(answer.equals("yes") || (answer.equals("Yes"))) {
break;
}
System.out.println("Enter a Name ");
name = KB.next();
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
while (hight <= 0.8 || hight >= 2.5)
{
System.out.println(name + "must be between 0.8 and 2.5 meters");
System.out.println("Enter " + name + "'s hight in meters");
hight = KB.nextFloat();
}
// compare within loop not outside
if (hight >= tallestHight)
{
tallestHight = hight;
tallestName = name;
}
// only if - not else if as they are 2 separate comparisons
if (hight <= shortestHight)
{
shortestHight = hight;
shortestName = name;
}
}
System.out.println("The tallest persone is " + tallestName + " at a hight of " + tallestHight);
System.out.println("And The shortest persone is " + shortestName + " at a hight of " + shortestHight);
I'm trying to teach myself Java and running into a little hiccup just two chapters into the book I got :P This is one from one of the exercises:
"Write a class that calculates and displays the conversion of an entered number of dollars into currency denominations---20s, 10s, 5s, and 1s."
I'm going on four hours of reading from 0 knowledge of coding thus far so hopefully this doesn't sound too simple a question to answer. I'm sure there's a much more efficient way of writing this entire thing, but my question pertains to how I can terminate the entire thing if the user answers "yes" or continue on with the revised version if they answer "no"?
Also any advice or guidance you guys can give me on learning Java would be much appreciated!
Thanks for taking the time to read this
import javax.swing.JOptionPane;
public class Dollars
{
public static void main(String[] args)
{
String totalDollarsString;
int totalDollars;
totalDollarsString = JOptionPane.showInputDialog(null, "Enter amount to be converted", "Denomination Conversion", JOptionPane.INFORMATION_MESSAGE);
totalDollars = Integer.parseInt(totalDollarsString);
int twenties = totalDollars / 20;
int remainderTwenty = (totalDollars % 20);
int tens = remainderTwenty / 10;
int remainderTen = (totalDollars % 10);
int fives = remainderTen / 5;
int remainderFive = (totalDollars % 5);
int ones = remainderFive / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties + "\nTen Dollar Bills: " + tens + "\nFive Dollar Bills: " + fives + "\nOne Dollar Bills: " + ones);
int selection;
boolean isYes, isNo;
selection = JOptionPane.showConfirmDialog(null,
"Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
isYes = (selection == JOptionPane.YES_OPTION);
JOptionPane.showMessageDialog(null, "You responded " + isYes + "\nThanks for your response!");
isNo = (selection == JOptionPane.NO_OPTION);
int twenties2 = totalDollars / 20;
int tens2 = totalDollars / 10;
int fives2 = totalDollars / 5;
int ones2 = totalDollars / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2);
}
}
First of all, you don't really seem to need the two booleans for isYes and isNo. Basically you asking the user whether he wants a different solution, that is one true/false value (or rather: isNo is the same as !isYes since the option pane will only return one of the values YES_OPTION and NO_OPTION).
What you'll want to do next is go to your 'refined' version if the user indicates that the first output was not what he wanted:
int selection = JOptionPane.showConfirmDialog(null,
"Is this how you wanted the total broken down?", "Select an Option", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (selection == JOptionPane.NO_OPTION) {
int twenties2 = totalDollars / 20;
int tens2 = totalDollars / 10;
int fives2 = totalDollars / 5;
int ones2 = totalDollars / 1;
JOptionPane.showMessageDialog(null, "Total Entered is $" + totalDollarsString + "\n" + "\nTwenty Dollar Bills: " + twenties2 + "\nTen Dollar Bills: " + tens2 + "\nFive Dollar Bills: " + fives2 + "\nOne Dollar Bills: " + ones2);
}
If the user selects 'Yes', your main method is done anyway, so there's no need to do anything in this case.