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

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
}

Related

Java - IF condition not reading entered String variable value [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String play = "y";
System.out.print("Enter something: ");
play = scan.next();
System.out.println(play);
if (play == "Y" || play == "y")
{
System.out.println("If test works!!");
}
System.out.println("Did it work???");
}
}
I assume this has something to do with when I press enter, it's storing that as well. I tried changing String play to a char, but then I get errors from Scanner saying it can't change a String to a char.
You should atmost avoid using “==“ when comparing objects especially strings. “==“ checks for object references. Change the comparison to use .equals method and it should work
if(play.equals(“Y”) || play.equals(“y”))
in case if “play” can be null, the below snippet is more safe.
if(“Y”.equals(play) || y.equals(play))

String input and if [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
public class LabWork {
private String yourStatus;
private int yourIncome;
private double tax;
public int calculateTax () {
if (yourStatus = "Married" && yourIncome <= 2000) {
tax = yourIncome/10;
}
else if (yourStatus = "Married" && yourIncome > 2000) {
tax = 3*yourIncome/20;
}
else if (yourStatus = "Single" && yourIncome <=2000) {
tax = 17*yourIncome/100;
}
else
tax = 22*yourIncome/100;
}
public double getTax () {
return tax;
}
}
this is my first code and I have a tester class to use this like:
import java.util.Scanner;
public class UseLab3Work {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is your status? ");
String yourStatus = keyboard.next();
System.out.println("What is your incomew? ");
int yourIncome = keyboard.nextInt();
}
}
However, in the first program, I'm getting an error like "String cannot be converted to boolean" at line 7,10 and 14. Then how should I use if with String? For example I have input in tester and when I write there Married, the program should calculate tax related to my String input.
I first would have thought to mark this a duplicate, since you are comparing your Objects wrong, but it's a step further.
if (yourStatus = "Married" )
Here, you don't compare the values of the String, you actually just assign it.
if (yourStatus == "Married")
This would be better, but will produce false results. After all, the == operator is used for referential comparison, while you want to compare values.
if (yourStatus.equals("Married")) (or if (yourStatus.equalsIgnoreCase("Married")) )
would be better, since this is the correct way to compare the values of Strings.
An even better way would be:
if ( "Married".equals(yourStatus))
In the other order, if yourStatus is null, it will throw a NullPointerException, which you avoid by calling equals (or equalsIgnoreCase) on the String literal.

While loop skipping over if statements? [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 7 years ago.
This is a program that runs a Conways Game of Life simulation.
The main method is here:
public static void main(String Args[]) {
int x = 0;
int y = 0;
boolean cellState[][] = new boolean[][]{};
boolean newCellState[][] = new boolean[][]{};
String answer;
Scanner input = new Scanner(System.in);
while (true) {
System.out.print("\n Type anything for next generation, 'new' for new grid, or 'stop' to end>> ");
answer = input.nextLine();
if (answer == "new") {
cellState = newCells(cellState);
} else if (answer == "stop") {
break;
} else {
System.out.println("Not an option yet");
}
}
}
No matter what answer is entered it will skip past the if statements and return to the beginning of the loop.
It has nothing to do with the actual contents of the statements as far as I can tell, but its might have to do with the boolean expressions.
You should use .equals() to compare Strings and not ==.
== is used to check object references, while .equals() checks the String values.
Use: if(answer.equals("new")) and you should be golden.
It has been explained very thoroughly here.
I'll recommend to do it like this:
if ("new".equals(answer)) {
cellState = newCells(cellState);
} else if ("stop".equals(answer)) {
break;
} else {
System.out.println("Not an option yet");
}
Strings can be compared with == as well, if and only they are internalized. Strings initialized with double quotes are already internalized.
So, in your case, you can do just this.
answer = input.nextLine().intern();

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.

Need to fix program in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I want user to input text while it is not equal to "start".When it is equal to "start" I want to show "Bravo".In my code when I enter "start" it just continue to ask to input a text.What is missing in my code to process the operation i described.
import java.util.Scanner;
public class Application {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String komanda = "a";
do {
System.out.println("Unesi komandu ");
komanda = input.nextLine();
}
while(komanda != "start");
System.out.println("Bravo");
}
}
You have to use the equals method to compare strings in java:
while (!komanda.equals("start"));
or even better
while (!"start".equals(komanda));
this does not crash if komanda is null
See How do I compare strings in Java? for more information.
do it this way
Scanner input = new Scanner(System.in);
String komanda = "a";
do {
System.out.println("Unesi komandu ");
komanda = input.nextLine();
}
while(!"start".equals(komanda));
System.out.println("Bravo");

Categories

Resources