Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to ask user to insert operator and get the answer till user enters keys other than +,-,* or \ .I did the program like this.But it will not work properly.Its looping even for other keys.What is the problem with the coding?
public static void main(String Args[]) throws IOException
{
InputStreamReader myrdr=new InputStreamReader(System.in);
BufferedReader myBfr=new BufferedReader(myrdr);
Scanner myScanner=new Scanner(System.in);
String mathOp;
float Res,Num1,Num2;
System.out.print("Mathematical Operator :");
mathOp=myBfr.readLine();
Res=0;
while(mathOp!="+"||mathOp!="-"||mathOp!="*"||mathOp!="\\")
{
System.out.print("Enter number one: ");
Num1=myScanner.nextInt();
System.out.print("Enter Number Two: ");
Num2=myScanner.nextInt();
switch(mathOp)
{
case "+":
Res=Num1+Num2;
break;
case "-":
Res=Num1-Num2;
break;
case "\\":
Res=Num1/Num2;
break;
case "*":
Res=Num1*Num2;
break;
default:
{
System.out.println("Programme Exits");
return;
}
}
System.out.println("Answer is : "+Res);
System.out.print("Mathematical Operator :");
mathOp=myBfr.readLine();
}
}
Don't use == (which compares if the 2 operands are the same String object, which they aren't), use equals() (which compares if the contents of the 2 String objects are the same).
But better yet, simplify your code to this:
while (!"+-*\\".contains(mathOp))
btw, divide is usually a normal slash /, not a backslash \.
Yoy have to use someting like that
while((!mathOp.equals("+"))||(!mathOp.equals("-"))||(!mathOp.equals("*"))||(!mathOp.equals("\")))
First of all you should know the proper use of || and &&
True || False returns true
True || False || False || False returns true,one True is enough to make the condition return true no matter how many false you have
So in your case you are saying that if the input is different from one of them than let it proceed,so if you have + it will enter since + is different that -. You should instead use &&.
True && False returns False
True && True && True && False returns False. One False is enough to return False no matter how many True you have.
If you use && you would be telling the condition to return true only if all the sub-conditions are true,i.e it is different than + and different than - and different than * and different than .
Moreover, replace your "+" by '+' because the latter it is a character while the first is a string. == can be used only on characters,numbers and boolean values. To compare Strings you should use .equals("x")
Make your while loop like this
while(mathOp.equals("+") || mathOp.equals("-") ||
mathOp.equals("//") || mathOp.equals("*"))
Use String.equals() to compare string in Java, not == or !=. To explain more, you shouldn't use == or != while comparing String values in Java because they check for equality for the values in the right and left operands. i.e a memory address in case of String objects ,which will not be equal for two different objects. You can make use of == and != with primitive datatypes and compile time constants. There is also a concept called String constant pool which has the compile time String constants created by using assignment operator like String new = "new"; without using new operator during object creation which can be compared using == or !=.
Related
This question already has answers here:
What is the difference between == and equals() in Java?
(26 answers)
Closed 10 months ago.
I am within my first year of CS and near the end of my first Java themed course so I'm not quite sure how to find the answer to my question myself.
While writing some code for a project I created my input scanner as:
Scanner scanner = new Scanner(System.in);
I am taking user inputs as strings via a variable assignment:
String userInput = scanner.nextLine();
the user should only be entering strings of char "1" - "6" and "q" (to quit app)
What I'm using that works currently is as follows:
userInput = scanner.nextLine();
while (!appQuit) { //So long as user doesn't quit application
if (userInput.equals("q")) {
appQuit = true;
}
else if (userInput.equals("1")) { //Menu selection for intake a new dog
intakeNewDog(scanner);
displayMenu();
userInput = scanner.nextLine();
}
//removed "2" - "6" for brevity
else {
System.out.println("Not a valid input");
displayMenu();
userInput = scanner.nextLine();
}
}
The only way I found to check equality was the userInput.equals() function.
When I originally wrote it I tried using:
if (userInput == "1") { code }
but it would never successfully compare values as I thought it would.
Any insight into why one method works over the other? Or where I should be looking for these answers?
-Jonesy
The == equal operator compares the object references where the equals function compares the value.
For primitive types and enums the == equal operator compares the value.
An exception happens for comparing strings in a switch case statement since it internal uses the equals method.
As a rule of thumb, always use equals comparison for String. There maybe is, but i have not seen a case where reference comparison was important.
https://docs.oracle.com/javase/8/docs/technotes/guides/language/strings-switch.html
Also interesting:
What makes reference comparison (==) work for some strings in Java?
In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. You can override the equals method to do more specific things, but that's the just of it.
This is literally the first thing that appears if you search java == vs equals in google.
While you might be trying to compare two strings, the operator == does not behave in java as it does in other languages.
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
First off, I know this might have been answered SOMEWHERE but I can't seem to search for the correct terms to get an answer. Also, I'm pretty new to coding, and obvious here, so this probably won't be the best written 'question'.
Quick backstory: I'm coding a sorting game in BlueJ(I know... shitty, but it's what we are learning in school), and for a method I'm creating for any yes/no questions I need isn't working properly. At first, I was having an issue with it allowing to to have the user input save as a String, now I'm having an issue with that String used in the if-else statement parameters. This is what I have right now:
public void userAnswer(int method) //used for yes/no questions
{
System.out.println("Please type 'y' for yes and 'n' for no.");
String answer = keyboard.next();
answer.toLowerCase();
System.out.println(answer + "worked");
if(answer == "y")
{
System.out.println("worked2");
if(method == 0)
completeOrNot();
if(method == 1)
usersMove(theArray);
}
else if(answer == "n")
{
System.out.println("worked3");
System.out.print("\n");
}
}
I'm completely stuck as to why it's not moving into the if-else statement. I test to see if it would print the String, and it will, but it won't convert it to lower case. I just don't know what to do. Any and all help would be appreciated!
When comparing Strings in Java, use the equals() method. Otherwise, you compare their memory locations if you use ==.
"hi".equals("hello") returns False
"hello".equals("hello") returns True
Don't use == to compare strings. use equals:
answer.equals("y")
Strings in Java are objects - you need to evaluate with the equals method for equality, not the == operator for reference identity:
if ("y".equals(answer)) {
// code
} else if ("n".equals(answer)) {
// code
}
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm writing a simple program and in it I need to get a user's input for yes/no (I'm using Scanner, UI, for this) like so:
System.out.println("Do you know the insulation capacity? (y/n) ");
String IC = UI.nextLine();
And that works perfectly fine, but I have trouble in the next section, where I check the string in an if statement:
if(IC == "y" || IC == "Y" || IC == "yes" || IC == "Yes"){ //four options of saying "yes"
System.out.print("What is the insulation capacity? ");
m = UI.nextDouble();
}else if(IC == "n" || IC == "N" || IC == "no" || IC == "No"){ //four options of saying "no"
findM();
}else{
System.out.println("Answer was not clear. Use y, n, yes, or no.");
checkM();
}
When I run the program, the else is always executed, even if IC is Y, y, Yes... etc.
Why is this the case and how do I get this to work?
Thanks,
-Justice
You should compare Strings with equals instead of ==. Otherwise, you'll be comparing the references, not their value, which is what you want.
Also, in this case equalsIgnoreCase may be helpful for you. You would only need 2 comparisons instead of 4.
Example:
if(IC.equalsIgnoreCase("y") || IC.equalsIgnoreCase("yes"))
You cannot compare Strings in Java using == operator. Use equals instead as for every Object-Type. In your case best solution is to use condition like ic.equalsIgnoreCase("y") || ic.equalsIgnoreCase("yes")
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
So, for some reason I'm having problems just USING a string input.
I don't know why. Maybe it's some incredibly stupid thing everyone knows, but I don't.
Here's the non-functioning code:
import javax.swing.*;
public class Thing {
public static void main(String[] args) {
String input;
JOptionPane.showMessageDialog(null,"Welcome to the test...");
input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
String i = input;
if(i == "Yes") {
tutorial();
} else if(input=="'Yes'") {
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
} else {
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
}
Yes, I actually do have a tutorial method somewhere else, and it works fine.
The main problem is that if I enter 'Yes' or Yes, it still goes to the final else.
I only put in the
String i = input;
and changed it from
if(input == "Yes") {
because it didn't work then, either.
So what am I doing wrong?
Don't use the == operator to compare Strings, use equals() instead, as thoroughly explained here, here, here, here or any of the numerous duplicates.
if ("Yes".equals(input))
Or even
if ("yes".equalsIgnoreCase(input))
Notice that the operation is invoked on the "yes" literal to avoid a possible NullPointerException in the case input was null and the operation was invoked on it (Yoda condition).
From the Java Language Specification, Chapter 15 - Expressions, section 21 - Equality Operators:
15.21.3. Reference Equality Operators == and !=
While == may be used to compare references of type String, such an equality test determines whether or not the two operands refer to the same String object. The result is false if the operands are distinct String objects, even if they contain the same sequence of characters (ยง3.10.5). The contents of two strings s and t can be tested for equality by the method invocation s.equals(t).
As mentioned, the problem is that you are comparing this String using the == comparator, not the .equals() method.
If you are running on Java 7, my advice, for a cleaner solution, would be also to wrap this in a switch statement:
JOptionPane.showMessageDialog(null,"Welcome to the test...");
String input = JOptionPane.showInputDialog("Do you wish to take the tutorial?" + "\n" +
"If affirmative, enter 'Yes'");
switch (input) {
case "Yes":
tutorial();
break;
case "'Yes'":
JOptionPane.showMessageDialog(null,"Don't actually put apostraphes around you're answer.");
tutorial();
break;
default:
JOptionPane.showMessageDialog(null,"Remember, you can pull up the tutorial at any time with 'T'");
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I have been having difficulties using nextLine() to get a string, and then use it as a test condition (either in an if statement or a while loop). Looking at the println(), it seems as if the String is correctly assigned to the variable 'repeat' but then the test condition fails for some reason. Banging my head on the wall, bleeding from my forehead. Please help.
import java.util.Scanner;
public class potpie {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
String repeat = "yes";
System.out.println("Type in yes");
repeat = input.nextLine();
System.out.println("If repeat is now yes, print yes: " +repeat);
if(repeat == "yes"){
System.out.println("It worked");
} else
System.out.println("it failed");
}
}
You should use equals. == provide you reference equality and equals provide you value equality.
if("yes".equals(repeat)){
instead of
if(repeat == "yes"){
I would advice you to get eclipse/net beans and start debugging or a simple search would have resulted in the answer
Java Debugging with Eclipse - Tutorial
if(repeat == "yes"){
should be
if(repeat.equals("yes"){
(or)
if("yes".equals(repeat){
Every day we see this question lot of times, simple search could have provided you sufficient information.
== equals for primitive comparison (reference equality). equals() is for String (or) Object comparison (object content equality).
Sometimes == should be used for objects, but what it is actually comparing is whether a and b are literally the same object (have the same address in memory). As the others have said, you are comparing content in this situation, so you use .equals()