I'm trying to write a simple program that will ask for the user to enter a number in-between 1 and 10, then display the number. Now I have gotten part to work where if the number is outside of the range it asks again, but I can't seem to get it to ask again if anything aside from a number is inputted, such as % or hello.
The source code: (Cut out the top)
public static void main(String[] args){
int number; //For holding the number
String stringInput; //For holding the string values until converted
//------------------//
//Introducing the user
JOptionPane.showMessageDialog(null, "This is a program that will ask \n"
+ "you to enter a number in-between \n"
+ "1-10, if the number is not within \n"
+ "the parameters, the program will repeat.");
//---------------------//
//Get input from the user
stringInput = JOptionPane.showInputDialog("Enter number.");
number = Integer.parseInt(stringInput);
//-----------------//
//Checking the number
while (number > 10 || number < 0){
stringInput = JOptionPane.showInputDialog("That number is not within the \n"
+ "allowed range! Enter another number.");
number = Integer.parseInt(stringInput);
}
//-------------------//
//Displaying the number
JOptionPane.showMessageDialog(null, "The number you chose is "
+ number
+ ".");
//-------------//
//Closing it down
System.exit(0);
}
The main problem is the:
number = Integer.parseInt(stringInput);
I can't seem to convert the data values properly. I already thought of something like using an if statement to determine if the number is an integer, but I couldn't figure out how to check. I wish I could do:
if (number == Integer)
As you can see I am still extremely new to Java, any help is appreciated, thanks for taking the time to read.
You need to surround the call to Integer.parseInt() with a try/catch block to detect invalid input, like:
try {
number = Integer.parseInt(stringInput);
} catch (NumberFormatException e) {
// Not a number, display error message...
}
Here is a solution:
String errorMessage = "";
do {
// Show input dialog with current error message, if any
String stringInput = JOptionPane.showInputDialog(errorMessage + "Enter number.");
try {
int number = Integer.parseInt(stringInput);
if (number > 10 || number < 0) {
errorMessage = "That number is not within the \n" + "allowed range!\n";
} else {
JOptionPane
.showMessageDialog(null, "The number you chose is " + number + ".");
errorMessage = ""; // no more error
}
} catch (NumberFormatException e) {
// The typed text was not an integer
errorMessage = "The text you typed is not a number.\n";
}
} while (!errorMessage.isEmpty());
I'm trying to write a simple program that will ask for the user to
enter a number in-between 1 and 10
please to read Oracle tutorial How to use Dialogs - JOptionPane Features, then code should be very short and simple, without parsing an Integer from String
.
import java.awt.EventQueue;
import javax.swing.Icon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
public class MyOptionPane {
public MyOptionPane() {
Icon errorIcon = UIManager.getIcon("OptionPane.errorIcon");
Object[] possibilities = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
Integer i = (Integer) JOptionPane.showOptionDialog(null,
null, "ShowInputDialog",
JOptionPane.PLAIN_MESSAGE, 1, errorIcon, possibilities, 0);
// or
Integer ii = (Integer) JOptionPane.showInputDialog(null,
"Select number:\n\from JComboBox", "ShowInputDialog",
JOptionPane.PLAIN_MESSAGE, errorIcon, possibilities, "Numbers");
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MyOptionPane mOP = new MyOptionPane();
}
});
}
}
Related
package ex2.pkg4;
import javax.swing.JOptionPane;
public class Ex24 {
public static void main(String[] args) {
String num1 = JOptionPane.showInputDialog("Enter The First Number");
int no1 = Integer.parseInt(num1);
String num2 = JOptionPane.showInputDialog("Enter The Second Number");
int no2 = Integer.parseInt(num2);
String num3 = JOptionPane.showInputDialog("Enter The Third Number");
}
}
Use an Array and when the array is filled with the desired amount of numerical values use the java.util.Arrays#sort() method to sort that array in Ascending Order (ex: 1, 2, 3), for example:
/* Create a parent for your JOptionPanes. This ensures that your
JOptionPane dialogs will not be be hidden behind possible on-top
applications or even the IDE. This can happen if null is used as
parent. */
JDialog jd = new JDialog();
jd.setAlwaysOnTop(true); jd.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
// The number of INTEGER numerical values you want.
int desiredNumberOfValues = 3;
// The int[] Array the will hold the valid numbers entered by User.
int[] wantedNumbers = new int[desiredNumberOfValues];
// A counter used to keep track of the number of values entered by User.
int numberCounter = 0;
// Used to hold the number entered in Input dialogs
String number;
// Get the desired amount of numbers from User...
while (numberCounter < desiredNumberOfValues) {
numberCounter++;
/* Notice how basic HTML is used in the Message body of the
Input dialog below. This can add a little flair to things :) */
number = JOptionPane.showInputDialog(jd, "<html>Enter integer numerical value #"
+ " <font size='4' color= blue><b>"+ numberCounter
+ "</b></font>:<br><br></html>", "Integer Number Entry...",
JOptionPane.QUESTION_MESSAGE);
jd.dispose(); // Dispose of parent
/* If a Cancel button is selected or the dialog is
closed, we quit. */
if (number == null) {
JOptionPane.showMessageDialog(jd, "<html>Application Canceled!<br><br>"
+ "<center><font size='5' color=red><b>Bye-Bye</b></font></center></html>",
"Application Canceled" ,JOptionPane.WARNING_MESSAGE);
jd.dispose(); // Dispose of parent
return;
}
/* Validate the supplied value. If it's not a string representation
of a signed or unsigned integer value then inform the User of an
invalid entry and allow the User to try again. */
if (!number.matches("-?\\d+")) {
JOptionPane.showMessageDialog(jd, "<html>Invalid numerical value (" + number
+ ") supplied!<br>You will need to try again.</html>",
"Invalid Entry...", JOptionPane.WARNING_MESSAGE);
jd.dispose(); // Dispose of parent
numberCounter--; // decrement since the entry isn't valid.
continue; // loop again...
}
/* If we can get to here then the User's entry is valid
so we convert the entered valid number to integer and
then place that number into the array. */
wantedNumbers[numberCounter - 1] = Integer.parseInt(number);
}
/* Now we have all the numbers we want. Let's sort
them in ascending order. */
java.util.Arrays.sort(wantedNumbers);
// Let's build a string to display those numbers in a message box
StringBuilder sb = new StringBuilder("");
for (int val : wantedNumbers) {
if (!sb.toString().isEmpty()) {
sb.append(", ");
}
sb.append(val);
}
// Dsiplay all the numbers supplied by User in a Message Dialog box.
JOptionPane.showMessageDialog(jd, "<html>The numerical values that were supplied are:<br>"
+ "<br><center><font size='5' color=blue><b>" + sb.toString()
+ "</b></font></center></html>", "Supplied Values..."
,JOptionPane.INFORMATION_MESSAGE);
jd.dispose(); // Dispose of parent
Hello my task is to write a program that selects a random number between 1 and 5 and asks the user to guess the number. Then I must display a message that indicates the difference between the random number and the users guess. I then must display another message that displays the random number and the Boolean value true or false depending on whether the user's guess equals the random number. I have got the first part of the assignment done, where the user guesses a number and the computer generates a random number between 1 and 5, but I don't have a clue on how to make it display how close or far off they were or how to use a Boolean to show if the guess was equal to the number or not. I have left code of what I have so far. Thanks for the help and sorry if there is anything wrong with this post.
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
I need the first message to read something like "You were 3 numbers off." and the second message needs to read something like "You guessed the number 3 correctly" or "You did not guess the number 3 correctly."
Take the absolute value of the entered number subtracted by the random number.
Something like:
package randomguessmatch;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class RandomGuessMatch
{
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
Scanner input = new Scanner(System.in);
JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
}
Based on Zachary McGee's answer:
public static void main(String[] args)
{
int random = 1 + (int)(Math.random() * 5);
String input = JOptionPane.showInputDialog(null,"Enter a number between 1 and 5: ");
if(Integer.parseInt(input) == random)
JOptionPane.showMessageDialog(null, "You guessed correctly!");
else
JOptionPane.showMessageDialog(null, "You were " + Math.abs(random - Integer.parseInt(input)) + " away");
JOptionPane.showMessageDialog(null,"The number is: " + random);
}
If you have any questions to the code, feel free to ask :)
I've built a little random number generator using JOptionPane. The exceptions that I've written prevent the user from quitting the program when clicking the X button. I've done lots of research and tried several things but nothing seems to work.
Here's my code:
import javax.swing.JOptionPane;
import java.util.Random;
public class Generate {
private int number;
private int min;
private int max;
private int repeat;
Random no = new Random();
int x = 1;
void generateNumber() {
do {
try {
String from = (String) JOptionPane.showInputDialog(null, "Welcome to Random Number Generator!\n\nPlease insert your number range.\n\nFrom:", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
min = Integer.parseInt(from);
String to = (String) JOptionPane.showInputDialog(null, "To:", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
max = Integer.parseInt(to);
System.out.println();
String count = (String) JOptionPane.showInputDialog(null, "How many numbers would you like?", "Random Number Generator", JOptionPane.QUESTION_MESSAGE, null, null, "Enter Number");
repeat = Integer.parseInt(count);
System.out.println();
for (int counter = 1; counter <= repeat; counter++) {
number = no.nextInt(max - min + 1) + min;
JOptionPane.showMessageDialog(null, "Random number #" + counter + ": " + number, "Random Number Generator", JOptionPane.PLAIN_MESSAGE);
}
x = 2;
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: the second number needs to be higher than the first", "Random Number Generator", JOptionPane.ERROR_MESSAGE);
}
} while(x == 1);
}
}
Main:
class RandomNumber {
public static void main(String[] args) {
Generate obj = new Generate();
obj.generateNumber();
}
}
This is what happens when I try to close the program
You don't test the from value after showInputDialog() invocations.
For example here :
String from = (String) JOptionPane.showInputDialog(null,...
After this call, You chain directly with
min = Integer.parseInt(from);
whatever the value of from.
If from is null you finish in this catch as null is not a number :
catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "INPUT ERROR: please insert a number", "Random Number Generator",
JOptionPane.ERROR_MESSAGE);
}
And x has still 1 as value. So the loop condition is still true.
To solve your problem, you just to test the value returned by showMessageDialog() and if the value is null, let the user exits from the method.
Add this code at each time you retrieve a user input and that you want to enable the user to exit :
if (from == null) {
return;
}
Hello please please please can someone help me. I am writing a program where the user can enter a maximum number for a guessing game and using a random generator he/she would have to guess the number from 1-to the max number. i have done most of it but i am stuck on how to loop back the program to enter another input if user say enters a letter or anything else apart from an integer. From the "do" part is where i get confused!
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JOptionPane;
public class guessinggame { // class name
public static void main(String[] args) { // main method
String smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
int max = Integer.parseInt(smax);
do {
if (max > 10000) {
JOptionPane.showMessageDialog(null, "Oh no! keep your choice below 10000 please.");
smax = JOptionPane.showInputDialog("Enter your maximum number for the Guessing Game:");
max = Integer.parseInt(smax);
}
} while (max > 10000);
int answer, guess = 0, lowcount = 0, highcount = 0, game;
String sguess;
Random generator = new Random();
answer = generator.nextInt(max) + 1;
ArrayList<String> buttonChoices = new ArrayList<String>(); // list of string arrays called buttonChoices
buttonChoices.add("1-" + max + " Guessing Game");
Object[] buttons = buttonChoices.toArray(); // turning the string arrays into objects called buttons
game = JOptionPane.showOptionDialog(null, "Play or Quit?", "Guessing Game",
JOptionPane.PLAIN_MESSAGE, JOptionPane.QUESTION_MESSAGE,
null, buttons, buttonChoices.get(0));
do {
sguess = JOptionPane.showInputDialog("I am thinking of a number between 1 and " + max + ". Have a guess:");
try {
guess = Integer.parseInt(sguess);
} catch (NumberFormatException nfe) {
JOptionPane.showMessageDialog(null, "That was not a number! ");
}
if (guess < answer) {
JOptionPane.showMessageDialog(null, "That is too LOW!");
lowcount++;
} else {
JOptionPane.showMessageDialog(null, "That is too HIGH!");
highcount++;
}
break;
} while (guess != answer);
JOptionPane.showMessageDialog(null, "Well Done!" + "\n---------------" + "\nThe answer was " + answer + "\nLow Guesses: " + lowcount
+ "\nHigh Guesses: " + highcount + "\n\nOverall you guessed: " + (lowcount + highcount) + " Times");
System.exit(0);
}
}
First thing's first, the break in the last do-while. If you break without condition inside a loop; it's not a loop; it's a single-execution block.
Other than that, you should, in areas where you're validating input, follow this structure. (pseudo code so you can implement).
Do-While input does not equal answer
Get input from user with dialogue
Begin Try
Parse user input
If input > answer
Notify user
Else-If input < answer
Notify user
End Try
Begin Catch Parse error
Alert user of invalid input
End Catch
End While
How do I round my numbers of output += Math.pow(baseUno, powernumber)+ " "; to the nearest whole number?
They always give me an output of, for example, 1.0 or 2.0. How do you round these so that they would simply result as 1 and 2?
import javax.swing.*;
import java.text.*;
import java.util.*;
public class level7Module1
{
public static void main(String[] args)
{
String base, power, output = " "; //user inputs, and the output variable
double baseUno, powerUno, basenum = 0, powernum = 0; //user inputs parsed so they can be used in mathematical equations
DecimalFormat noDigits = new DecimalFormat("0");
// oneDigit.format(variablename)
base = JOptionPane.showInputDialog(null,"Enter your prefered base, a number between 1 and 14: \nPress 'q' to quit."); //User input
if (base.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0); //quits
}
baseUno = Integer.parseInt(base);
// basenum = noDigits.format(baseUno);
if (baseUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (baseUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
//I chose 0 and 14 because on my monitor the combination of 14 and 14 filled up the entire screen, so I limited to things
//that would fit on my monitor :)
power = JOptionPane.showInputDialog(null, "How many numbers of this base would you like? Between 1 and 14 again, please.\nPress 'q' to quit.");
if (power.equals("q"))
{
JOptionPane.showMessageDialog(null,"Goodbye!");
System.exit(0);
}
powerUno = Integer.parseInt(power);
// powernum = noDigits.format(powerUno);
if (powerUno <= 0)
{
JOptionPane.showMessageDialog(null,"Really? Why would you try to trick me? ):");
System.exit(0);
}
if (powerUno > 14)
{
JOptionPane.showMessageDialog(null,"That wasn't cool. Take some time to think about this \nand\nthen\ntry\nagain.\n\n\n\n\n\n\n\nJerk.");
System.exit(0);
}
for (int powernumber=0; powernumber!=powerUno; powernumber++) //Set the number of powers done to 0, then until it's "powernum" input, it keeps going.
{
output += Math.pow(baseUno, powernumber)+ " "; //Output is the basenum to the power of powernum plus a space, then repeats condition above.
}
JOptionPane.showMessageDialog(null,"Your numbers are: " + output); //Giving the users their outputs
}
}
To the simplest approach change this line :
JOptionPane.showMessageDialog(null,"Your numbers are: " + output);
to
JOptionPane.showMessageDialog(null,"Your numbers are: " + (int)output);
just type caste the result to int