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 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.

Below example will prompt user to input id card number, if the user input is not a number, it will display an error message to user in console and prompt again until user input correct number value.

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;

        }

   }

}

Below is the output. The black line is the System.out output, the green line is user input and the red line is System.err output.

READ :   How To Use Java Code To Set File Permission

java system in out error example

(Visited 57 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

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