Return to previous ShowInputDialog after ShowMessageDialog - java

There will be a ShowInputDialog box for user to key in numbers. When user keys in character it will show a MessageDialog box to indicate invalid input.
How do I return to the previous showInputDialog for user to reenter the number after the user click on "OK" button on the MessageDialog box?
The codes:
public static void addStock(Stock s[],int index)
{
s[index] = new Stock();
try{
s[index].setNumber(Double.parseDouble(showInputDialog(null,"Enter number: ")));
}catch(NumberFormatException e){
showMessageDialog(null, "Invalid input. Enter digits only.", "Error!",ERROR_MESSAGE);
}
}
*Edit: It is an inventory system using dialog boxes as the interface to interact with user. For example, to add,delete,update stock in the system.

Try this one :
boolean isValSet = false;
while(!isValSet)
{
try {
String val=JOptionPane.showInputDialog(null,"Enter number: ");
double parseDouble = Double.parseDouble(val);
//set you parseDouble to your attribute.
isValSet=true;
} catch(NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Invalid input. Enter digits only.", "Error!",JOptionPane.ERROR_MESSAGE);
}
}

Related

String data still remains? (Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string)

I am trying out to code a simple arithmetic game in Java but I faced an error like: Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string. This happens when I clicked on number buttons and cleared them to enter a new number but it seems that the string still contains the previous number I clicked. (For example, I clicked 5 and deleted it so I could enter 9 instead and now the string seems to register it as 59 instead of just 9.) I used .setText('') to clear the text area.
This is my code for when the buttons are pressed:
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("one"))
{
answerText.append("1");
userAnswer = userAnswer + "1";
}
// same code for two, three, four... to nine.
if(e.getActionCommand().equals("enter"))
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
}
The answer variable and delete button is :
answerText = new JTextArea();
answerText.setEditable(false);
clearbtn = new JButton("Clear");
clearbtn.setActionCommand("clear");
clearAnswer.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
answerText.setText("");
}
});
How do I make sure that my answerText is completely clear?
Your error message:
java.lang.NumberFormatException: For input string
This means that you are trying to parse a string into a number, but the string contains something that cannot be parsed into a number. Java prints the content of the string after the text For input string. In this case there's nothing after that text, because the string that you are trying to parse is the empty string - that you set in the text box by calling answerText.setText("");
Solution: Check if the string you are trying to parse is empty before you try to parse it into a number. For example:
if (e.getActionCommand().equals("enter"))
{
if (!"".equals(userAnswer)) // Check if userAnswer is not empty
{
int userValue = new Integer(userAnswer);
if (userValue == rightAnswer)
{
score++;
userAnswer = "";
generateRandomProblem();
}
else
{
JOptionPane.showMessageDialog(this,"Wrong answer! Please try again.");
}
}
else
{
JOptionPane.showMessageDialog(this, "Please enter a number before pressing Enter.");
}
}
The variable userAnswer doesn't get cleared when answerText is cleared. This might cause issues.
The exception you are having is probably being cause because int userValue = new Integer(userAnswer); is called at a point where userAnswer is empty (because it can't make a number out of nothing).

JOptionPane cancel button and getting input

I'm trying to get the user to input there name if it is left blank it will ask again, if they fill it out it sets a JLabel or hit cancel to get out.
My last if statement is wrong it does not like nameEnt.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
if (nameEnt == nameOption.CANCEL_OPTION) {
System.exit(0);
}
}
The JOptionPane.CANCEL_OPTION is a static int field, and you can't compare String with int with ==.
Good practice
In your case you want to use ok and cancel button JOptionPane.showConfirmDialog and JOptionPane.showInputDialog() in one shot and this is not possible, i suggest to use this instead :
JTextField nameF = new JTextField(20);//create TextField
JPanel myPanel = new JPanel();//cerate JPanel
myPanel.add(new JLabel("Name"));
myPanel.add(nameF);//add your JTextField to your panel
int result;
do {
result = JOptionPane.showConfirmDialog(null, myPanel,
"Title of Panel", JOptionPane.OK_CANCEL_OPTION);//add your panel to JOptionPane
if (result == JOptionPane.OK_OPTION) {//if the user press OK then
if (nameF.getText().isEmpty()) {//check if the input is empty
//if this condition is true JOption stays until name is entered or canceled
} else if (!nameF.getText().matches("[a-zA-Z]+")) {//check if the input match with your regex
//name match exactly
//name.setText(nameF.getText());
}
}
} while (result != JOptionPane.CANCEL_OPTION);//If the user hit cancel then exit
As per the JOptionPane API, if the user cancels the dialog, null is returned.
And so the correct solution is to to not to use equals, but rather to check the return value for null and to do this first, before checking its length.
public Player() {
//setBackground(Color.green);
setSize(600, 400);
name = new JLabel();//Input hint
JOptionPane nameOption = new JOptionPane();
String nameEnt = nameOption.showInputDialog("First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
}
if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
}
if (nameEnt.length() == 0) {
//if this condition is true JOption stays until name is entered or canceled
}
// if (nameEnt == nameOption.CANCEL_OPTION) {
// System.exit(0);
// }
}
But why are you creating a JOptionPane this way? Better to use the static method of creation.
// don't use null as the first parameter if the GUI is already showing
String nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
}
Or maybe something like this, if you're trying to loop to get input:
public Player() {
setSize(600, 400); // This is not good to do. Ask for details and I'll tell.
name = new JLabel();// Don't forget to add this to the GUI!
String nameEnt = "";
while (nameEnt.trim().isEmpty()) {
// if the GUI is already showing, pass a component from it as the first param here, not null
nameEnt = JOptionPane.showInputDialog(null, "First Name: ");
if (nameEnt == null) {
// user canceled. get out of here.
System.exit(0);
// or return;
// or throw some exception
} else if (!nameEnt.matches("[a-zA-Z]+")) {
name.setText(nameEnt);
} else {
// set it to "" so that we keep looping
nameEnt = "";
}
}
}

Java for loop with if statement only iterating once

I have a version of a login for an employee system i would like to make, I have a for loop which should go through the entire list of Accounts, then see if the name of an employee matches one in the list then the if statement continues, further questions asked etc... it seems to only iterate once and then stop as it will only find the first user and tell me the other accounts do not exisit, even though they do!! What am i doing wrong? Also my list contains Employees and Managers which inherit from Account, the if statement uses the getName in Account to compare if it equals to the user input. Sorry if this is ridiculously stupid/bad! thanks.
List <Account> Accounts = new LinkedList<Account>();
Here is where i populate my Account, the main method calls this and the list() is called whihc contains the problematic loop
public void add() {
Employee Geoff = new Employee("Geoff", "password1");
Manager Bob = new Manager("Bob", "password2");
Employee John = new Employee("John", "password3");
Accounts.add(Geoff);
Accounts.add(Bob);
Accounts.add(John);
list();
}
problem:
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
}
}
System.out.println("Employee does not exist!");
login();
}
I am doing the print statement in the for loop to see what it is findng, and unfortunalty it is only the first account
EDIT: I have included more code here, my after my initial if statement i want to check if the code the user enters is also correct.
see if the name of an employee matches one in the list then the if
statement continues, further questions asked etc... it seems to only
iterate once and then stop as it will only find the first user and
tell me the other accounts do not exisit, even though they do!!
If it works for one employee and tells that others don't exist then your for loop does not iterate once.
The output you get is exactly what the code looks like. You get username once then try to match the same name with every employee in the list. If the names are equal you ask for password, otherwise you print out that employee doesn't exist. Everything right as it is in the code. You should add to your question the expected behaviour so I, or someone else can fix your code without guessing the purpose of your methods.
Here's one of those guesses:
System.out.println("Please enter your name: ");
String empName = Scan.nextLine();
boolean userFound = false;
for (Account a : Accounts) {
System.out.println(a);
if (a.getname().equals(empName)) {
System.out.println("\nPlease enter your passcode: ");
String code = Scan.nextLine();
if (a.check(code) == true) {
System.out.println("logged in");
userFound = true;
break;
}
}
}
if(userFound) {
login();
} else {
System.out.println("User not found.");
}
This is a possible solution that doesn't use your Account class (since I do not know what it looks like) and instead uses a Map:
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Hello welcome: ");
System.out.println("Please enter your name: ");
String empName = input.nextLine();
boolean found = false;
Map<String, String> accounts = new HashMap<String, String>();
accounts.put("Geoff", "password1");
accounts.put("Bob", "password2");
accounts.put("John", "password3");
Set<String> names = accounts.keySet();
for (String a : names)
{
if (!a.equals(empName))
{
continue;
}
found = true;
// three tries to login
boolean success = false;
for(int i = 0; i < 3; i++)
{
System.out.println("Please enter your passcode: ");
String code = input.nextLine();
if (accounts.get(a).equals(code))
{
System.out.println("logged in");
success = true;
}
else
{
System.out.println("Wrong password... try again");
}
}
if(!success)
{
System.out.println("User failed to authenticate after 3 attempts. User has been locked out!");
}
}
if(!found)
{
System.out.println("Employee does not exist!");
}
}
Since I do not know what the login() method does, I just simply added that into the code. This solution iterates three times in an attempt to get the correct password. If that fails, a message is displayed.

Data validation within data validation

I first want to validate that the user entered a value and to make sure to exit if 'cancel' was pushed. Then, I want to validate that the String releaseDateString is in the correct format at the same time as converting the String to java.sql.Date.
The first validation is taking place but then the JOptionPane carries on repeating itself and does not even consider the try and catch following it.
Here is my method
boolean retry = false;
java.sql.Date releaseDate = null;
String releaseDateString = "";
String title = "";
while (!retry) {
while(!retry){//field is validated to make sure a value was entered and to exit if cancel was pushed
releaseDateString = JOptionPane.showInputDialog("Please input the release date of the movie (yyyy-mm-dd)");
qtd.stringValidation(releaseDateString);
}
try { //the date is validated to make sure it is in the correct format
releaseDate = java.sql.Date.valueOf(releaseDateString);
} catch (Exception e) {
retry = false;
JOptionPane.showMessageDialog(null, "Make sure you enter a date in the format of 'dd-mm-yyy'");
}
}
It links to this method
public static boolean stringValidation(String attribute){
boolean retry = false;
if (attribute == null){
System.exit(0);
}
else if (attribute.equals("")) //if the cancel button is selected or no value was entered into the
{
JOptionPane.showMessageDialog(null, "Make sure you enter a character into the textbox");
}
else {
retry = true;
}
return retry;
}
When you do this,
qtd.stringValidation(releaseDateString);
You aren't assigning the result to retry. I believe you wanted,
retry = qtd.stringValidation(releaseDateString);

Why won't this method call work?

I'm creating a method to take an input by a user and validate it to make sure it's correct. If it's correct it will call a method and input the user input in to it. But for some reason, the method call is not working. It doesn't produce any errors, it just simply doesn't do it. I placed a print statement at the end of the code to make sure it actually reaches there and it does, but for some reason it's just not calling the method like it's supposed to. The other method works fine if I call it by itself and input a string via the parameters.
The code is:
public void getGetScheduledShowByFilmInput()////new - omar////
{
BufferedReader reader;
reader = new BufferedReader(new InputStreamReader(System.in));
String filmInput;
filmInput = "";
boolean foundFilm;
foundFilm = false;
System.out.println("Here is a list of films that are currently showing:");
for(Film film : films){
System.out.println(film.getFilmName());
}
System.out.println("");
System.out.println("Please type the film name that you wish to view the corresponding shows for and press enter.");
System.out.println("Type 'exit' and press enter to exit this process.");
while(foundFilm == false){
try{
filmInput = reader.readLine();
}
catch (IOException e){
System.out.println("Error");
}
//If user enters "exit" then return.
if(filmInput.equals("exit")){
return;
}
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName() == filmInput){
foundFilm = true;
break;
}
}
if(foundFilm = true){
System.out.println("Film found.");
}
else{
System.out.println("The film name you entered has not been recognised. Please try again.");
}
}
//Call the function and input the film name input by the user.
getScheduledShowsByFilm(filmInput); ////This is the code that seems to be the problem.
System.out.println("reached bottom");
}
and the second method is:
public void getScheduledShowsByFilm(String inputFilmName)
{
ArrayList<Show> scheduledShows;
scheduledShows = new ArrayList<Show>();
for(Film film : films){
if(inputFilmName == film.getFilmName()){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}
for(Show show : scheduledShows){
System.out.println("**********************************");
show.getShowDetails();
System.out.println("**********************************");
}
}
The second method works perfectly when I call it on its own and enter parameters manually though.
It's probably something extremely simple that I'm not understanding! haha, thank you for your help :)
foundFilm can never be false because you always assign true to it:
if(foundFilm = true){
System.out.println("Film found.");
}
try changing it to this:
if(foundFilm)
{
System.out.println("Film found.");
}
In getGetScheduledShowByFilmInput() and getScheduledShowsByFilm(String) avoid doing string comparison using the equality operator (==). The == operator tests for object equality, but you want to test whether two strings contain the same sequence of characters. Therefore, use equals instead:
//Check to see if the film name input by the user corresponds to any film showing.
for(Film film : films){
if(film.getFilmName().equals(filmInput)){
foundFilm = true;
break;
}
}
and
for(Film film : films){
if(inputFilmName.equals(film.getFilmName())){
for(Schedule schedule : schedules){
scheduledShows.add(schedule.getShowsOfFilm(film));
if(scheduledShows.get(scheduledShows.size() - 1) == null){
scheduledShows.remove(scheduledShows.size() - 1);
}
}
}
}

Categories

Resources