Showing posts with label System.out.print. Show all posts
Showing posts with label System.out.print. Show all posts

Saturday, 25 May 2013

User I/O in Java

This example does console input/output in Java. It asks the user to type his / her name then says Hello.

At the start of the program, the java.io package is imported. This contains code to do system input / output. The asterisk which follows means that the program may want to use any of the classes in java.io.

The program creates an InputStreamReader class variable called isr to read what the user types. It also creates a BufferedReader class variable called br to store it temporarily.

The try block reads the user's input and the catch block handles exceptions: 

UBUNTU > cat prog31.java
import java.io.*;
public class prog31
{
public static void main(String[] args)
  {
  System.out.print("What is your name? ");
  InputStreamReader isr = new InputStreamReader(System.in);
  BufferedReader br = new BufferedReader(isr);
  try
    {
    String your_name = br.readLine();
    System.out.println("Hello " + your_name);
    }
  catch (IOException test)
    {
    System.out.println("I/O error");
    }
  }
}
UBUNTU > javac prog31.java
UBUNTU > java prog31
What is your name? Andrew
Hello Andrew
UBUNTU >

Thursday, 16 May 2013

Java System.out.println and System.out.print

What is the difference between these two?
 
System.out.println outputs a newline character afterwards:
 
UNIX > cat prog28.java
public class prog28
{
public static void main (String args[])
  {
  System.out.println("International DBA");
  }
}
UNIX > javac prog28.java
UNIX > java prog28
International DBA
UNIX >
 
… but System.out.print doesn’t:
 
UNIX > cat prog29.java
public class prog29
{
public static void main (String args[])
  {
  System.out.print("International DBA");
  }
}
UNIX > javac prog29.java
UNIX > java prog29
International DBAUNIX >
 
… although you can add one yourself if you wish:
 
UNIX > cat prog30.java
public class prog30
{
public static void main (String args[])
  {
  System.out.print("International DBA\n");
  }
}
UNIX > javac prog30.java
UNIX > java prog30
International DBA
UNIX >

If you have a Java book on Amazon, which you would like to advertise here for free, please write to me at international_dba@yahoo.co.uk.