Java User Input with Scanner: Reading int, String, double, boolean & char

package Pack1;
import java.util.Scanner;

public class my_inputs {
    public static void main(String[] args) {
        Scanner my_input = new Scanner(System.in);  // Scanner object created
        System.out.println("Enter input: ");
        int my_int = my_input.nextInt();            // Collecting integer input
        System.out.println("You entered: " + my_int);
        my_input.close();
    }
}

Console Interaction:

Enter input: 
42
You entered: 42

1. Complete Reference: java.util.Scanner Input Methods 🔝

Data Type Scanner Method Example Valid User Input
int my_input.nextInt() 42, -150
String (1 word) my_input.next() Rama (stops at space)
String (full line) my_input.nextLine() Rama Rao (reads until Enter)
boolean my_input.nextBoolean() true or false (case-insensitive)
double / float nextDouble() / nextFloat() 99.95, 3.5
char my_input.next().charAt(0) A (extracts index 0 of token)
long / short / byte nextLong() / nextShort() / nextByte() 9000000000, 3200, 120

2. Reading Two Integers & Computing Their Mathematical Sum 🔝

If you enter 30 and 40 and write System.out.println("Sum: " + my_int1 + my_int2);, Java concatenates them as strings and prints 3040! Store int sum = my_int1 + my_int2; (or use parentheses (my_int1 + my_int2)) so Java performs mathematical addition:

package Pack1;
import java.util.Scanner;

public class my_inputs {
    public static void main(String[] args) {
        Scanner my_input = new Scanner(System.in);
        System.out.println("Enter first input: ");
        int my_int1 = my_input.nextInt();

        System.out.println("Enter second input: ");
        int my_int2 = my_input.nextInt();

         // Caution: "Sum: " + my_int1 + my_int2 concatenates as strings ("3040")!
         // Compute mathematical sum first (or wrap in parentheses):
        int sum = my_int1 + my_int2;
        System.out.println("Sum of two inputs: " + sum);
        my_input.close();
    }
}

Console Interaction:

Enter first input: 
30
Enter second input: 
40
Sum of two inputs: 70

3. Collecting String Inputs & Closing the Scanner 🔝

Use my_input.next() to read single-word tokens (such as First Name and Last Name), and call my_input.close(); when finished reading all inputs:

package Pack1;
import java.util.Scanner;

public class my_inputs {
    public static void main(String[] args) {
        Scanner my_input = new Scanner(System.in);
        System.out.println("Enter First Name: ");
        String my_str1 = my_input.next();  // Reads a single word (up to whitespace)

        System.out.println("Enter Last Name: ");
        String my_str2 = my_input.next();

        System.out.println("Welcome " + my_str1 + " " + my_str2);
        my_input.close();
    }
}

Console Interaction:

Enter First Name: 
Rama
Enter Last Name: 
Rao
Welcome Rama Rao

4. Reading boolean, double, float, char, long, short & byte 🔝

Because Scanner does not have a dedicated nextChar() method, read a single character using my_input.next().charAt(0) (see String.charAt()). Here are all seven remaining primitive types in action:

package Pack1;
import java.util.Scanner;

public class my_inputs {
    public static void main(String[] args) {
         // Demonstrating all primitive Scanner methods using an in-memory input stream:
        Scanner my_input = new Scanner("true 99.95 3.5f A 9000000000 3200 120");

        boolean my_boolean = my_input.nextBoolean();
        double  my_double  = my_input.nextDouble();
        float   my_float   = my_input.nextFloat();
        char    my_char    = my_input.next().charAt(0);  // First character of token!
        long    my_long    = my_input.nextLong();
        short   my_short   = my_input.nextShort();
        byte    my_byte    = my_input.nextByte();
        my_input.close();

        System.out.println("boolean=" + my_boolean + ", double=" + my_double + ", float=" + my_float);
        System.out.println("char=" + my_char + ", long=" + my_long + ", short=" + my_short + ", byte=" + my_byte);
    }
}

Terminal Output:

boolean=true, double=99.95, float=3.5
char=A, long=9000000000, short=3200, byte=120

5. Solving the #1 Scanner Bug: Why nextLine() Skips Input After nextInt() 🔝

When a user types 25 and presses Enter, nextInt() reads 25 but leaves the trailing newline character (\n) in the buffer. If you immediately call nextLine(), it consumes that empty \n and returns an empty string ""! Add an extra sc.nextLine(); right after nextInt() to clear the newline:

import java.util.Scanner;

public class NextLineAfterNextIntFix {
    public static void main(String[] args) {
        Scanner sc = new Scanner("25\nHyderabad India\n");
        int age = sc.nextInt();
        sc.nextLine();  // CRITICAL: Consumes the leftover newline after 25!
        String city = sc.nextLine();  // Now reads the full line "Hyderabad India"
        System.out.println("Age: " + age + " | City: " + city);
        sc.close();
    }
}

Terminal Output:

Age: 25 | City: Hyderabad India

6. Production Recipe: Preventing InputMismatchException with hasNextInt() 🔝

If a user types letters like "abc" when nextInt() is waiting for a number, Java throws an InputMismatchException. Guard numeric reads with a while (!sc.hasNextInt()) loop:

import java.util.Scanner;

public class SafeIntValidation {
    public static void main(String[] args) {
        Scanner sc = new Scanner("abc 85");
        while (!sc.hasNextInt()) {
            System.out.println("Invalid integer skipped: " + sc.next());
        }
        int validScore = sc.nextInt();
        System.out.println("Accepted valid integer: " + validScore);
        sc.close();
    }
}

Terminal Output:

Invalid integer skipped: abc
Accepted valid integer: 85
Method Delimiter / Stop Rule Consumes Newline ( )?
next() / nextInt() Whitespace (space, tab, newline) No (leaves trailing in buffer)
nextLine() Line break ( or ) Yes (consumes and strips )

7. Common Developer Pitfalls & Traps 🔝

Closing a System.in Scanner Too Early

Calling my_input.close() closes the underlying System.in keyboard stream for the entire JVM process! Once closed, even creating a brand-new new Scanner(System.in) later in your program will fail to read any input. Only call close() at the very end of main().

Locale Decimal Separator Mismatch in nextDouble()

On European OS locales where commas are used as decimal separators (99,95), typing 99.95 with a dot throws InputMismatchException unless you configure my_input.useLocale(Locale.US);.

8. Complete Compilable Java Program 🔝

import java.util.Scanner;

public class MyInputsFullDemo {
    public static void main(String[] args) {
        Scanner sc = new Scanner("30 40 GradeA");
        int a = sc.nextInt(), b = sc.nextInt();
        char ch = sc.next().charAt(5);
        sc.close();
        if ((a + b) == 70 && ch == 'A') {
            System.out.println("All Java Scanner user input checks passed! sum=70, grade=" + ch);
        }
    }
}

Terminal Output:

All Java Scanner user input checks passed! sum=70, grade=A

9. Frequently Asked Questions (FAQ) 🔝

What is the difference between my_input.next() and my_input.nextLine()?

next() reads only a single whitespace-delimited token (stopping at the first space or tab), whereas nextLine() reads the entire line of text including spaces up to the Enter key.

Why do I need import java.util.Scanner; at the top of the file?

Unlike System and String (which live in java.lang), Scanner lives in the java.util package and must be imported explicitly.

Can Scanner read from a String or a File instead of System.in?

Yes! You can pass a String (new Scanner("10 20")) or a java.io.File object (new Scanner(new File("data.txt"))) to the Scanner constructor.

How do I change the delimiter of a Scanner (e.g., to split by comma)?

Call my_input.useDelimiter(","); (or my_input.useDelimiter(",\s*");) to tokenize comma-separated values.

When should I use BufferedReader instead of Scanner?

Use BufferedReader when reading millions of lines in competitive programming or high-throughput logs where raw I/O speed matters more than built-in token parsing.

Further Reading & Related Tutorials 🔝


Java



plus2net.com






✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer