Tuesday, November 29

Standard Input , Output , Scanner class in Java to read strings

We use System.in to get input data from users to the program and it calls Standard input, as the same with this System.out which is Standard output to display or print information in console input. Scanner class from the package java.util allows us to achieve multiple input routines of string values only and the numerical values have the same but with a little difference we'll talk about it in other side.

This is an example for the standard input by using  a Scanner object. 

import java.util.*;   // import statement where Scanner object is

public class  You_j  {   // name of class

    public static void main (String [] args)  {  // main method

        String enterName;   // data type of String

        Scanner scan = new Scanner(System.in);  // use System.in to tell the scanner it's Input

        System.out.print("Type your name ");
        enterName = scan.next();
        System.out.print("Welcome " + enterName);  // Show output Welcome with the name

I will talk directly about  String in the forth line and this is to let the data that would be entered is string data type not numbers. The fifth line as you can see Scanner is the object to read input from the user and it begins with a capital letter, scan this is the name of our scanner and you can use whatever except reserved words in Java and illegal characters. Seventh line we assign name that entered to jump the next which is printing welcome with the name.

Note:  Actually there is another type to write the whole code above or change the order of the variables or assign value to Scanner. For more details see this another type.

import java.util.*;
public class You_j {
    public static void main(String []args) {
        String enterName;
        Scanner scan;
        scan = new Scanner(System.in);
        System.out.print("Type your name ");
        enterName = scan.next();
        System.out.print("Welcom " + enterName);

If you noticed that in first code we create ( scan ) object and assign the other side of the code in the same place ended by ( ; ) . The first code it is much better and these aspects of Java codes good to know.