string variable in if statment fail [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 1 year ago.
so I try to use a string variable in the if statement but it seems it doesn't work like int and double and other primitive data types, why? Pls help
my code:
import java.util.Scanner;
public class Something{
static void Some(){
Scanner input = new Scanner(System.in);
String answer;
System.out.println("Hello Sir, what can I do for you?");
answer = input.nextLine();
String i = "2";
if(answer == i){
System.out.println("Sure Sir ");
}
else{
System.out.println("Sir, anything?");
}
}
public static void main(String [] args){
Some();
}
}
input:2
output: Sir, anything?

The == operator compares references in case of strings. To compare values you can use equals() method.
if(a.equals(b)){}

Related

Java ArrayIndexOutOfBoundsException when reading user input [duplicate]

This question already has answers here:
How can I avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException? [duplicate]
(2 answers)
Closed 7 years ago.
Whenever I try to use anything higher than eq[0], I end up with an ArrayIndexOutOfBoundsException.
My code:
import java.util.Scanner;
public class Calc{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
String[] eq=in.next().split(" ");
double a=Double.parseDouble(eq[0]);
double b=Double.parseDouble(eq[-1]);
if(eq[1]=="+"){
System.out.println(">>"+String.valueOf(a+b));
}else if(eq[1]=="-"){
System.out.println(">>"+String.valueOf(a-b));
}else if(eq[1]=="/"){
System.out.println(">>"+String.valueOf(a/b));
}else if(eq[1]=="*"){
System.out.println(">>"+String.valueOf(a*b));
}
}
}
eq[-1] -1 index is problem
eq[1]=="+" // logical error use equals() method to compare String.
Scanner in=new Scanner(System.in);
String[] eq=in.nextLine().split(" "); // use nextLine() instead of next().
double a=Double.parseDouble(eq[0]);// 1st operand
double b=Double.parseDouble(eq[2]);// 3rd operand
if(eq[1].equals("+")){ //operator // compare string with equals method not with (==).
System.out.println(">>"+String.valueOf(a+b));
}else if(eq[1].equals("-")){
System.out.println(">>"+String.valueOf(a-b));
}else if(eq[1].equals("/")){
System.out.println(">>"+String.valueOf(a/b));
}else if(eq[1].equals("*")){
System.out.println(">>"+String.valueOf(a*b));
}
Firstly, eq[-1] the index should not be valid. I think it is only valid for Python.
Secondly, when you want to compare 2 strings, you should not use ==.
.equals function will help.

IF condition on strings [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
I'm writing a simple code to test the value that was inputted to my constant value.
I declared this code as my constant value.
String LetMeThrough = "drunk";
String GotAnID = "drunk";
This is the whole code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner DrunkTest = new Scanner(System.in);
String InputDrunk;
String InputDrunkAgain;
String LetMeThrough = "drunk";
String GotAnID = "drunk";
System.out.print("Type drunk: ");
InputDrunk= DrunkTest.next();
System.out.print("Re Type drunk: ");
InputDrunkAgain = DrunkTest.next();
if(InputDrunk == LetMeThrough & InputDrunkAgain == GotAnID){
System.out.print("You're not DRUNK");
}
else
System.out.print("You're F***** DRUNK");
}}
The problem is that if I type "drunk" on both.
I will get "You're F****** DRUNK" instead of the "You're not DRUNK".
When the inputted values is the same as my constant values.
You must use String::equals method to compare.

How do i save next string in scanner? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Iam making a basic calculator with 3 functions. Iam using a Scanner-utility to help me interact with the calculator. You enter the first number, then it saves it to a variable, You enter a second number and that is also saved to a variable. Then after that it asks you what you want to do with the numbers. You can choose between Multiply, Add, Subtract. But none of them seem to work, and i dont know why, but iam guessing that the String that is inserted after the question isnt saved or maybe iam using wrong method.
import java.util.Scanner;
public class MainClass {
private static final String Multiply = null;
private static final String Add = null;
private static final String Subtract = null;
public static void main(String[] args)
{
MainClass mainObject=new MainClass();
mainObject.Calculator();
}
public void Calculator()
{
double firstnumber;
double secondnumber;
double result;
String word1="Multiply";
String word2="Add";
String word3="Subtract";
Scanner scan=new Scanner(System.in);
System.out.println("Enter first number");
firstnumber=scan.nextInt();
System.out.println("Enter second number");
secondnumber=scan.nextInt();
System.out.println("What do you want to do?");
String operator=scan.next();
if(operator==word1)
{
result=firstnumber*secondnumber;
System.out.println(result);
}
else if(operator==word2)
{
result=firstnumber+secondnumber;
System.out.println(result);
}
else if(operator==word3)
{
result=firstnumber-secondnumber;
System.out.println(result);
}
}
}
The comparison operation between the strings is not == but the equals() method:
if(operator.equals("add"))
...
else if (operator.equals("subtract"))
...
else if (operator.equals("multiply"))
...
else
wrong input

String comparisons not returning correctly? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender == "boy"){
System.out.println("You are a boy.");
}
if(Gender == "girl"){
System.out.println("You are a girl.");
}
}
}
I'd like to know why this program isn't working. In Eclipse it says there is no errors but when i run it and type in boy or girl nothing happens and I don't see why.
Also please no making fun of the program I am testing myself on string variables.
If you are comparing Strings, don't use ==, but use equals():
if(Gender.equals( "boy" ) ){
System.out.println("You are cool.");
}
if(Gender.equals( "girl" ) ){
System.out.println("You are cute.");
}
In Java == compares object identities and not contents! So in your case your compare the object, you read in, with two others objects. This will always fail.
On the other hand equals() compares the contents of both objects and thus will succeed here.
This is probably a duplicate of this answer:
What is the difference between == vs equals() in Java?
Use equals instead of == in java for stirng comparison
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender.equals("boy")){
System.out.println("You are cool.");
}
if(Gender.equals("girl")){
System.out.println("You are cute.");
}
}
}
Use .equals() for string comparision not ==
I have just answered an answer: exactly same problem
Use equals method for string comparision.
== will not compare string object's string value it just checks for reference equality.
In this respect if you compare two string objects with same value they are not equal by == operator
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender.equals("boy")){
System.out.println("You are cool.");
}
if(Gender.equals("girl")){
System.out.println("You are cute.");
}
}
}
Just realized multiple same answers. Reason is same, use .equals instead of ==
import java.util.Scanner;
public class Poop {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
String Gender;
System.out.println("Are you a boy or a girl?");
Gender = input.nextLine();
if(Gender.equals("boy")){
System.out.println("You are cool.");
}
if(Gender.equals("girl")){
System.out.println("You are cute.");
}
}}
Use the .equals for string comparison.
if(Gender.equals("boy"))
Or you could intern the input like so, and then use ==
Gender = input.nextLine().intern();
if(Gender=="boy")
Interesting program though :D
I'm getting in on this...
== tests if the two String objects are the same object.
.equals() tests if the two Strings have the same "value"
Change your tests to if(Gender.equals("boy")) etc.
Java ain't javasript.

Java If loop don't get executed: Scanner [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
My second scanner input get stored as desired but still the if condition comparing correctString == stringValue is not executed.
Could you help.
{
static String stringValue = "A";
public static void main(String[] args) {
int time;
time = speedType();
//System.out.println(time);
}
private static int speedType() {
System.out.println("Let's play a game\nHow fast can you type \"I type very quickly\" \nPress Enter then type the statement and then press Enter again");
Scanner scanner = new Scanner (System.in);
String string = scanner.nextLine();
if(string.equals("")){
Date startTime = new Date();
System.out.println("Start:\n");
String correctString = scanner.nextLine();
System.out.println(correctString);
if (correctString == stringValue){
Date endTime = new Date();
System.out.println(endTime);
}
else
System.out.println("Please enter correct string");
}
return 0;
}}
Regarding,
if (correctString == stringValue){
Don't compare Strings using ==. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in right now. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of
if (fu == "bar") {
// do something
}
do,
if ("bar".equals(fu)) {
// do something
}
or,
if ("bar".equalsIgnoreCase(fu)) {
// do something
}

Categories

Resources