Java System In Out Error Example

This example will tell you how to use java standard input, output, and error object to read string data from user command line input, write string data to standard output console and display error messages to standard error output. All the standard input or output object is the static variable of java.lang.System class.

1. Java System Input Output Variables Overview.

  1. System.in: Used to read string data from standard input such as command line console.
  2. java.util.Scanner: A util class that used to wrap java.lang.System.in to read data. It provides a lot of convenient methods.
  3. System.out: Used to write string data to standard output.
  4. System.err: Write error messages to standard error.

2. Java Input Output Example.

  1. The below example will prompt the user to input id card number.
  2. If the user input is not a number, it will display an error message to the user in the console and prompt again until the user inputs the correct number value.
  3. Below is the example java source code.
    package com.dev2qa.java.basic;
    
    import java.util.Scanner;
    
    public class SystemIO {
    
    public static void main(String[] args) {
    
        // Scanner is a class which wrap System.in to read user input from console.
    
        Scanner scanner = new Scanner(System.in);
    
        // Use System.out to print debug info.
    
        System.out.println("Please input your id card number.");
    
        // Read user input.
    
        String line = scanner.nextLine();
    
        // If user input is not an integer number.
    
        while(!isInteger(line))
    
        {
    
           // Use System.err to print error info.
    
           System.err.println("Your input is not an integer, input again.");
    
           // Read user input again.
    
           line = scanner.nextLine();
    
         }
    
         System.out.println("Your input is an integer number. ");
    
       }
    
     
       /* Check whether user input is an integer or not. */
    
       private static boolean isInteger(String value)
    
       {
    
           booleanret = true;
    
           try
    
           {
    
               Long.parseLong(value);
    
           }catch(NumberFormatException ex)
    
           {
    
               ret = false;
    
           }finally
    
           {
    
               return ret;
    
            }
    
       }
    
    }
  4. Below is the above example execution output.
    Please input your id card number.
    
    jerry
    Your input is not an integer, input again.
    
    123456789
    Your input is an integer number.
0 0 votes
Article Rating
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x