0

I am new to programming and need help with a bit of code I wrote.

This is what I have so far:

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner Scan = new Scanner(System.in);
        System.out.println("The program is starting, please be patient...");
        System.out.println("Do you want to start the program? (y/n):");
        String input = Scan.nextLine();
        if (input == "y") {
            System.out.println("Hello World!");
        }
        else {
            System.out.println("Error");
            System.out.println(input + " not recognized!");
        }
    }
}

When I run this, there are no errors, but when I type "y" it runs the else section instead of saying "Hello World!". How can I make it so when I type in "y" it says "Hello World!"?

JohnDoe
  • 235
  • 2
  • 11

2 Answers2

2

Correct way to compare is

if(input.equals("y"))
apgp88
  • 955
  • 7
  • 14
1

Use String#equals instead of ==

if (input.equals("y")) {
            System.out.println("Hello World!");
        }

== compares reference where as String#equals() compares values in String Object

Neeraj Jain
  • 7,643
  • 6
  • 34
  • 62