Reputation: 39
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner name = new Scanner(System.in); ## I am asking for input form user but it does not take imput
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
}else System.out.println("Well good meet");
}
}
Why does the program run the else and not ask for my input?
Upvotes: 0
Views: 62
Reputation: 605
You merely created a Scanner but did not tell it to read something from the standard input. You can do that by calling scanner.next()
to read a token scanner.nextLine()
to read a line, etc. As well you are comparing a Scanner
to a String
in the if-statement.
import java.util.Scanner;
class Tutorial {
public static void main (String args[]){
System.out.println("Who goes there?");
Scanner s = new Scanner(System.in);
String name = s.next(); // get the token
if (name.equals("me") || name.equals("Me") ){
System.out.println("Well, good for you smartass.");
} else System.out.println("Well good meet");
}
}
Upvotes: 2
Reputation: 1615
You've only created an instance of the Scanner object. You need to invoke a method such as Scanner#nextLine()
to read input and then compare the read value to "me" or "Me".
Example:
Scanner name = new Scanner(System.in);
String input = name.nextLine();
if (...) // Compare input to something here.
You might want to use String#equalsIgnoreCase
for case-insensitive matching too.
Upvotes: 1
Reputation: 11244
You should read your input by using scanner.nextLine()
:
Scanner scanner = new Scanner(System.in);
String name = scanner.nextLine();
if (name.equals("me") || name.equals("Me"))
{
System.out.println("Well, good for you smartass.");
} else {
System.out.println("Well good meet");
}
scanner.close();
Upvotes: 4