Q. Logical Operators

0 Mohammed Al Mubaireek · May 11, 2015
Hello , 
thanks for these videos which are very useful for me :)

you said we can make double of if statement

import java.util.Scanner;

public class IFSTATMENT {
private static final String mhhm = null;

public static void main (String args []){
System.out.println("Please. Enter The Password");
Scanner kb= new Scanner(System.in);
int password;
int Year;
password=kb.nextInt();
System.out.println("Please. Enter The UserName");
Year=kb.nextInt();
if(password==12345 && Year == 2012){
System.out.println("Welcome Mohammed To JAVA Program");
}
else{
System.out.println("Error: You Are Not Allow to Acces This File");

}


}

}


I would like to ask , Am I able to make it with string , like this .>>

import java.util.Scanner;

public class FruitDriver {
 private static final String mhhm = null;

 public static void main (String args []){
  System.out.println("Please. Enter The Password");
  Scanner kb= new Scanner(System.in);
 int password;
 password=kb.nextInt();
 int name;
 System.out.println("Please. Enter The UserName");
 name=kb.next();
 if(password==12345 && name =="car"){
  System.out.println("Welcome Mohammed To JAVA Program");
 }
 else{
  System.out.println("Error: You Are Not Allow to Acces This File");
  
 }
 
 
 }

}


if not , could you tell me how to do it ? 
Regards,
Mohammed 

Post a Reply

Replies

Oldest  Newest  Rating
+1 steven kitchener · May 12, 2015
Hi Mohammed,

You certainly can use String comparisons in if statements but you need to make some changes to the code you posted above. Unlike when comparing ints where you can use the "==" comparison when comparing Strings you need to use a method called .equals(), as shown below.
String message = "New message";

if(message.equals("New message"){
System.out.println("The messages are equal");
}

If the above code is run then the line "The messages are equal" will be printed out.
Now to add it into your code. I will post comments next to the pieces i change (look out for the "//" in the following code)

Scanner kb= new Scanner(System.in);

System.out.println("Please. Enter The Password");
int password;
password=kb.nextInt();

System.out.println("Please. Enter The UserName");
String name; //We needed to define a String variable not an int variable
name=kb.next();

if(password==12345 && name.equals("car")){ //The first comparison is fine, but the second needed to //be changed to the ".equals" method
System.out.println("Welcome Mohammed To JAVA Program");
}else{
System.out.println("Error: You Are Not Allow to Acces This File");
}

Hope this helps,
Steven
  • 1

Java / Android Development

106,922 followers
About

Very popular language used to create desktop applications, website applets, and Android apps.

Links
Moderators
Bucky Roberts Administrator