-1

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), i.e., 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”.

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
Chibaba
  • 33
  • 1
  • 4
  • 2
    DId you use `==` to compare `String`s in your `if` statement, something like `if (s == "SomeValue")...`? If so, change it to `if (s.equals("SomeValue"))`, – Kevin Anderson Aug 29 '18 at 11:06
  • 1
    Possible duplicate of [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – Ole V.V. Aug 29 '18 at 11:21

1 Answers1

3

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:

  1. public Compare: You're missing a class here
  2. quotes should be " instead
  3. If should be with a lowercase if
  4. 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");
  }
}
Kevin Cruijssen
  • 9,153
  • 9
  • 61
  • 135