Scanner

In Java, you can use the Scanner class to read user inputs of various data types. Here are examples of reading different data types using Scanner:

  1. Reading Integers: To read integers from the user, you can use the nextInt() method of the Scanner class.

    import java.util.Scanner;
    
    public class ReadIntegers {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter an integer: ");
            int num = scanner.nextInt();
            System.out.println("You entered: " + num);
            scanner.close();
        }
    }
  2. Reading Floating-Point Numbers: To read floating-point numbers (e.g., doubles or floats), you can use the nextDouble() method.

    import java.util.Scanner;
    
    public class ReadFloatingPoint {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a floating-point number: ");
            double num = scanner.nextDouble();
            System.out.println("You entered: " + num);
            scanner.close();
        }
    }
  3. Reading Strings: To read strings, you can use the next() or nextLine() methods.

    import java.util.Scanner;
    
    public class ReadString {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a string: ");
            String input = scanner.nextLine();
            System.out.println("You entered: " + input);
            scanner.close();
        }
    }
  4. Reading Booleans: To read boolean values (true or false), you can use the nextBoolean() method.

    import java.util.Scanner;
    
    public class ReadBoolean {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a boolean value (true/false): ");
            boolean value = scanner.nextBoolean();
            System.out.println("You entered: " + value);
            scanner.close();
        }
    }
  5. Reading Characters: To read individual characters, you can use the next() method and retrieve the first character of the input string.

    import java.util.Scanner;
    
    public class ReadChar {
        public static void main(String[] args) {
            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter a character: ");
            String input = scanner.next();
            char ch = input.charAt(0);
            System.out.println("You entered: " + ch);
            scanner.close();
        }
    }

These are some common ways to read user inputs of different data types using the Scanner class in Java. Remember to handle exceptions, such as InputMismatchException or NoSuchElementException, when the user input doesn't match the expected data type.

Last updated