Question about the cancel button on a standard JOptionPane - java

So I am working on a program for school, and part of the assignment is to have a bunch of prompts for input pop up. I am using the JOptionPane, which inherently has an OK button and a Cancel button. Now, to make the program exit when they press cancel when the prompt is asking for a string, I have something like this:
firstName = JOptionPane.showInputDialog("Please enter your first name:");
if(firstName == null)System.exit(0);
But I also have to do the same thing for numbers I get as input, both Doubles and Ints. If I try the same thing, it throws an error saying The operator == is undefined for the argument type(s) double, null. So, what is the best way for me to check if they click Cancel when being prompted for a numerical value? Thanks for your help!
Edit #1
Here is the code for the JOptionPane getting a numerical value:
startDateMonth = Integer.parseInt(JOptionPane.showInputDialog("Please enter the start date month (1-12):"));

JOptionPane.showInputDialog() returns always a string which is the user input. If the user has clicked the Cancel button it will return null. If you want to convert the user input to another type just parse the string. I mean the code you have pasted should remain the same.
If you are asking for a different thing, please clarify.
Petar

Related

How do I make my user input as a variable in Java while dealing with J Option Pane

I'm a rookie java coder, and I was trying to make a program that receives value from the user in which I can assign whatever he/she enters as a variable so that it can be displayed in a box through JOptionPane.showMessageDialog("");
If the user did not enter anything into the box (Meaning the user input value is equaled to null), java must respond with "You did not enter anything" in the form of JOptionPane.showMessageDialog.
Although it keeps saying one of my variables cant be "resolved"
here's where the error is:
String moviename;
String moviename = JOptionPane.showInputDialog("Whats you favourite movie?");
JOptionPane.showMessageDialog(null, moviename+", sounds like a good watch.");
if (moviename.equals("null")) {
JOptionPane.showMessageDialog(null, "You did not enter anything");
}

How Can I Check , If A User Input (Double) Contain More Than One Point (.)?

First Of All , I Am New To Android Development 😉
Whats Working Fine :-
I Have Created A Calculator, Where User Enter Numbers Using EditText & Select Operator Using Radio button .
On Clicking Of A Button :-
It Creates Variable Double With Value Of EditText
It Returns Respected Answer (In Double) .
Here's Problem Arrive :-
If User Enter More Than 1 Point (.) Ex - [ 5.5.2 ] in Any of the EditText & And Click Button
What Happens Next is a Think Which You Already know 😉
Exactly ! Crash !
So , Is There Any Way To Deal With It ? 😅
Any Suggestion is Appreciated 😌
this not an android problem it's a java problem any way you have to get the text from the EditText as String and then check for the count of the .(Point) in the string
String line = EditText.getText.toString()
int count = line.length() - line.replace(".", "").length();
now if count is more than 1 it will make crash so give the user messae and stop the process else do what you want you are save
It may not be the best solution but its one of the solutions. What you can do is; when user enters the double value, you can convert it into a String using Double.toString() method. and then you can check if it contains more than one '.' (dots).
Pseudo would look like this.
value = get double value from EditText()
str = value.toString()
checkFlag = check(str) //Checks if there are more then one dot
then you cna take decision based on checkFlag value

Design Pattern in Java for Getting Input and Acting on it

I'm trying to make a tic-tac-toe game and I'm encountering a lot of copy-paste work for inputs. I'm trying to figure out what design pattern and implementation works for prompting the user, collecting their input, comparing it and then acting by assigning a value. Right now my code looks like this.
public void promptPlayerCount(BufferedReader in) throws IOException {
String input;
// initial prompt
System.out.println("How many players?");
input = "try again";
while (input.equals("try again")) {
input = in.readLine();
// extract data and check it
switch (Integer.parseInt(input)) {
case 1:
// assignment
playerCount = 1;
break;
case 2:
playerCount = 2;
break;
default:
input = "try again";
// clarified instructions
System.out.println("please enter 1 or 2");
}
}
}
There's a part of me that thinks I could make a function (maybe a factory?) that allows me to generate a function by passing the constructing function the details of the initial prompt, the extraction method, the assignment action and the clarification message.
Would this be best done with lambda functions?
Text input is hard, especially if you can't trust your user (like in a game). Your parseInt will throw a nasty exception right off if your value isn't an integer.
Also standard in is not friendly. I assume this is for an assignment so I won't fault you for using it, but in anything where you don't HAVE to use stdin, don't. The problem is that it's amazingly difficult to get Java to respond to anything less than an entire line with an enter at the end.
When dealing with user input I almost always trim it (Just because they love to insert random white spaces at the beginnings and end) and check to see if it's empty. This could probably be put into a function that also either shows an error or exits the program on "Empty" and otherwise returns a string.
If you often want int values, write a second function that calls the first. Have the second function return an int, but have it catch the exception if the text is invalid and prompt the user again. You could even have this function take a "Range" of integers as a parameter and provide a prompt. So what you have above could look like this:
playerCount = getUserInput("Please enter the number of users", 1, 2);
The rest is wrapped in simple non-redundant functions.
Won't write the code for you because A) it's probably a homework assignment and the fun part is actually coding it and B) someone else probably will provide a full solution with code before I'm done typing this :(
Good luck.

Console default values when using Scanner(System.in)

I am trying to emulate this,
$ are you sure (y,n)? y
Where if the user hits enter, the default option would be read from nextLine() using the Scanner (default being the value already populated in the System.in which is in the above example the String y).
if the user wants to change the value he should hit (backspace/delete) and enter a new value.
is this scenario possible using the Scanner and System.in?
This question is not the same, I want to be able to write to System.in so when I do nextLine() to the Scanner object it will return the default value I have wrote. it is something I always see in bash scripts. In that question he is just outputting the default value within the printed string and then defaulting to it if the user hits enter on an empty input.
This is the closest question I have found, and the answer is saying it is impossible to do.
What do you think?
EDIT1:
Read Tom's comment below.
There is no benefit in pursuing such effect.

How to get the Input entered on JTextField in Java using Scanner object?

I am learning java , I want to make one simple calculator program using GUI in Java. Idea is simple.
Calculator has 2 JTextField for 1st number and for 2nd number.
When I run that program will show -- "Enter the First Number" , below that JTextField to enter 1st number , below that "Enter the Second Number" , below that JTextField to enter 2nd number.
My doubt/question is How to get those input from JTextField and assign it to Scanner input1 and Scanner input2 ? Is it possible to do that ? If not what are the alternative ways ?
Hope you will understand my question , if you are in-front of me I hope I will explain it more properly .
You don't need a Scanner to read data from a JTextField.
If the identifier of the JTextField is jt, you simply can,
String text = jt.getText();
String text = jtext.getText().toString();
or if you want a number
int num = Integer.parseInt(jtext.getText().toString());
The .toString() is redundant but it makes the code easier to read and you will thank yourself later too!

Categories