Java Exceptions Prevent Closing The Program (when clicking X button) - java

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;
}

Related

How do I implement a "Beeping" Sound to my code?

So my code runs fine and all; no problems, or atleast I think it doesn't have any; I need to add two final things: first one is a way to make a beep sound (think I have to use toolkit, actionListener, etc) and the other thing, is a way to print the current random number the program generates (something like a toString). I've tried my professor's methods for the beep sound and nothing, so now I'm here. Thanks in advance.
Tried some methods from my professors code but nothing.
//Interface
package edu.pupr.LottoGame;
public interface Ask {
public void ask();
}
//Class
package edu.pupr.LottoGame;
import java.util.Random;
import javax.swing.JOptionPane;
public class theLotto {
//VARIABLE
public int values;
//OVERLOAD CONSTRUCTOR
public theLotto(int values) {
this.values = values;
}
//MUTATOR
public void setValues(int values) {
this.values = values;
}
//ACCESSOR
public int getValues() {
return values;
}
//ANONYMOUS CLASS
public void start() {
Ask ak = new Ask() {
public void ask() {
//ANONYMOUS VARIABLES USED
String input = null;
int reply;
int randomNum;
//BEGINNING OF FIRST DO-WHILE
do {
//INPUT OF USER : 4 DIGITS
input = JOptionPane.showInputDialog("Plese enter 4 digits (1000-9999)");
values = Integer.parseInt(input);
}while(values < 1000 || values > 9999);
//ENDING OF FIRST DO WHILE
//RANDOM NUMBER GENERATOR
Random rn = new Random();
randomNum = 1000 + rn.nextInt(10000 - 1000);
//DETERMINES IF THE USER WON OR LOST
if(values == randomNum)
JOptionPane.showMessageDialog(null, "You Won! The num: " + randomNum);
else
JOptionPane.showMessageDialog(null, "You Lost! The wining num was: " + randomNum);
//BEGINNING OF SECOND DO-WHILE
do {
//WANNA PLAY AGAIN PANEL
reply = JOptionPane.showConfirmDialog(null, "Continue?", null, JOptionPane.YES_NO_OPTION);
//IF OPTION IS YES
if (reply == JOptionPane.YES_OPTION) {
//BEGINNIG OF THIRD DO-WHILE
do {
//INPUT OF USER : 4 DIGITS
input = JOptionPane.showInputDialog("Plese enter 4 digits (1000-9999)");
values = Integer.parseInt(input);
}while(values < 1000 || values > 9999);
//END OF THIRD DO-WHILE
//RANDOM NUMBER GENERATOR
Random rn2 = new Random();
randomNum = 1000 + rn2.nextInt(10000 - 1000);
//DETERMINES IF THE USER WON OR LOST
if(values == randomNum)
JOptionPane.showMessageDialog(null, "You Won! The num: " + randomNum);
else
JOptionPane.showMessageDialog(null, "You Lost! The wining num was: " + randomNum);
}
//IF OPTION IS NO
else {
JOptionPane.showMessageDialog(null, "GOODBYE");
System.exit(0);
}
}while(reply != JOptionPane.NO_OPTION);
//END OF SECOND DO-WHILE
}
};
//PART OF ANONYMOUS
ak.ask();
}
}
//Class Driver
package edu.pupr.LottoGame;
public class theLottoDriver {
public static void main(String [] args) {
theLotto lt = new theLotto(0);
lt.start();
}
}
Ouput should be something like this:
Enter Number: 3267
09/07/2019 09:50:23:
throw #1: 4392
throw #2: 8391
You lost !!!

How do i get the array to hold the number of games played and run it for each player?

I have an assignment where two users are to enter their names, then get the number of games they played, then get the scores for each game that they played, put the scores in an array (or two arrays???), then compare the two arrays and scores to see who won each game or if they're tied, then display results. I don't have to sort it or search through it I don't believe.
Ss my teacher says getting the scores has to be a void method, but I'm not sure how I get the values from this void method into arrays for each player so I can compare the score values.
public class Lab9 {
public static void inputScores(int[] array, String name) {
String inputScores = "";
for (int i = 1; i < array.length; i++) {
inputScores = JOptionPane.showInputDialog(name + " enter your score for game " + i);
array[i] = Integer.parseInt(inputScores);
}
}
public static void main(String[] args) {
int numberOfGames = getPositiveIntOrQuit("How many games were played?", "Lab 9 (by Jarvis),");
String name = getStringOrQuit("Player 1-What is your name?", "Lab 9 (by Jarvis");
String name1 = getStringOrQuit(" Player 2 - What is your name?","Lab 9(by Jarvis");
int score = getNonNegativeIntOrQuit(name + " enter your score for game" , "Lab 9 (by Jarvis)");
}
public static String getStringOrQuit(String prompt, String title) {
String userInputString;
userInputString = JOptionPane.showInputDialog(null, prompt, title, JOptionPane.QUESTION_MESSAGE);
// Did user hit Cancel or OK with nothing typed?
if (userInputString == null || userInputString.trim().equals("")) {
JOptionPane.showMessageDialog(null,"No input, so program will terminate now.");
System.exit(0);
}
return userInputString;
} // getStringOrQuit
public static int getPositiveIntOrQuit(String prompt, String title) {
String userInputString;
int userInputInt = 0;
do {
userInputString = JOptionPane.showInputDialog(null, prompt, title, JOptionPane.QUESTION_MESSAGE);
// Did user hit Cancel or OK with nothing typed?
if (userInputString == null || userInputString.trim().equals("")) {
JOptionPane.showMessageDialog(null,"No input, so program will terminate now.");
System.exit(0);
}
else
try {
userInputInt = Integer.parseInt(userInputString); // This line might throw an exception.
// Ok, if conversion in above line worked, check if input is a positive integer.
if (userInputInt < 1)
JOptionPane.showMessageDialog(null,"Bad input value. It must be a positive integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(null,"Bad input value. It must be a positive integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
} while (userInputInt < 1);
return userInputInt;
} // getPositiveIntOrQuit
public static int getNonNegativeIntOrQuit(String prompt, String title) {
String userInputString;
int userInputInt = -1;
do {
userInputString = JOptionPane.showInputDialog(null, prompt, title, JOptionPane.QUESTION_MESSAGE);
// Did user hit Cancel or OK with nothing typed?
if (userInputString == null || userInputString.trim().equals("")) {
JOptionPane.showMessageDialog(null,"No input, so program will terminate now.");
System.exit(0);
}
try {
userInputInt = Integer.parseInt(userInputString); // This line might throw an exception.
// Ok, if conversion in above line worked, check if input is a positive integer.
if (userInputInt < 0)
JOptionPane.showMessageDialog(null,"Bad input value. It must be a non-negative integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
catch (NumberFormatException exc) {
JOptionPane.showMessageDialog(null,"Bad input value. It must be a non-negative integer.",
"Input error", JOptionPane.ERROR_MESSAGE);
}
} while (userInputInt < 0);
return userInputInt;
}
}
Ive written up some code, take it as my solution to your problem.
I would create a hashmap ( or two, one for each player ) and map the game number to the score. You can then use this hashmap to compare scores quite easily
Example ( This is rough code i did it quickly ):
public class random {
private static Scanner keyboard = new Scanner(System.in);
private static HashMap<Integer, String> gameMap = new HashMap<Integer, String>();
public static void mapScores(){
System.out.println("How many games have been played?");
int numOfGames = keyboard.nextInt();
String score = "";
for(int i = 0; i < numOfGames; i++){
System.out.println("Please enter the score for game: " + i);
score = keyboard.nextLine();
gameMap.put(i, score);
}
}
}
EDIT:
Okay, then i would suggest declaring your integer arrays statically. Makes for easy access. You're saying an array that holds the players scores and the players name, which is why id suggest a hashmap because and array cannot store the name. I'll demonstrate,:
public class random {
private static Scanner keyboard = new Scanner(System.in);
private static HashMap<String, int[]> gameMap = new HashMap<String, int[]>();
private static int[] hello = new int[10];
public static void mapScores(int[] array, String name){
String inputScores = "";
for (int i = 1; i < array.length; i++) {
inputScores = JOptionPane.showInputDialog(name + " enter your score for game " + i);
array[i] = Integer.parseInt(inputScores);
}
}
public static void main(String[] args) {
random.gameMap.put("name", new int[10]);
random.mapScores(gameMap.get("name"), "name");
for(int i = 0; i < gameMap.get("name").length; i++){
System.out.println(gameMap.get("name")[i]);
}
}
}
Obviously i haven't taken the time to correctly create the objects but hopefully you can see the idea despite the bad code. Hope this helps!

How do i fix this simple program? guessing game

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

Java Multiplying 2 integers from strings

I've tried searching a number of threads in terms of multiplying 2 strings. However, it seems that most of the links I found weren't applicable or I couldn't interpret them well enough.
Would it be possible if could tell me what is wrong with my current code?
public static void main(String[] args) {
String sample = value1();
String sample2 = value2();
//========== Test if users placed any characters within the boxes =========\\
try {
Integer.parseInt(sample);
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return;
}
try {
Integer.parseInt(sample2);
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return;
}
Integer.parseInt(sample);
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
}
public static String value1() { //obtain first user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample = value1();
}
return sample;
}
public static String value2() { //obtain second user input.
String sample2 = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample2.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample2 = value2();
}
return sample2;
}
}
My final output should multiply the following numbers
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
You can't multiply strings together. You can multiply numbers, and it sounds like that's what you want to do. Indeed, you're already parsing the strings as integers - and then ignoring the result. You just need to change this:
Integer.parseInt(sample);
Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "+sample * sample2+ ".");
to:
int value1 = Integer.parseInt(sample);
int value2 = Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is "
+ (value1 * value2) + ".");
you are trying to multiply two string not two number
you should use like this :
System.out.println("The total multiplication that you have inserted is "+ Integer.parseInt(sample) * Integer.parseInt(sample2)+ ".");
You have to assign the return value of Integer.parseInt() to variables. The variables passed as param stay unchanged.
int a = Integer.parseInt(sample);
int b = Integer.parseInt(sample2);
System.out.println("The total multiplication that you have inserted is " + a * b + ".");
1st suggestion: Don't (ever!) declare 2 methods that do exactly the same thing!!
public static String value() { //obtain *first and second* user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
sample = value();
}
return sample;
}
2nd suggestion: Don't check the validity of your input in both value() method and main():
public static int value() { //obtain second user input.
String sample = JOptionPane.showInputDialog(null, "Insert Value", "Enter amount ", JOptionPane.QUESTION_MESSAGE);
if (sample.isEmpty()) {
JOptionPane.showMessageDialog(null, "Error!", "No Value Detected", JOptionPane.ERROR_MESSAGE);
return value();
}
try {
int v = Integer.parseInt(sample);
return v;
} catch (NumberFormatException e) {
System.out.println("System detects that you are using characters");
return value();
}
}
for this 2nd case, main becomes:
public static void main(String[] args) {
int x1 = value();
int x2 = value(); // call again the *same* method
System.out.println("The total multiplication that you have inserted is "+x1 * x2+ ".");
}

Converting JOptionPane input to integer

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();
}
});
}
}

Categories

Resources