Scanning and Formatting

Scanning and Formatting

In Java, the Scanner class is used to read input from different sources like files, user input, etc. It is a powerful class for scanning data from different input streams.

Here is an example of using the Scanner class to read user input from the console:

import java.util.Scanner;

public class ScannerExample {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        System.out.print(“Enter your name: “);

        String name = scanner.nextLine();

        System.out.print(“Enter your age: “);

        int age = scanner.nextInt();

        System.out.println(“Your name is ” + name + ” and you are ” + age + ” years old.”);

    }

}

In the above example, we create a Scanner object and pass System.in as a parameter, which is the standard input stream (console). We then use the nextLine() and nextInt() methods to read the user’s input and store it in the name and age variables, respectively. Finally, we print out the values of name and age using the println() method.

Java also provides the Formatter class, which is used to format and output different types of data. Here is an example of using the Formatter class to format a date:

import java.util.Date;

import java.util.Formatter;

public class FormatterExample {

    public static void main(String[] args) {

        Formatter formatter = new Formatter();

        Date date = new Date();

        formatter.format(“Today is %tA, %<tB %<td, %<tY.”, date);

        System.out.println(formatter);

    }

}

In the above example, we create a Formatter object and a Date object. We then use the format() method to format the date and store it in the formatter object. Finally, we print out the value of the formatter object using the println() method. The %tA, %<tB, %<td, and %<tY are format specifiers that are used to format the date. The %tA specifier outputs the full name of the day of the week, %<tB outputs the full name of the month, %<td outputs the day of the month, and %<tY outputs the year. The < character is used to indicate that the argument for the format specifier should be reused from the previous argument (in this case, the date object).

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Share this post
[social_warfare]
Streams and Bytes Data
Command Line I/O

Get industry recognized certification – Contact us

keyboard_arrow_up