I'm writing a program in the Java language, and I'm using if else statement. In this program i need to input word(s), ie, alphabet character that has been assigned to be the values of the String data type. So that the program will print the sequential if statement, but is seems that program is not recognizing the input, because it keep printing only else statement. I need to know how to assign String values in Java language, import java.util.Scanner;
on an if else Statement algorithm.
import java.util.Scanner;
public class Compare
{
public static void main (String []args)
{
Scanner input = new Scanner(System.in);
String name = “Henry”;
System.out.println(“Enter a NAME”);
name = input.nextLine();
If ( name = “Henry”)
System.out.println(“Welcome Henry”);
else
System.out.println(“Invalid Input”);
}
}
When i run it in CMD:
C:\CODE>java Compare
Enter a NAME:
Henry
Invalid Input
It doesn't accept the String value “Henry” thats why the else statement keeps displaying “Invalid Input”.
Based on the code in your comment:
import java.util.Scanner; public Compare { public static void main (String []args) { Scanner input = new Scanner(System.in); String name = “Henry”; System.out.println(“Enter a NAME”); name = input.nextLine(); If ( name = “Henry”) System.out.println(“Welcome Henry”); else System.out.println(“Invalid Input”); } }
These are the errors:
public Compare
: You're missing a class
here “
quotes should be "
instead If
should be with a lowercase if
if(name = "Henry")
should be if(name.equals("Henry"))
(Because comparing Strings is done with .equals
. Note that even a normal compare would have been ==
instead of =
as well..) All combined:
import java.util.Scanner;
public class Compare{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Enter a NAME");
String name = input.nextLine();
if(name.equals("Henry"))
System.out.println("Welcome Henry");
else
System.out.println("Invalid Input");
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.