1
Input/Output
2
Input/Output• In Java input and output take place through I/O
streams– An I/O stream represents an input source or output
destination– Streams support various data types– A program uses an input stream to read data from
some input device– A program uses an output stream to send data to
some output device
3
Command line I/O• System.in is a raw byte stream– Also known as the standard input stream– Not too useful
• System.out is an output stream– We have already used it for printing
4
Example: Reading an integerclass InputOutput { public static void main (String a[]) { Integer n = new Integer(a[0]); System.out.println(n); }}
• Similar methods for other data types– parseFloat, parseDouble, parseLong, parseShort
5
Using System.inclass Count { public static void main(String args[]) throws
java.io.IOException { int count = 0; while (System.in.read() != -1) { count++; } System.out.println(“Input has ” + count + “
chars.”); }} // Use control-D to terminate the input stream
6
Reading a lineclass LineInput { public static void main(String args[]) throws
java.io.IOException { char line[] = new char[100]; int count = 0, i; while ((line[count++]=(char)System.in.read()) != ‘\n’); System.out.println(“Input line was: ”); for (i=0; i<count; i++) { System.out.print(line[i]); } }}
Processing Primitive Data Types as Objects
Java provides a convenient way to incorporate or wrap a primitive data type into an object, e.g., wrapping int into Integer. The corresponding class is called a wrapper class.
By using a wrapper object instead of primitive data type, generic programming can be used.
Number classEach numeric wrapper class extends Number
class containg methods doubleValue(), floatValue(), intValue(), longValue(), shortValue() and byteValue().
A wrapper object can be constructed using either primitive data type value or string representing numeric value, e.g.
new Integer(5), new Integer(“5”), new Double(5.0), new Double(“5.0”).
MAX_VALUE & MIN_VALUE
Each numeric wrapper has constants MAX_VALUE & MIN_VALUE representing maximum and minimum values.
System.print.ln(“Maximum Integer”+ Integer.MAX_VALUE);
The numeric wrapper classes have static method valueOf(String s)Double doubleObject=Double.valueOf(“12.4”);
Parsing methodspublic static byte parseByte(String s)public static byte parseByte(String s, int radix)public static short parseShort(String s)public static short parseShort(String s, int radix)public static int parseInt(String s)public static int parseInt(String s, int radix)public static double parseDouble(String s)public static double parseDouble(String s, int radix)Integer.parseInt(“11”,2) returns 3;Integer.parseInt(“11”,8) returns 9;Integer.parseInt(“12”,2) is invalid.
Sorting an Array of Objectspublic class GenericSort{
public static void main(String[] args){Integer [] intArray={new Integer(2), new Integer(3), new
Integer(1)};Double [] doubleArray= new Double(2.3), new Double (1.2), new
Double(4.3)};String [] stringArray={“We”, “You”, “Them”};
sort(intArray);sort(doubleArray);
sort(stringArray);System.out.println(“Sorted objects:”)printList(intArray);printList(doubleArray);printList(stringArray);
}
public static void sort(Comparable[] list){ Comparable currentMax; int currentMaxIndex; for(int i=list.length-1;i>=1;i--){ currentMax=list[i];
currentMaxIndex=i;for( int j=i-1;j>=0;j--){ if (currentMax.compareTo(list[j]<0){currentMax=list[j];currentMaxIndex=j;}}if (currentMaxIndex!=i){list[currentMaxIndex]=list[i];list[i]=currentMax;}}
}
a
13
Examples of class: Using System.in.read ()
14
Building a wrapperpublic class MyInput { // Read a character public char ReadChar () throws java.io.IOException { return (char)System.in.read (); } // Read multiple characters public String ReadString (int howmany) throws
java.io.IOException { String str = “”; int k; for (k=0; k<howmany; k++) { str += (char)System.in.read (); } return str; }
15
Building a wrapper // Read a line public String ReadLine () throws
java.io.IOException { String str = “”; char c; while ((c=(char)System.in.read ()) != ‘\n’) { str += c; } return str; }
16
Building a wrapper // Read an integer public int ReadInt () throws java.io.IOException { String str = “”; char c; while (true) { c = (char)System.in.read (); if ((c == ‘\n’) || (c == ‘ ‘)) { break; } str += c; } Integer n = new Integer (str.trim()); return n.intValue(); }
17
Building a wrapper // Read a double public double ReadDouble () throws java.io.IOException { String str = “”; char c; while (true) { c = (char)System.in.read (); if ((c == ‘\n’) || (c == ‘ ‘)) { break; } str += c; } Double n = new Double (str.trim()); return n.doubleValue(); }
18
Building a wrapper // Read a float public float ReadFloat () java.io.IOException { String str = “”; char c; while (true) { c = (char)System.in.read (); if ((c == ‘\n’) || (c == ‘ ‘)) { break; } str += c; } Float n = new Float (str.trim()); return n.floatValue(); }} // end class
Using the wrapper• Let us build an interactive calculator– Asks for two numbers (integers, floats, or doubles)– Asks for the operation type: +, -, /, *– Computes the answer, prints it, and prompts for the
next input– User should be asked before closing the calculator
Using the wrapperclass DeskCalculator { public static void main (String a[]) throws
java.io.IOException { char inputOp, exitChar, sundries; MyInput inp = new MyInput(); double operand1, operand2; while (true) { System.out.println (“Enter two numbers:”); operand1 = inp.ReadDouble (); operand2 = inp.ReadDouble (); System.out.print (“What do you want to do? (+, -,
*, /)”); inputOp = inp.ReadChar (); // next slide
Using the wrapper // Eat up the \n at the end sundries = inp.ReadChar (); switch (inputOp) { case ‘+’ : System.out.println (operand1+operand2); break;
case ‘-’ : System.out.println (operand1-operand2); break; // next slide
Using the wrapper case ‘*’ : System.out.println(operand1*operand2); break;
case ‘/’ : System.out.println(operand1/operand2); break; default : System.out.println (“Invalid operation!”); break; } // end switch
Using the wrapper System.out.print (“Want to exit? (y/n)”); exitChar = inp.ReadChar (); // Eat up the ‘\n’ sundries = inp.ReadChar (); if (exitChar == ‘y’) { System.out.println (“Bye for now!”); break; } } // end while } // end main} // end class