JOptionPane.showInputDialog Changing the ´cancel´ Button - joptionpane

So I'm trying to get a number input from a player in an RPG/survival type game, using showInputDialog to present the options, prompting the user to input a number. My problem is, I get a fatal error if they press cancel.
This is my current code:
String typeReader;
do{
typeReader = JOptionPane.showInputDialog(options);
}while(typeReader.isEmpty());
if (typeReader.isEmpty())
typeReader = "0";
charType = Integer.parseInt(typeReader);
and this is the error I get:
Exception in thread "main" java.lang.NullPointerException
at Game.main(Game.java:66)
Java Result: 1
BUILD SUCCESSFUL (total time: 14 seconds)
Ideally, if a user presses cancel the program would just read it as an empty String:
typeReader = "";
Can anyone help?

OK, you seem to be pretty new to this ;-)
First, you won't need the loop. Just write
String typeReader = JOptionPane.showInputDialog(options);
If the user clicks "Cancel", typeReader will be null afterwards. null is not an object, so you cannot call isEmpty() on it and you get the NullPointerException. Instead, you should check for null:
if (typeReader != null) {
...
}
You should read the Oracle tutorial on dialogs and maybe also the Javadoc.

Related

Elvis operator doesn't work in Kotlin while the synthax seems correct

I am learning Kotlin from this [video][1] and at 35:45 he is running this code:
[enter image description here][2]
I ve tried to run exactly the same code:
fun main() {
val x = readLine()?:"1"
val y = readLine()?:"1"
val z = x.toInt() + y.toInt()
print(z)
}
But i get this error:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at MainKt.main(Main.kt:4)
at MainKt.main(Main.kt)
Can somebody help me please? I am really a noob in kotlin (and sofware programming too) and i didn't found an answer on the web.
Thank you.
[1]: https://www.youtube.com/watch?v=5flXf8nuq60&t=302s
[2]: https://i.stack.imgur.com/nlHqi.jpg
[3]: https://i.stack.imgur.com/o7y2I.jpg
The Elvis operator evaluates to the right operand only when the left operand is null. The empty string "" is not the same as null.
readLine() returns null when it detects the "end of file". When reading from a file, this is obviously when reaching the end. When reading from stdin (the console's standard input), this is usually when you press Ctrl+D.
If you just press Enter, you are effectively inputting an empty line (""), not the "end of file".
If you want to get this kind of default value when you press Enter on the command line, then you should react to the empty string instead of null. As #lukas.j mentioned, one way to do this is to use ifEmpty to provide a default:
val x = readln().ifEmpty { "1" }

How to display an error message if user input is not in the correct form?

So far in my code I prompt the user to enter a positive integer representing the number of people they are inviting to an event.
I already have an if statement to return an error message if the user input is a negative value.
But how do I return an error message if the user enters a character, string, or double?
Whenever I test this by entering a letter, the terminal just displays the following message:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:909)
at java.util.Scanner.next(Scanner.java:1530)
at java.util.Scanner.nextInt(Scanner.java:2160)
at java.util.Scanner.nextInt(Scanner.java:2119)
at Cookies.main(Cookies.java:15)
Catch the exception then display the message
such as
try
{
int i = Integer.parseInt(input);
}
catch(NumberFormatException e)
{
System.out.println("You didn't enter an integer");
}

Infinite loop that reads stdin in JScript

I'm trying to create an infinite loop to poll for midi input. The loop I have here is technically infinite but I think what's happening is it's getting stuck on the WScript.StdIn.ReadLine() method. It seems that it waits each time for the user to enter something before it continues. I think this because when I enter a character, any midi input in that instance will get routed and the WScript.Echo message will go off.
How can I get it to not wait but check in that instance if there's a character or not? so that the loop doesn't get stopped waiting for input. Is there another ReadLine() method that would work for what I'm looking for?
Here's the code:
while (true) {
str = WScript.StdIn.ReadLine();
if (str == 'q')
break;
// WScript.StdOut.Write("the while loop continues..."
WScript.Echo("the while loop continues...")
msgStr = mox.GetMidiInput()
if (msgStr !== "") {
msgArray = msgStr.split(",")
tStamp = msgArray[0]
port = msgArray[1]
stat = msgArray[2]
data1 = msgArray[3]
data2 = msgArray[4]
mox.OutputMidiMsg( 3, stat, data1, data2);
} else {
continue;
}
}
EDIT:
Right now I just got rid of the ReadLine() because I read on MSDN that it waits for an enter keypress before it returns and I don't think there are any arguments to change that... so I have an infinite loop like I want but I have to resort to ctrl+c to exit it. Anybody have any ideas for a construct that would allow me to quit via the keyboard somehow?
EDIT 2:
I found out that midiox actually provides a method to be polled to exit the script and it works great.

GetMessage() function is calling itself infinitely (not coming out of loop)

I am implementing similar type of thing- I have some message box in the else part of the code below..what I get on debugging is that - I have same message box again and again and it doesn't end (which makes my program crash and I need to restart my laptop)..Is there any solution for it? I am using MFC application and creating a button on window explorer's preview pane. Every thing is fine but this is the problem that once if I enter in the loop below I am not able to come out (I mean there is some thing in DispatchMessage or TranslateMessage which calls this function again and again)..I couldn't find whats that ??
the code is as follow-
while( (bRet = GetMessage( &msg, NULL, 0, 0 )) != 0)
{
if (bRet == -1)
{
// handle the error and possibly exit
}
else
{
TranslateMessage(&msg);
DispatchMessage(&msg);
//Onee message box here
}
}
finally i found that when i return true; in this loop the control will come out of the loop(but its not in good approach) but this getmessage was not useful for me infact when i reomved it my program was working fine. In its presence it was having infinite loop.
Because i created the dialog using CreateDialogParam() and then DialogProc is called through this CreateDialogParam() and then i used WM_Commnands to handle the message received according to the application and i feel no use of this getmessage (please point anyone if i am wrong)

Wait for something of variable time to complete before continuing method

I need to be able to halt a method while it waits for user input.
I tried using a while (true) loop to check to see if a boolean was set indicating that the operation had completed, but as I predicted, it made the application non-responsive.
How do you halt and resume a method after a variable has been set, without calling the method again, and without making the entire application non-responsive.
Here's basically what the program does
openFile method called
openFile method determines whether file has a password
if it does, display an alert to the user requesting the password
Here's the problem, halting the method until the password has been entered.
Any help appreciated.
Why do you want to halt the method? You could use a delegate. You present the alert view and register the delegate for the alert view. The delegate registers for the didDismissAlertViewWithButtonIndex method and acts according to the button. If the password was entered correctly and the OKAY button was tapped, you can continue with your process.
You can't. You need to split it up into two methods, one that does the initial check and then prompts for the password, then the second that uses the password to get the file.
You may need something like below.
class Program
{
static void Main(string[] args)
{
}
void YourFileReadMethod()
{
string password = string.Empty;
bool isPasswordProtected = CheckFileIsPasswordProtected();
if (isPasswordProtected)
{
Form passwordFrm = new Form();//This is your password dialogue
DialogResult hasEntered = DialogResult.No;
do
{
hasEntered = passwordFrm.ShowDialog();
password = (hasEntered == DialogResult.Yes) ?
passwordFrm.passwordTxt//password property/control value;
: string.Empty;
} while (hasEntered != DialogResult.Yes);
}
ReadFileMethod(password);
}
private void ReadFileMethod(string password)
{
//use the password value to open file if not String.Empty
}
bool CheckFileIsPasswordProtected()
{
//your logic which decides whether the file is password protected or not
//return true if password is required to open the file
return true;
}
}