How do i get this to work properly? i am trying to get it to check that input in joptionpane is an int then continue the rest once an int is put in. import javax.swing.JOptionPane; import java.util.Random; import java.util.Scanner; public class Dieroll { public static void main(String[] args) { String userenters; userenters = JOptionPane.showInputDialog ("How many sides on your die?: "); String input = userenters; boolean success = false; while (!success) { try { Integer.parseInt(input); break; } catch (NumberFormatException e) { JOptionPane.showMessageDialog(null,(e)); break; } } JOptionPane.showMessageDialog(null, "Number of sides is: " + userenters); int res = Integer.parseInt (input); Random dice = new Random(); int x = dice.nextInt(res); JOptionPane.showMessageDialog(null, "Die roll value is: " + (x+1)); } }
@smokeybrown
ive worked on this code for two days now, i have no idea what to do with it anymore
There are multiple problems in this code- 1) Why're you even using the success variable when you never change it? 2) Using a while loop with breaks inside both try and catch blocks!? There's no use of a while loop if you're going to exit it in the first iteration itself. 3) try-catch might not be the best way to check if your input is valid in this case. Imagine this scenario: The user clicks on 'Cancel' or 'x,' this will return a null value that gets stored in the input variable, and then when you do Integer.parseInt(input) it'll throw an error message even tho the user just wanted to exit your program. 4) Negative inputs. Random.nextInt(int n) expects a positive input n. You don't have any checks for this, and it'll throw an IllegalArgumentException exception you aren't handling.
I think a do-while loop would be neater to implement, and rather than validating your input with a try-catch block, use the String matches() method.
Join our real-time social learning platform and learn together with your friends!