-2

I am making a program where the program says "Hey!" and if the user says "hi" reply with: "What's up?" back. the problem is that the program terminated before I could even type my input. I am really confused. I tried other stack posts but that did not work. Please help! Relevant code:

import java.util.*;  
class Main {
    public static void main(String[] args) {
        System.out.println("Hey!");
        Scanner sc = new Scanner(System.in);
        if (sc.equals("hi")) {
              System.out.println("Whats up?");
        }
        sc.close();
    }
}

If there is any way to shorten the code or make it more efficient please include that too.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
SamiOsman
  • 9
  • 1
  • 2
  • 4
    Does this answer your question? [How to get the user input in Java?](https://stackoverflow.com/questions/5287538/how-to-get-the-user-input-in-java) – Vlad L Jun 06 '21 at 19:09
  • 2
    You compare sc (the Scanner reference) with a String. That will never be true. Use sc.next() in your if statement, meaning your condition should be if (sc.next().equals("hi")) – rm_ Jun 06 '21 at 19:11
  • @user15793316 Ok. Just started working on that! Thanks a lot! – SamiOsman Jun 06 '21 at 21:41

1 Answers1

1

The scanner class isn't the user input, you can use it to get user input for example,

String input = scanner.next();

Your code should be

import java.util.*;  
class Main {
    public static void main(String[] args) {
        System.out.println("Hey!");
        Scanner sc = new Scanner(System.in);
        String input = sc.next(); 
        if (input.equals("hi")) {
            System.out.println("Whats up?");
        }
        sc.close();
    }
}
AmrDeveloper
  • 3,826
  • 1
  • 21
  • 30