Get String value from showOptionDialog - java

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
}

Related

Why is Java forcing me to initialize my String before letting the user input the value of the String?

I'm essentially making a small, simply "twenty questions" style program, using nested if-statements to try to guess what object the user is thinking based on clarifying questions.
I'm using the if statements to eventually give the user a "result" at the end, using a String variable called "result".
My ultimate confusion lies in which the compiler is stating that "variable response may have not been initialized". To which, based on the code, I would think it is after the if statements.
import java.util.Scanner;
public class TwoQuestions {
public static void main (String args[] ) {
Scanner kb = new Scanner(System.in);
String answer1, answer2, response;
System.out.println("\n[Two Questions]\nThink of an object, and I'll try to guess it.");
System.out.println("Is it an \"animal\", a \"vegetable\", or a \"mineral\"? (Type an answer exactly as quoted)");
answer1 = kb.nextLine();
System.out.println("Is it bigger than a breadbox? (yes/no)");
answer2 = kb.nextLine();
// example "response" based on user decisions
if (answer1 == "animal" || answer1 == "Animal") {
response = "yes";
if (answer2 == "yes" || answer2 == "Yes") {
response = "squirrel";
}
}
// more if statements...
// final machine "response" to user"
// TODO: Figure out why *this* "response" requires initialization before if statements.
System.out.println("My guess is that you are thinking of a " + response + ".\nI would ask you if I'm right, but I don't actually care.");
}
}
Like mad programmer said use String equals function to compare string.
Yes it will need to be initialize before compilation can take place. If Im not wrong you can initialize with Null, or " ", empty string.

int cannot be converted to String in showConfirmDialog using JOptionPane

I am trying to run the following piece of code in the main Java class:
personName = JOptionPane.showInputDialog("Enter the name of the person !");
onepty.setNameOfPerson(personName);
SpeechDecision = JOptionPane.showConfirmDialog(null,
"Select Yes or No", "choose one", JOptionPane.YES_NO_OPTION);
onepty.speechCheck(speechDecision);
The following method is defined in a data definition class which I am accessing via onepty object as shown above:
public String speechCheck(String str){
if(str == "Yes" || str =="YES"||str == "Y" ||str== "y"||str=="YEs"||str=="yeS"||str=="yES"){
this.speechVar = str;
}
else {
this.speechVar = str;
}
}
But I am getting the following error after compiling using jGrasp :
error: incompatible types: int cannot be converted to String
speechDecision = JOptionPane.showConfirmDialog(null,
^
1 error
Although the error is self explanatory but since I am net to jOptionPane, I am wondering whether the button input selected by the user after clicking on Yes or No option is getting stored as integer rather than string? Do I need to modify my speechCheck method to catch Integer value?Please advise.
The variable SpeechDecision is probably String, and it should be an int since that's the returned value from showConfirmDialog, see its signature:
public static int showConfirmDialog(...)
↑
Few notes:
Follow the Java Naming Conventions
Don't compare String using ==, use equals instead
Indent your code for better world
You can do something like that :
int speechDecision = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if (speechDecision == JOptionPane.YES_OPTION)
{
// Do something here
}
You have to use JOptionPane default constants
JOptionPane.YES_OPTION for YES and
JOptionPane.NO_OPTION for NO
and the type of SpeechDecision Should be integer.
So, Code will look like,
int speechDecision = JOptionPane.showConfirmDialog(null, "Select Yes No", "choose one", JOptionPane.YES_NO_OPTION);
if (speechDecision == JOptionPane.YES_OPTION){
// Do something here for yes
}
else{
// Do something here for no
}

The good usage of Boolean.valuesOf()

I have a question about the use of Boolean.valueOf(String). In my code the user will answer a question by entering either true or false. Then the String should be converted to a boolean.
public String setCorrespondingAuthor ()
{
String respons = "true";
do
{
System.out.print("Is s/he the corresponding author? (true/false)");
respons = sc.next();
sc.nextLine();
} while (!respons.equalsIgnoreCase("true")
&& !respons.equalsIgnoreCase("false"));
boolean flag = Boolean.valueOf(respons);
if (!flag)
{
return "not the corresponding author";
}
return "the corresponding author";
}
Right now, it works okay. The problem is that in the output, it prompts the question twice before treat it.
The problem is that you're reading twice from user input: sc.next() and sc.nextLine(). You should only read once and store that value in your respons variable.
You should also consider calling equalsIgnoreCase on String literals( such as "true" , "false") and not on variables, because variables might be null, resulting into a NullPointerException.
String respons = "true";
do
{
System.out.print("Is s/he the corresponding author? (true/false)");
respons = sc.nextLine();
} while (!"true".equalsIgnoreCase(respons)
&& !"false".equalsIgnoreCase(response));
return Boolean.valueOf(respons) ? "the corresponding author" : "not the corresponding author";

Catching value of JOptionPane input dialog with preset choices?

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.

Calling different classes with if else statements [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I'm writing a java program that is like a physics lesson:
import javax.swing.JOptionPane;
public class PhysicsClass {
public static void main(String[] args) {
int g = -1;
while (g<0){
String input = JOptionPane.showInputDialog("Welcome! What's your name? ");
if(input.length() > 0){
g++;
System.out.println("Great! Lets begin.");
}
else{
System.out.println(" ok then.");
System.exit(0);
}
}
String[] firstChoice = {"Kinematics", "Dynamics", "Impulse/Momentum", "Energy/Power"};
JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
int i = 0;
while (i<0){
String Choice = "";
if (Choice == firstChoice[0]){
Kinematics.IntroToKinematics();
i++;
}
else if (Choice == firstChoice[1]){
Dynamics.DynamicsIntro();
i++;
}
else if (Choice == firstChoice[2]){
ImpulseAndMomentum.ImpulseAndMomentumIntro();
i++;
}
else if (Choice == firstChoice[3]){
EnergyAndPower.EnergyAndPowerIntro();
i++;
}
else{
System.out.println("Please pick one.");
}
}
I want whatever choice you pick in the first choice array to then go to the respected class. So if I choose kinematics, it will call on the kinematics class, for which the first few lines are:
import javax.swing.JOptionPane;
public class Kinematics {
public static void IntroToKinematics() {
JOptionPane.showInternalMessageDialog(null, "Kinematics is one of the most basic"
+ " ideas of Newtonian Physics. It encompasses: speed, distance, time"
+ " displacement, acceleration and many key base concepts that form the the "
+ " foundation for most physic subjects. It will poke its head in everything"
+ "we cover.", "intro", JOptionPane.INFORMATION_MESSAGE);
}
}
It doesn't give me any errors but when I choose one of the strings from the array, it doesn't do anything. I think it might have something to do with the if else statements I used. Thanks for any and all help, I'm still relatively new to Java so any tips would be appreciated.
Use equals to compare strings like-
if(Choice.equals(firstChoice[0])){...}
First off you want to store the result of the input box somewhere:
String choice = JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
Then use .equals to do your string compares instead of ==
if (choice.equals(firstChoice[0])){
Kinematics.IntroToKinematics();
}
The loop shouldn't be necessary.
You're not binding Choice to selected value, it always compares it to ""
First at the showInputDialog you should do something like this
String Choice = "";
Choice= (String) JOptionPane.showInputDialog(null,
"Which one of these Topic would you like to start with?",
"Please pick a topic to start with",
JOptionPane.INFORMATION_MESSAGE, null,
firstChoice, firstChoice[0]);
Declaring first the variable Choice, and then asigning the inputDialog value to choice, afther that your while should be like this
int i = 0;
while (i<=0){
//do something
}
because the first time it runs i<0 , since 0 is not lower than 0 (since you are declaring int i =0;) is not going to run.
And you could keep using "", but something like this should be more efficient
if (Choice.equals(firstChoice[0])){
Kinematics.IntroToKinematics();
i++;
}
Finally try to use lowercase first at your variables eg: tableSize

Categories

Resources