int cannot be converted to String in showConfirmDialog using JOptionPane - java

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
}

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.

Error: unexpected type required: variable found: value

Im trying to make this variable int stringSize to print "ok" or "not ok" depending on the if statement.
Heres what i have:
int stringSize = (n_1 + n_2 + n_3);
if (stringSize < 20){
String.valueOf(stringSize) = "ok";
}else if (stringSize > 20){
String.valueOf(stringSize) = "not ok";
}
Theres more code but its irrelevant to the question, I think. Nevertheless everything is defined except until here.
I know i cant just put it equals to the "ok" so how do i get the stringSize to print either "ok" or "not ok"?
Im a beginner, so lets be nice and i tried looking up other solutions but none were similar to my case
TY in advance
In your code, stringSize is an integer, to store a string like "ok" or "not ok", you should use a String variable. Declare a String variable and store the value in that. For example -
int stringSize = (n_1 + n_2 + n_3);
String message = null;
if (stringSize < 20){
message = "ok";
}else if (stringSize > 20){
message = "not ok";
}
Moreover, String.valueOf() returns the string representation of the parameter where you cannot assign another value. For example, String.valueOf(stringSize) will return "15" if the value of stringSize is 15.
How do i get the stringSize to print either "ok" or "not ok"?
Just put the following line wherever you want to print the message. [following the example given above]
if(message != null){
System.out.println(message);
}
String.valueOf(stringSize) is an expression, you cannot assign a value to an expression. In fact, an expression has a value. All you need is to define a variable of type String: String message = "ok";
You can't assign a value to the result of an expression, however you mentioned you want to print the value. You can do that. Like,
if (stringSize < 20){
System.out.println("ok");
} else { // <-- if it should be ok or not ok, use else.
System.out.println("not ok");
}

Get String value from showOptionDialog

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
}

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");

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