Java executuion of else is expected but always if is executing [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
I think you have understood what I am trying to do. Give a prompt when user press OK without changing he default TEXT. But the first condition seems to be TRUE. I don't know if it is a problem of if statement or my code.I have included the whole class .Be sure to read comment to avoid reading unnessasary code.
ok = JButton
text = JTextField
int c = 0;
public class handler implements ActionListener{
public void actionPerformed(ActionEvent e){
//
//The following lines are not nessary for the question.
if(ok==e.getSource()){
if(!(male.isSelected() || female.isSelected()) && c==0){
c++;
JOptionPane.showMessageDialog(null,"Hey you haven't selected your gender. Do you wish to proceed","Warning",JOptionPane.PLAIN_MESSAGE);
}
}
//well these lines were not necessary
//They were just in the same class
//
//
//Here the else condition should execute
//
if(ok==e.getSource()) && (text.getText() != "Enter your name")){
JOptionPane.showMessageDialog(null,"Your name is "+text.getText(),"Name",JOptionPane.PLAIN_MESSAGE);
}else if((ok==e.getSource()) && (text.getText() == "Enter your name")){
JOptionPane.showMessageDialog(null,"Hey type in your name buddy ","Name",JOptionPane.PLAIN_MESSAGE);
}
}
}
So the problem is that the if condition gets executed, while the else if should when we are not changing the default text "Enter your name". I tried changing the text and in that condition also the if block is executing. And please do a full explanation of your answer. I am a beginner with rusted skills.

You need use other method to compare the strings, for example here:
text.getText() == "Enter your name")
you can use equals:
text.getText().equals("Enter your name")
You should do it in the two places into your original code.

Related

How to end do while loop with user input with if statement [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
boolean a = true;
do {
Scanner input = new Scanner(System.in);
System.out.println("Press any on keyboard:");
String keys = input.nextLine();
System.out.println("You pressed:");
System.out.println(keys);
System.out.println("Your hash is:");
String B = "#B";
String hash = B+keys;
System.out.println(hash);
System.out.println("To end loop press f");
//End Loop
Scanner exit = new Scanner(System.in);
String end = exit.nextLine();
if (end=="f") {
a=false;
}
}
while(a);
}
}
I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
use break statement under if(){} body. also your == comparison will give false, use str1.equals(str2) for comparison.
Your problem is you are comparing strings with ==.You have to use equals to write correct if statement.
if (end.equals("f")){...}
You could use the below code to check
if (end.equals("f")) { // end == "f" , it check the reference.
a = false;
}

java equalsIgnoreCase() in a do-while loop always returning false; [duplicate]

This question already has answers here:
Why does non-equality check of one variable against many values always return true?
(3 answers)
Closed 7 years ago.
I'm simply trying to determine if the user has entered a YES or NO value (disregarding caps though, hence equalsIgnoreCase()). However, regardless of me entering YES or NO, the do-while doesn't break E.G.
public int addInformation() {
final int YES = 1;
final int NO = 0;
String userDecision = "";
try(Scanner scanner = new Scanner(System.in)) {
System.out.println("Add Information Now? [YES/NO]");
do {
System.out.println("Please Enter YES or NO ");
userDecision = scanner.nextLine();
} while(!userDecision.equalsIgnoreCase("yes") |
!userDecision.equalsIgnoreCase("no"));
}
if(userDecision.equalsIgnoreCase("yes")) {
return YES;
}
return NO;
}
I'm looking for the behavior of "while the input value is not equal to 'yes' OR 'no', ask for the data again". However my code suggests "disregard whatever is typed, let's just keep looping for fun..." Where did I go wrong, Stack? thanks
This condition
while (!userDecision.equalsIgnoreCase("yes") |
!userDecision.equalsIgnoreCase("no"))
is always true. Any string must be EITHER not equal to "yes" OR not equal to "no".
If you mean to check that the string is not equal to either, you mean this:
while (!userDecision.equalsIgnoreCase("yes") &&
!userDecision.equalsIgnoreCase("no"))
Your condition is incorrect. You want to end the loop if either condition is false (so you need an and). Something like,
while(!userDecision.equalsIgnoreCase("yes") &&
!userDecision.equalsIgnoreCase("no"));

Can't figure out why my method isn't executing [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
Below is a snippet of code from a class in a simple program I'm writing that plays a simple game of Blackjack. I don't understand why the hit method isn't executing whenever, upon execution of the program, I enter "hit". It goes to the else part of the statement every time regardless of what I enter. I even added a System.out.println statement to make sure that the strings matched. I feel like I must be making a very basic mistake but I just can't seem to figure it out.
System.out.println("Would you like to hit or stand?");
Scanner input = new Scanner(System.in);
String playerDecision = input.nextLine();
//System.out.println(playerDecision);
if(playerDecision == "hit") {
hit();
}
else { System.out.println("ERROR");
}
}
public void hit(){
player.makeHand(deck.draw());
System.out.println("You have the following cards: ");
player.getHand();
System.out.println("Your hand total is ");
System.out.println(player.findHandTotal());
}
Wrong string comparison. Try
if("hit".equals(playerDecision)) {

Detecting Numbers in a String Variable (In Java) [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
So, normally for detecting user input, I use int and double variable types.
Example:
Scanner in = new Scanner(System.in);
int selection;
System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
selection = in.nextInt();
if(selection == 1){
System.out.print("you are a soldier");
}
else{
System.out.print(selection);
}
}
This technique usually works fine for me, but I noticed that if the user inputs a letter into the int variable, the game will crash because integers can't store letters. (right?) So I tried using a String variable in its place, like this:
Scanner in = new Scanner(System.in);
String selection;
System.out.println("Welcome to RPG! (prototype name)\nIn this game, you do stuff.\nChoose a class:\n1. Soldier\n2. Knight\n3. Paladin\n4. Heavy");
selection = in.next();
if(selection == "1"){
System.out.print("you are a soldier");
}
else{
System.out.print(selection);
}
}
This seemed to work at first, but as you can see, I have it set so that if the variable "selection" is equal to 1, that it will print "you are a soldier", yet this did not work, instead it printed out the "selection" variables value (1). Did I do something wrong or should I use a different type of variable?
you can use something la this :
try{
int type = Integer.parseInt(selection);
switch(type){
case 1:{
//do soldier stuff
}
case 2:{
// do knight stuff
}
default:{
//do other stuff
}
}
}catch(NumberFormatException exc ){
System.out.println(selection + "is not a number, try again!!!");
}
selection == "1"
Compare strings with String#equals.
"1".equals(selection)
There are lots of ways to do this. A quick point I'd like to make is if you're comparing strings you should use:
var.equals("string");
Since you're only taking one character you could use a character in which case the correct syntax would be:
var == '1'
If you want to be fancy you can do a try catch around your read statement and just read in an string and parse it to an integer, but that is a bit more advanced.
change selection == "1" to "1".equals(selection)
use .equals() for comparing the string "1" and selection and read this A simple explanation would be
x == y returns true only when both x and y refer to same object which is not in your case. equals check if contents are equal meaning if contents of memory location that x and y are referring to are equal or not.

I Cannot Get If/Else Statement to Prove True with Scanner [duplicate]

This question already has answers here:
Can't get else if statement to work in Java
(5 answers)
Closed 10 years ago.
Help. I'm new to Java programming so I'll try to make the best of your terms.
I was wondering how to get this program to register as true. When I type in "password" as an input, it does not execute any code from the "if" body. I also pasted this code in another class and it still doesn't work, regardless.
I've worked on this program for about a half an hour, and debugging it for twice as long. Please look through the coding.
import java.util.Scanner;
public class whileloop {
public void whileloop1() {
//DEBUG THIS PROGRAM! "password" does not work for input
System.out.println("Please enter the password to continue: ");
Scanner password = new Scanner(System.in);
String passwordinput = password.nextLine();
System.out.println("This is your entered password: " + passwordinput);
if (passwordinput == "password") {
System.out.println("Startup sequence has been iniciated.");
System.out.println("System is working correctly.");
//Terminate all here ---
} else {
System.out.println("Wrong password! Terminating program. /END");
}
System.out.println("Supressing the program's scanner!");
password.close();
}
}
When comparing string content in Java you use the .equals() method.
The == operator checks for reference equality, meaning, testing if they are both references of the same object.
So, in your case:
if(passwordinput.equals("password"))
This has been said many times, but I'll say it again, when comparing Strings in java, if you want to know if they point to the same reference use the == operator. if you want to check if they are equal in value use .equals("somestringhere") In your case use passwordinput.equals("password")
Since, in Java the line:
String s; declares a reference to a String object, unlike C++, which may declare an object of String.
So, the line if (passwordinput == "password") compares the reference of "password" and reference of passwordinput, the result will be false.
So, use if(passwordinput.equals("password"), which compares the object referenced by passwordinput with "password"

Categories