0

I'm in the process of writing a program, and I get to the part(which I've commented below) and I try to do

if(userInput.get() != "") 

It still executes the code inside the if statement if I leave the dialog box blank and press "ok" or enter. So it would say:

"You did not enter numeric information"

instead of

"You did not enter any information"

like in the outer else statement.

I tried with null and it didn't work either. What am I doing wrong here?

import java.util.Optional;

import javafx.application.*;
import javafx.event.*;
import javafx.geometry.Pos;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.input.*;
import javafx.scene.layout.*;
import javafx.scene.paint.*;
import javafx.scene.shape.*;
import javafx.scene.text.*;
import javafx.stage.*;
import javafx.stage.Stage;

public class QuizDialogBox extends Application {

public void start(Stage primaryStage) {

TextInputDialog inputDialog = new TextInputDialog();
inputDialog.setHeaderText(null);
inputDialog.setTitle("Grams to Ounces");
inputDialog.setContentText("Enter number of Grams: ");
Alert errorAlert = new Alert(AlertType.ERROR);

Optional<String> userInput = inputDialog.showAndWait();

if((userInput.get() != "") && userInput.isPresent())      //the part thats not working
{

    String userInputString = userInput.get();
    System.out.println("{" + userInputString + "}");

    if(isNumeric(userInputString)) 
    {
    int userNumber = Integer.parseInt(userInputString);
    System.out.println(userNumber);
    }
    else 
    {
        errorAlert.setContentText("You did not enter numeric information");
        errorAlert.showAndWait();
    }
}
else 
{
    errorAlert.setContentText("You did not enter any information");
    errorAlert.showAndWait();
}

}

public static void main(String args[]) {
    launch(args);
}

public static boolean isNumeric(String string)  {
    boolean isNumber = false;

    try
    {
        Integer.parseInt(string);
        isNumber = true;
    }
    catch(NumberFormatException ex) {

    }
    return isNumber;

}
}

1 Answers1

0

modify if(userInput.get() != "") to if(!userInput.get().isEmpty())

== compares the reference only.

Or you can use if(!userInput.get().equals("")) to compare two String

Be careful of checking null if userInput.get() is Nullable

Shubhendu Pramanik
  • 2,711
  • 2
  • 13
  • 23