我正在编写程序,然后进入该部分(在下面已进行评论),然后尝试做
if(userInput.get() != "")
如果我将对话框保留为空白并按“确定”或输入,它将仍然在if语句中执行代码。所以它会说:
"You did not enter numeric information"
代替
"You did not enter any information"
就像在外部else语句中一样。
我尝试使用null,但也不起作用。我在这里做错了什么?
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;
}
}
答案 0 :(得分:0)
将if(userInput.get() != "")
修改为if(!userInput.get().isEmpty())
==
仅比较参考。
或者您可以使用if(!userInput.get().equals(""))
比较两个String
请注意,如果null
是userInput.get()
,请检查Nullable