JOptionPane.showInputDialog and JOptionPane.showInputDialog Obligatory to respond - java

I'm doing a project to the university and I have a JOptionPane.showInputDialog that asks your name and another one that has 2 radio buttons. The thing is that I can leave it empty and the game continues. I wanted to stay still until you put a name on it and choose one of the two radio buttons.
Which means, its obligatory to answer to those things.

Not sure if i fully understand the question. Maybe a do-while can help?
String name = null;
do{
name = JOptionPane.showInputDialog(...);
}while(name == null || name.isEmpty());
This will force the user to enter a name, if the user clicks cancel or the X, the message will just re-appear. (If name == null, name.isEmpty() won't be called, avoiding NullPointerException).
If you want the program to exit if the name is null, try something like:
String name = null;
do{
name = JOptionPane.showInputDialog(...);
//Exits the program if the name is null,
//you can also use a "break;" here and handle the exit after the loop
if(name == null) System.exit(0);
}while(name.isEmpty());

Related

Null pointer exception when JOptionPane.showMessageDialog is cancelled

Despite efforts reading on how Null Pointer Exceptions are generated, I literally have no clue how this error is generating itself within my code.
I don't think this affects my code directly, as I could just catch the exception, but before I do that, I'd still like to learn more about the error.
Part of my code where the error is generating, I am opening a new Input dialog and waiting for the user's input. If the user cancels the input dialog, it's just meant to close the dialog, in which it does. However, it's giving me an error every time I cancel.
Here's the code:
String newInput = JOptionPane.showInputDialog(null, "Your current holdings are: "
+ cable.getHoldings(), "Edit Holdings", JOptionPane.CANCEL_OPTION);
if (newInput.isEmpty())
{
//Error generated here
JOptionPane.showMessageDialog(null, "Please enter in a number!");
}
else
{...}
The message dialog is only triggered if the user presses the 'OK' button on the input dialog. Otherwise, if a user cancels or exits the input dialog, a null pointer exception error is generated.
Does anyone mind helping me and letting me know why this is happening?
Thank you.
From docs
Returns: user's input, or null meaning the user canceled the input
so it retruns null if user cancel the dialog
From showInputDialog source code
if (value == UNINITIALIZED_VALUE) {
return null;
}
Solutions : put a nullity check before doing anything
if (newInput==null || newInput.isEmpty())
you don't need newInput.isEmpty() because it checks the length of a string so even user enters a space length will be 1 or length will be null in case of cancelled input so nullity check is only enough for checking some input.
Improvement : you can use regex to validate your input, is digit or not ,like this
if (newInput==null || !newInput.matches("\\d+"))
{
JOptionPane.showMessageDialog(null, "Please enter in a number!");
}
\\d+ check the input should contain at-least one or more integer digits.
The issue what I understood is that you are checking the isEmpty() method on a null (newInput) value which will throw the null pointer exception. You should check this below:
Instead of this:
if (newInput.isEmpty())
{
//Error generated here
JOptionPane.showMessageDialog(null, "Please enter in a number!");
}
Do this :
if (newInput == null)
{
//Error generated here
JOptionPane.showMessageDialog(null, "Please enter in a number!");
}
This should work fine. Hope this helps...!!!

User input for an if/else statement

its only my second program with java and im running into some issues.
I'm trying to get input from a user, either yes or no, then based on that go to an if else statemene. Heres what I have so far
String answer= UI.askString("Do you want to continue?");
if(answer=="yes"){
UI.println("Lets go");
}
else if(answer == "no"){
UI.println("Thank you. Goodbye");
}
else{
UI.println("Please enter yes or no");
}
Im thinking perhaps its better to use booleans for this?
Any help is gladly appreciated!
(also if you're wondering, its a custom import hence the weird syntax in some lines)
Cheers.
When you compare two Strings in Java with the == operator, they are compared to see if they are the same object, rather than whether they contain the same text. So, you could type "yes", and when you use if (answer == "yes") the comparison fails, because the object you got back from UI.askString is a different object, stored at a different place in memory, than the String the compiler generated from the literal "yes".
To compare the value of the two Strings you need to write answer.equals("yes"), or "yes".equals(answer). Either one will work, and will call the equals method of the String class, which will compare the actual text.
The latter syntax, "yes".equals(answer), is often recommended because it will not cause a NullPointerException, even if the variable answer is set to null. This is because the equals method handles null and simply returns false. If, on the other hand, you used the answer.equals("yes") form, and answer was null, you would be trying to invoke a method on null and an exception would be thrown.
what you are looking for is a dialog box. Here is oracle examples, with code. It is more than I can write here. There are ton of yes, no boxes and detection's of user input with them.
http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
Quick answer:
int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){ ... }
Other choices ...
YES_OPTION, NO_OPTION, CANCEL_OPTION, OK_OPTION, and CLOSED_OPTION
For a command line program you need...
import java.util.Scanner;
The code will look like ...
Scanner in = new Scanner(System.in);
String line = in.nextLine();
//ask them to write yes, no, whatever
if(line.equal("yes"){ }
else if (line.eqals("no") {}
else {}
using MikeG010590's answer, you can try:
Scanner in = new Scanner(System.in);
String line;
System.out.println("you want to continue?");
Boolean exit = null;
do {
line = in.nextLine();
switch (line) {
case "yes":
exit = false;
break;
case "no":
exit = true;
break;
default:
System.out.println("Please enter yes or no");
break;
}
}
while (exit == null);
System.out.println(exit ? "Thank you. Goodbye" : "Lets go");

How to access JOptionPane commands in showInputDialog?

Here is my code:
public static void nameset(){
int no = 1;
name = JOptionPane.showInputDialog(frame, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name.equals("") || name.equals(JOptionPane.CANCEL_OPTION));{
JOptionPane.showMessageDialog(frame,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name.equals("") || name.equals(JOptionPane.CANCEL_OPTION)){
if (no == 2){
JOptionPane.showMessageDialog(frame, "Seriously? Again?! that's it..");
if (name.equals(JOptionPane.CANCEL_OPTION)){
System.exit(0);
}else{
System.exit(0);
}
}
}
}
I want it so if you press the cancel option it tell you to restart. But if you press cancel, it shows an error in the console. I think it's the name.equals(JOptionPane.CANCEL_OPTION), But I'm not sure. Is there any reason for it not to work? Thanks in advance for any help.
The cancel button will always result in null being returned. See official JavaDoc:
Returns: user's input, or null meaning the user canceled the input
So your condition should be changed to:
if(name == null || name.equals(""))
and you also need to remove the semicolon after your first if statement! Otherwise the following block will always be executed.
Once that's fixed, your "exit after 3 times no" will not work because you're not actually looping your input dialog.
Try this
int no = 1;
String name = JOptionPane.showInputDialog(null, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);
if(name == null || name.equals(""));{
JOptionPane.showMessageDialog(null,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
no++;
}if (name == null || name.equals("")){
if (no == 2){
JOptionPane.showMessageDialog(null, "Seriously? Again?! that's it.."+name);
if (name == null || name.equals("")){
System.exit(0);
}else{
System.exit(0);
}
}
}

TextInputFile, TextOutputFile (with username, pass in a login system)

int menuoptions;
String userinput;
String usercheck="";
String username="user";
String password;
int intCounter=0;
con.println("TYPING GAME\n");
con.println("1. Sign in");
con.println("2. Create a new account");
menuoptions = con.readInt();
con.clear();
if(menuoptions==1){
while(!username.equals(usercheck) && intCounter==0){
con.println("Please type in your username.");
userinput = con.readLine();
con.clear();
TextInputFile infile = new TextInputFile("logins.txt");
while(infile.eof() == false && intCounter==0){
usercheck=infile.readLine();
infile.readLine();
if(username.equals(usercheck)){
intCounter=intCounter+1;
}
}
if(!userinput.equals(usercheck) && intCounter==0){
con.println("No such username.");
pause(2000);
con.clear();
}
else if(userinput.equals(usercheck)){
intCounter = intCounter+1;
}
}
con.println("What is your password?");
}
if(menuoptions==2){
con.println("What will be your username?");
username = con.readLine();
con.clear();
con.println("What will be your password?");
password = con.readLine();
con.clear();
TextOutputFile outfile = new TextOutputFile("logins.txt", true);
outfile.println(username);
outfile.println(password);
}
}
public static void pause (int intMS){
try{Thread.sleep(intMS);
}catch(InterruptedException y){}}
In logins.txt, i have 'voidturbulence' in one line, and in the next line, i have '80'.
when i type in 'voidturbulence', it jumps to 'no username found', when it should be asking for the password.
However, if userinput (voidturbulence) is equal to usercheck (the first line [voidturbulence]), then shouldn't it break out of the loop and ask me for the password?
A. The code
usercheck=infile.readLine();
infile.readLine();
looks suspicious to me. You probably have a blank line, a line with the user name, and some other text in the file read by infile. Thus, usercheck probably never receives the user name you target. (You skip every second line from infile.)
B. instead of
infile.eof() == false
use
!infile.eof ()
for better readability.
Otherwise,
(((infile.eof() == false) == true) == true)
would be considered more readable, right?
C. instead of
if (menuoptions == 1)
{
}
if (menuoptions == 2)
{
}
use
if (menuoptions == 1)
{
}
else if (menuoptions == 2)
{
}
since menuoptions cannot equal 2 when you just found it was equal to one (and did not change it in the first then-block).
D. What is intCounter good for?
You initialize it to 0.
You increment it if the username equals
usercheck.
The while loop loops as long as username is not equal to
usercheck and intCounter equals 0.
Thus, both condition will be fullfilled if username equals usercheck.
You could eliminate intCounter.
This is a good example for a bad variable name. "intCounter" neither guarantees that it is an int, nor that it contains a count of anything. You will find that if you try to create useful names, you'll tend to create useful code. In your example, you created a useless name, and useless code that manipulates the value behind the name, but really don't accomplish anything.
E. What are you trying to accomplish?
Except for the headline of the question, there is no specification of the requirements your code tries to cover. Better specify what you want to do, then present the code, and specify your problem. DonĀ“t just throw some general keywords at us, followed by code. Please ;)

Java - how to take undetermined amount of input from user

Java Question:
I want to take an undetermined number of lines of input from a user. For instance, I want the user to continue entering names of people as strings until the user has no other names to enter. I want a user-friendly way to easily indicate that the user has no more input. The loop may look like the following. Any good ideas? Any tips on improving the snippet of code is appreciated as well.
BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
while( <user still has more input> ) {
System.out.println("Enter name: ");
String s = read.readLine();
...
<do something with s>;
...
}
thank you!
You need a value that isn't a name but indicates no more data. An empty line would be good. You also want to query if they really want to quit, so in case they accidentally hit return they haven't lost all their data.
name = read.readLine();
Pattern p = Pattern.compile("^\\s$"); //empty line or one of just space chareacters
if (p.matcher(name).matches()) {
System.out.println("Are you done?[y/n]");
if (Pattern.matches("[yY]", read.readLine()) {
//quit your loop
}
}
You could have a boolean variable, such as finished, and check if the user enters 'Q' or another item to indicate that they are finished. If so, set finished to true and you will exit your loop on the next iteration.
Here is a quick example,
boolean finished = false;
String name = null; // initialized to a default value.
System.out.println("Enter 'Q' to quit");
while(!finished) {
System.out.println("Enter name: ");
name = read.readLine(); // moved declaration outside of loop
if(name.equals("Q")) {
finished = true;
}
// do work with name
}
I have also modified your code a bit,
I have added a message to the user to indicate what terminates the input.
I have renamed your variable s to something more meaningful, because you are storing the user's name it seemed reasonable to change it to name.
As a force of habit, I have also initialized my variables with default values, so I assigned the name variable to null. Not totally necessary, but I consider it good practice.
Since I have assigned name a default value, I have moved it outside of your loop.
A simple way is to have users enter an empty line when they are done. You'd just check if line.equals("") or maybe trim it before.

Categories

Resources