DEV Community

Neelakandan R
Neelakandan R

Posted on

2 1 1 1 1

Java User Input (Scanner)

Java User Input

The Scanner class is used to get user input, and it is found in the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods found in the Scanner class documentation. In our example, we will use the nextLine() method, which is used to read Strings:

package afterfeb13;

import java.util.Scanner;

public class scanner {
    public static void main(String[] args) {

        int total = 0;
        int count = 0;

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter name");
        String name = sc.nextLine();
        System.out.println("Welcome to java: " + name);

        int[] mark = new int[5];
        for (int i = 0; i < mark.length; i++) {
            mark[i] = sc.nextInt();
            System.out.println("Enter 10th marks = " + mark[i]);
            total = total + mark[i];

        }
        System.out.println("Total of 10th = " + total);

        int[] marks = new int[6];

        for (int j = 0; j < marks.length; j++) {
            marks[j] = sc.nextInt();
            System.out.println("Enter 12th marks = " + marks[j]);
            count = count + marks[j];

        }
        System.out.println("Total of 12th = " + count);
    }

}

Enter fullscreen mode Exit fullscreen mode


Output:

Enter name
neelakandan
Welcome to java: neelakandan
98
Enter 10th marks = 98
87
Enter 10th marks = 87
76
Enter 10th marks = 76
56
Enter 10th marks = 56
87
Enter 10th marks = 87
Total of 10th = 404
97
Enter 12th marks = 97
89
Enter 12th marks = 89
97
Enter 12th marks = 97
89
Enter 12th marks = 89
98
Enter 12th marks = 98
67
Enter 12th marks = 67
Total of 12th = 537

Input Types

In the example above, we used the nextLine() method, which is used to read Strings. To read other types, look at the table below:

**nextBoolean()-Used for reading Boolean value

nextByte()-Used for reading Byte value

nextDouble()-Used for reading Double value

nextFloat()-Used for reading Float value

nextInt()-Used for reading Int value

nextLine()-Used for reading Line value

nextLong()-Used for reading Long value

nextShort()-Used for reading Short value**

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay