0% found this document useful (0 votes)
12 views6 pages

Java Scanner Class Overview and Examples

The Scanner class in Java is used for taking user input, such as numbers and text, from the keyboard. It is created using 'Scanner sc = new Scanner(System.in);' and includes common methods like nextLong() for inputting long numbers. The document provides several example programs demonstrating the use of the Scanner class for various tasks, including adding numbers, calculating the area of a rectangle, checking if a number is even or odd, and printing user details.

Uploaded by

aryantiwary28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views6 pages

Java Scanner Class Overview and Examples

The Scanner class in Java is used for taking user input, such as numbers and text, from the keyboard. It is created using 'Scanner sc = new Scanner(System.in);' and includes common methods like nextLong() for inputting long numbers. The document provides several example programs demonstrating the use of the Scanner class for various tasks, including adding numbers, calculating the area of a rectangle, checking if a number is even or odd, and printing user details.

Uploaded by

aryantiwary28
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SCANNER CLASS

What is a Scanner?

The Scanner class is used in Java to take input from


the user (like numbers, text, etc.) through the
keyboard.

It belongs to the package:

import [Link];

OR

import [Link].*;

How to Create a Scanner Object?

Scanner sc = new Scanner([Link]);

Common Scanner Methods:

Topic: Scanner Class Prepared By: Ms. Ashwini Y.


nextLong() To input the long number

Simple Example:
import [Link];

public class UserInput


{
public static void main(String args[])
{
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
Topic: Scanner Class Prepared By: Ms. Ashwini Y.
[Link]("Hello, " + name + "!");
}
}
—---------------------------------------------------------------

1)​Program to Add Two Numbers


import [Link];

public class AddNumbers {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int a = [Link]();
[Link]("Enter second number: ");
int b = [Link]();
int sum = a + b;
[Link]("Sum = " + sum);
}
}

2)​Program to Find Area of a Rectangle


import [Link];

public class RectangleArea {


public static void main(String args[]) {

Topic: Scanner Class Prepared By: Ms. Ashwini Y.


Scanner sc = new Scanner([Link]);
[Link]("Enter length: ");
double length = [Link]();
[Link]("Enter breadth: ");
double breadth = [Link]();
double area = length * breadth;
[Link]("Area = " + area);
}
}

3)​Program to Check if Number is Even or Odd


import [Link];

public class EvenOdd {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter a number: ");
int num = [Link]();
if (num % 2 == 0)
[Link]("Even Number");
else
[Link]("Odd Number");
}
}

Topic: Scanner Class Prepared By: Ms. Ashwini Y.


4)​Program to Print User's Name and Age
import [Link];

public class UserDetails {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter your name: ");
String name = [Link]();
[Link]("Enter your age: ");
int age = [Link]();
[Link]("Hello " + name + ", you
are " + age + " years old.");
}
}

5)​Program to Find the Greater of Two Numbers


import [Link];

public class GreaterNumber {


public static void main(String args[]) {
Scanner sc = new Scanner([Link]);
[Link]("Enter first number: ");
int x = [Link]();
[Link]("Enter second number: ");
int y = [Link]();

Topic: Scanner Class Prepared By: Ms. Ashwini Y.


if (x > y)
[Link](x + " is greater.");
else if (x < y)
[Link](y + " is greater.");
else
[Link]("Both are equal.");
}
}

**************************************************************

Topic: Scanner Class Prepared By: Ms. Ashwini Y.

Common questions

Powered by AI

The Scanner class is particularly beneficial in scenarios requiring simple input from the user through standard input like keyboards, such as getting user details or performing arithmetic operations . However, it has limitations, including potential performance issues with large inputs and constraints on types of input beyond simple data extraction tasks . Moreover, it may not be suitable for high-frequency input/output operations or handling non-standard input sources without additional customization.

The Scanner class in Java allows for user input by creating a Scanner object that reads from inputs such as the keyboard. For example, in the program to add two numbers, Scanner is used to read integer inputs from the user for two numbers, which are then added to display the sum . Similarly, it can also handle inputs when checking whether a number is even or odd .

The Scanner class offers ease of use for user input operations in Java due to its simple methods like `nextInt()` or `nextLine()` for reading inputs directly and efficiently from standard input sources . However, a potential drawback is its inefficiency with larger input data due to its synchronous input capture, which might not be the best fit for performance-intensive applications. Additionally, handling exceptions or bad inputs may require extra handling, adding to code complexity under specific conditions.

For more advanced input processing, the Scanner class can be complemented with classes like BufferedReader for more efficient handling of large-scale text data inputs. While Scanner is great for parsing primitive types and strings, BufferedReader can efficiently read character streams with larger data sets due to its buffering capabilities. Combining Scanner for initial data parsing and BufferedReader for detailed text processing can provide versatility and efficiency suited to both small and large input tasks in Java .

The Scanner class can handle different types of input by using methods like `nextInt()` for integers, `nextDouble()` for doubles, and `nextLine()` for strings, allowing it to be versatile in processing various data types. For instance, in the rectangle area calculation program, `nextDouble()` is used to read floating-point numbers for length and breadth to then calculate the area with `double area = length * breadth;` . This flexibility shows its capability in processing different kinds of user inputs.

The process involves reading an integer input from the user using the Scanner class and checking if the number is divisible by 2. If the remainder of dividing the number by 2 is 0, the number is even; otherwise, it is odd. The program demonstrates this with: `int num = sc.nextInt(); if (num % 2 == 0) System.out.println("Even Number"); else System.out.println("Odd Number");` .

The java.util.Scanner import is necessary for enabling the use of the Scanner class in Java programs, facilitating user input functionality. This can be done specifically by importing `java.util.Scanner` or more generally by importing all classes in the util package with `import java.util.*;`. Both imports allow access to the Scanner class, but the latter might introduce unnecessary overhead if only the Scanner class is needed .

The principles of the Scanner class, such as ease of parsing various input types and integrating seamlessly into basic I/O operations, can be applied to improve user interaction in languages like Python or C++. In Python, similarly using `input()` for standard I/O operations can be enhanced with additional parsing modules such as argparse for command-line input handling, or integrating libraries like PIpES for more complex input routing. C++ could benefit from implementing streamlined user input classes that abstract typical I/O operations and combine efficiency with flexibility, akin to Scanner in Java .

To improve a program's robustness while obtaining user input via Scanner, implement error handling using try-catch blocks to capture InputMismatchExceptions. Pre-validating inputs by checking hasNext methods (e.g., `hasNextInt()`) before actually reading values can prevent exceptions. Additionally, using `sc.nextLine()` after numeric inputs helps clear input buffers, reducing misreads in successive operations. Encouraging user feedback loops and clear prompts can also enhance usability and prevent common input errors .

To enhance a Java program using the Scanner class for string input handling, one can use `nextLine()` to capture full lines of input for strings, ensuring spaces and multi-word strings are not split incorrectly. For example, in reading the user's name, `String name = sc.nextLine();` ensures that the entire line entered is treated as a single string regardless of spaces. Additionally, calls to `next` can be used if separate tokens within a line are meant to be split and handled individually .

You might also like