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!");
}
Related
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!");
}
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.
I wrote a program that asks for user input (numbers), then tells the user which of the two numbers they put in are bigger after making sure both values are numbers. This is looped. The problem is, when the user enters something that isn't valid, the program shuts down instead of referring to my else statements. I think this is because text values in strings cannot be processed using parseInt() so instead of the program realizing that a text value isn't a valid number, it just fails. I am using BlueJ to make this program if that helps anyone solve the problem. I am also open to people telling me how to make my program more efficient/easier to code (I am a beginner).
import java.util.Scanner;
public class TemperatureDriver {
public static void main(String[] args) {
while (true) {
Scanner keyInput = new Scanner(System.in);
System.out.print("Enter a number"+ "\n");
String number_one = keyInput.next();
if (Integer.parseInt(number_one) <=0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if(Integer.parseInt(number_two) <=0 || Integer.parseInt(number_two) > 0){
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) < Integer.parseInt(number_two)){
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if(Integer.parseInt(number_one) == Integer.parseInt(number_two)){
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
} else {
System.out.println("Invalid number!"+ "\n");
}
}
}
}
Your code where you call parseInt should be embedded in a try block, which should be followed by a catch block to catch the NumberFormatException.
try {
if (Integer.parseInt(number_one) <= 0 || Integer.parseInt(number_one) > 0) {
System.out.print("Enter another number" + "\n");
String number_two = keyInput.next();
if (Integer.parseInt(number_two) <= 0 || Integer.parseInt(number_two) > 0) {
if (Integer.parseInt(number_one) > Integer.parseInt(number_two)) {
System.out.print(number_one + " is greater than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) < Integer.parseInt(number_two)) {
System.out.print(number_one + " is less than " + number_two + "\n" + "\n");
} else if (Integer.parseInt(number_one) == Integer.parseInt(number_two)) {
System.out.print(number_one + " is equal to " + number_two + "\n" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} else {
System.out.println("Invalid number!" + "\n");
}
} catch (NumberFormatException e) {
System.out.println("Not a valid number");
}
For this I wanted to print out the frequencies of the amount of times each types of car was chosen... however, as I run the program, its printing out a 0 (for frequency) each time I chose honda for example.
It would be better to print out a table of all frequencies at the end of each program, however I'm just not sure how to get there.
public static void main(String[] args) {
int prompt;
int[] carsValues = new int[5];//didnt want to use 0
do{
prompt = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter"
+ "\n"
+ "1 For Honda"
+ "\n"
+ "2 For Toyota"
+ "\n"
+ "3 For Ford"
+ "\n"
+ "4 For Chevrolet"
+ "\n"
+ "5 For Kia"
+ "\n"
+ "6 To Quit"));
if (prompt == 1)
{
display(carsValues);
int n = 1;
carsValues[n]++;
display(carsValues);
};
if (prompt == 2)
{
display(carsValues);
int n = 2;
carsValues[n]++;
display(carsValues);
};
if (prompt == 3)
{
display(carsValues);
int n = 3;
carsValues[n]++;
display(carsValues);
};
if (prompt == 4)
{
display(carsValues);
int n = 4;
carsValues[n]++;
display(carsValues);
};
if (prompt ==5)
{
display(carsValues);
int n = 5;
carsValues[n]++;
display(carsValues);
}
if (prompt >= 7)
{
JOptionPane.showMessageDialog(null, "Unrecognizable Command"
+ "\n"
+ "Error: Entered Option Is Greater Than The Choice of 5"
+ "\n"
+ "Try Again"
+ "\n");
};
if (prompt <= 0)//child proofing
{
JOptionPane.showMessageDialog(null, "Unrecognizable Command"
+ "\n"
+ "Error: Entered Option Is A 0 Or A Negative"
+ "\n"
+ "Try Again"
+ "\n");
};
}while(prompt!= 6);
}
public static void display(int[] input){
try{
int miles, gallons, mpg;
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
if (miles <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
}
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
if (gallons <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
}
mpg = miles/gallons;
JOptionPane.showMessageDialog(null, String.format("MPG Turns Out To Be %n" + mpg));
}catch(ArithmeticException mathError){
JOptionPane.showMessageDialog(null, "Division by Zero"
+ "\n"
+ "Can't Do That");
}
for(int counter = 0; counter < input.length; counter++){
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"+(input[counter]));
break;// bad idea
}
}
}
because carsValues[0] is never increased and yet you print only carsValues[0] every time. look at the break in the for loop:
for(int counter = 0; counter < input.length; counter++){
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"+(input[counter]));
break;// bad idea
}
In your example, the last loop:
for(int counter = 0; counter < input.length; counter++){
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"+(input[counter]));
break;// bad idea
The loop breaks after 0 everytime, and carsValues[0] is never used. So your result will always be 0.
Here's a way that would work. It can be refactored depending on your skill level.
import javax.swing.JOptionPane;
public class HelloWorld
{
public static void main(String[] args) {
int prompt;
int[] carsValues = new int[6];//didnt want to use 0
do{
prompt = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter"
+ "\n"
+ "1 For Honda"
+ "\n"
+ "2 For Toyota"
+ "\n"
+ "3 For Ford"
+ "\n"
+ "4 For Chevrolet"
+ "\n"
+ "5 For Kia"
+ "\n"
+ "6 To Quit"));
if(prompt < 0 || prompt > 6){
JOptionPane.showMessageDialog(null, "Unrecognizable Command"
+ "\n"
+ "Error: Entered Option must be between 1 and 5 inclusive"
+ "\n"
+ "Try Again"
+ "\n");
}
else{
int n = prompt;
carsValues[n]++;
display(carsValues);
}
}while(prompt!= 6);
}
public static void display(int[] input){
try{
int miles, gallons, mpg;
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
if (miles <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
miles = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Miles Driven "));
}
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
if (gallons <= -1){
JOptionPane.showMessageDialog(null,"Input Is Negative"
+ "\n"
+ "Try Again");
gallons = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter Gallons Used "));
}
mpg = miles/gallons;
JOptionPane.showMessageDialog(null, String.format("MPG Turns Out To Be %n" + mpg));
}catch(ArithmeticException mathError){
JOptionPane.showMessageDialog(null, "Division by Zero"
+ "\n"
+ "Can't Do That");
}
JOptionPane.showMessageDialog(null, "Amount of Times Chosen"
+ "\n"
+ "Honda: " + input[1]
+ "\n"
+ "Toyota: " + input[2]
+ "\n"
+ "Ford: " + input[3]
+ "\n"
+ "Chevrolet: " + input[4]
+ "\n"
+ "Kia: " + input[5]
+ "\n");
}
}
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