I am using a JOptionPane with input dialog. I am having trouble catching the value of the choice so that I can use it later in my program.
String[] options = {"Selection Sort", "Insertion Sort"};
Object searchType = JOptionPane.showInputDialog(null, null, "Choose a sort type ",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
…and this is what it looks like.
edit: I am having trouble catching the option that is chosen by the user.
I have tried:
int selection = JOptionPane.QUESTION_MESSAGE;
and that will compile, however I can't actually use the value.
basically when a person selects one of the two options I want to know which one it is.
edit2: For future reference this works:
Object selection = searchType;
if(selection.equals(options[0]))
{
//something
}
else if(selection.equals(options[1]))
{
//something else
}
I think you should read the JavaDocs a little close...
Returns:
user's input, or null meaning the user canceled the input
This means, if the use selected Okay, that it will return the item the user selected as listed by the options parameter. In your case this will be Selection Sort or Insertion Sort or null if they canceled the dialog
Updated with example
Using this and selecting [Okay] outputs Selection Sort
String[] options = {"Selection Sort", "Insertion Sort"};
Object searchType = JOptionPane.showInputDialog(null, null, "Choose a sort type ",
JOptionPane.QUESTION_MESSAGE, null, options, options[0]);
System.out.println(searchType);
Take a closer look at How to Make Dialogs for more details
You should check the object returned and compare it to the items held in your array.
Either that, or call toString() on it and use the String value returned to decide.
Related
Basically i want to enter the names as long as i don't cancel the InputMessageDialog, then i want to asign my names to variable created before and print them out at the end in the MessageDialog. I was trying some stuff outside the loop but got the notificacion that "value 'names' is always 'null'"
String names;
while (true) {
names = JOptionPane.showInputDialog(null, "ENTER THE NAMES");
if (names == null) {
JOptionPane.showMessageDialog(null, "ENTRY CANCELED!");
break;
} else {
}
}
JOptionPane.showMessageDialog(null, "YOUR NAMES: " + names);
Your code is pretty close to what you describe as your goal – the primary thing missing is that you need to keep track of the various values along the way, and print them at the end.
The code you posted will loop again and again asking for a single value (which you are storing into String names - a little confusing choice for variable name, since it contains only one name input). As you found, when the user hits the cancel button (to end the loop), it sets names to null. The final step shows a dialog box with the last value for names (which is always null).
Here's a program that:
loops until the user hits the "cancel" button (which would set input to be null), or if they enter a blank value – this allows the user to exit by simply hitting return without typing anything
adds all non-empty input values to a java.util.Set – this is an arbitrary choice, use whatever data structure is appropriate for your program
shows a final dialog with the contents of the set
import javax.swing.*;
import java.util.HashSet;
import java.util.Set;
public class t {
public static void main(String[] args) {
Set<String> values = new HashSet<>();
while (true) {
String input = JOptionPane.showInputDialog(null, "enter something");
if (input != null && !input.isEmpty()) {
values.add(input);
} else {
break;
}
}
JOptionPane.showMessageDialog(null, "all values: " + values);
}
}
If I run with the following input:
one
two two
three three three
<blank>
Then the final dialog message is:
all values: [one, two two, three three three]
Note that a java.util.Set doesn't necessarily return items in any specific order, it just happens to have worked out that way in this example.
Hi guys I know this is a weird question but can an object return to being zero? I'm asking because I have a huge design flaw with a basic GUI that i'm running where if I answer what I wanted on a menu it would continue to use the same old answer.
To get around that I would ask again on the lower part but then I ran into a worse problem..it kept on asking. I feel trapped tbh and I can't find anyway inside my programming book to reset or get around this.
Object[] menuPossibilities = {"Create a New Account", "Deposit", "Withdraw", "Display Balance", "Exit"};
Object menuValues = JOptionPane.showInputDialog(null, "Please pick an option from this menu: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
while (!menuValues.equals("Exit")){
Bank newBank = new Bank();
// Bank newBank1 = new Bank();
// Bank newBank2 = new Bank(); Do the same thing as below but switch out
// bank1 and bank2 as a substitute.
ArrayList<BankAccount> bankList = newBank.getBankAccounts();
if (menuValues.equals("Create a New Account")){
newBank.openAccount();
}
else if (menuValues.equals("Deposit")){
newBank.deposit();
}
else if (menuValues.equals("Withdraw")){
newBank.withdraw();
}
else if (menuValues.equals("Display Balace")){
newBank.deposit();
}
else if (menuValues.equals("Exit")){
System.out.println("Thank you for using our service.");
}
Object menuValuesTWO = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
}
The above is the code I have in case I wasn't very clear. But basically If I take out the menuvalueTWO and hit the create bank account then it'll loop back around and say "So wanna make another bank account?".
Object menuValuesTWO = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
should be
menuValues = JOptionPane.showInputDialog(null, "Since you did not pick 5 please pick another option: ",
"input", JOptionPane.INFORMATION_MESSAGE, null, menuPossibilities, menuPossibilities [0]);
I can't validate the change as I cannot run your code. But as #Stephen C suggested you must use the same object that you are looping on.
... can an object return to being zero?
Not unless some method explicitly sets it to zero.
In cases like this the problem is typically something else; for example, that you are actually looking at different objects.
In your example, it looks like you have made some mistakes in the way that you have modeled and/or implemented operations like openAccount, deposit and withdraw. I would expect:
openAccount() should return the BankAcount it created, and also add it to the Bank's bank account list.
deposit() should be an operation on a BankAccount and should take a parameter saying how much to deposit.
withdraw() should be an operation on a BankAccount and should take a parameter saying how much to withdraw.
And so on.
(Alternatively, if deposit and withdraw are operations on the Bank object, then they need another parameter - an account number? - to say which account to operate on.)
String[] enrollment = {"first Value", "second value"}
int enroll = JOptionPane.showOptionDialog(null,
"Please select your enrollment:", "Enrollment",
JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null,
enrollment, enrollment[1]);
How can I get the value from enroll (like first Value) and compare it in a if statement? Since enroll returns an integer variable.
I dont think this question is a duplicate as marked because I am just trying to get the value inside the integer, store it and compare later.
You may have to do something like this in your if/else checking
if (enroll != JOptionPane.CLOSED_OPTION) {
System.out.println(enrollment [enroll ]);
} else {
System.out.println("No option selected".);
}
if (enroll == 0) { // 0 here is the first thing in the enrolment array
// do something
}
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());
I'm writing an app that takes in an input from the AddBook class, allows it to be displayed in a List, and then allows the user to Search for their book. To this end, I'm creating a temporary EditText, binding it to the box where the user actually enters their search value, then (after ensuring that it is not empty) I compare what they've entered for the ISBN number with the ISBN numbers of each entry in the arrayList of <Book> custom objects, the list being named books.
Problem is, when I try to parse the EditText into an Int, it doesn't seem to work. I first tried using toString() on the EditText, then using Integer.parseInt() on the result of that method, but it hasn't worked out, as the conversion is seemingly unsuccessful;
All of the resources are in place and the code compiles properly, so those aren't the problems here.
EditText myEdTx = (EditText) findViewById(R.id.bookName);
if(myEdTx.getText().equals("")){Toast toast = Toast.makeText(this, "Please enter something for us to work with!", Toast.LENGTH_SHORT);
toast.show();}
else{
//resume here
for(int i=0; i<books.size(); i++)
{
Book tBook = new Book(i, null, null); tBook = books.get(i); String s=myEdTx.toString();
int tInt = Integer.parseInt(s);`
To get the string representation of an EditText's content, use:
String s = myEdTx.getText().toString();
Using toString() directly on the EditText gives you something like:
android.widget.EditText{40d31450 VFED..CL ......I. 0,0-0,0}
...which is clearly not what you want here.
You assume the user inputs a number into the text field, but that is unsafe, as you only get a string text (which theoretically can contain non-numbers as well). When I remember correctly, you can adjust a text field in android where a user only can input numbers, which should suit you more.
NumberFormatException occurs when Integer.parse() is unable to parse a String as integer, so, its better to Handle this exception.
String s = myEdTx.getText().toString();
try {
int tInt = Integer.parseInt(s);
} catch( NumberFormatException ex ) {
//do something if s is not a number, maybe defining a default value.
int tInt = 0;
}
So the current String here you are trying to parse is with white space in the line
and integer class unable to parse that white space. So use following code.
String s=myEdTx.getText().toString();
int tInt = Integer.parseInt(s.trim());
String s = myEdtx.getText().toString().trim();
int iInt = Integer.parseInt(s);