Basic Input Output
Basic Input Output
James Brucker
Display output
System.out.println("I'm a string" + " again");
System.out.print("apple");
System.out.print("banana\n");
System.out.print("grape");
a String
any Object
int a = 100;
System.out.print("a = "); // print a string
System.out.print(a); // print an int
System.out.print('\t'); // print a TAB char
System.out.print("Square Root of 2 = ");
System.out.print(Math.sqrt(2)); // print double
a String
a = 100
0.333333333333333
More on print and println
To print several values at once, if the first value is a
String, you can "join" the other values using +
a = 100
Printing an Object
If the argument is an object, Java will call the object's
toString() method and print the result.
ERROR:
double angle = Math.toRadians(45);
double x = Math.sin(angle);
System.out.println("sin(" , angle ,") = " , x);
%d %6.2f
Common printf Formats
Format Meaning Examples
%d decimal integers %d %6d
%f fixed pt. floating-point %f %10.4f
%e scientific notation %10e (1.2345e-02)
%g general floating point %10g
(use %e or %f, whichever is more compact)
%s String %s %10s %-10s
%c Character %c
int a = System.in.read( );
if (a < 0) /* end of input */;
else {
byte b = (byte)a;
handleInput( b );
}
Boring, isn't it?
Input Line-by-Line
To get a line of input as a String, you can create a
BufferedReader object that "wraps" System.in.
package myapp;
import java.util.Scanner;
...
2) or create as an attribute.
Typically a static attribute since System.in is static.
public class InputDemo {
// create a Scanner as static attribute
static Scanner console =
new Scanner( System.in );
// read Strings
String word = scan.next( ); // next word
String line = scan.nextLine( ); // next line
Input Errors
If you try to read an "int" but the next input is not an integer
then Scanner throws an InputMismatchException
Scanner scan = new Scanner( System.in );
// read a number
System.out.print("How many Baht? ");
int amount = scan.nextInt( );
convert next input
word to an "int"
How many Baht? I don't know
Exception in thread "main"
java.util.InputMismatchException
How to Test the Input
Scanner has methods to test the next input value:
Scanner scanner = new Scanner( System.in );
int amount;
// read a number
System.out.print("How many Baht? ");
if ( scanner.hasNextInt( ) ) true if the next
amount = scanner.nextInt( ); input value is an
else { "int"
System.out.println("Please input an int");
scanner.nextLine(); // discard old input
}