Read user input from console using Scanner class : Scanner « File Input Output « Java






Read user input from console using Scanner class

 
 
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Username: ");
    String username = scanner.nextLine();

    System.out.print("Password: ");
    String password = scanner.nextLine();

    System.out.print("What is 2 + 2: ");
    int result = scanner.nextInt();

    if (username.equals("admin") && password.equals("secret") && result == 4) {
      System.out.println("Welcome");
    } else {
      System.out.println("Invalid username or password!");
    }
  }
}

   
  








Related examples in the same category

1.new Scanner(new BufferedReader(new FileReader("xanadu.txt")))
2.Split a string using Scanner class
3.Read file using Scanner class
4.Scanning text with java.util.Scanner
5.Simplify the code in TextReader by using java.util.Scanner
6.Read in the current contents of the java.net homepage
7.Perform the conversions after parsing the String