1 Input/Output. 2 In Java input and output take place through I/O streams – An I/O stream represents an input source or output destination – Streams support.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

STRING AN EXAMPLE OF REFERENCE DATA TYPE. 2 Primitive Data Types  The eight Java primitive data types are:  byte  short  int  long  float  double.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
1 LECTURE#7: Console Input Overview l Introduction to Wrapper classes. l Introduction to Exceptions (Java run-time errors). l Console input using the BufferedReader.
Mathematical Operators  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming in.
1 1 Abstract Classes and Interfaces. 22 Motivations You learned how to write simple programs to display GUI components. Can you write the code to respond.
Some basic I/O.
Programming in Java; Instructor:Alok Mehta Objects, Classes, Program Constructs1 Programming in Java Objects, Classes, Program Constructs.
1 Introduction to Console Input  Primitive Type Wrapper Classes  Converting Strings to Numbers  System.in Stream  Wrapping System.in in a Buffered.
Inheritance and interfaces A class C1 is derived from class C2, then C1 is called subclass, and C2 is called superclass Superclass-parent, base class Subclass.
Chapter 3b Standard Input and Output Sample Development.
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: IO *Standard Output *Formatting Decimal.
CPS 2231 Computer Organization and Programming Instructor: Tian (Tina) Tian.
Chapter 11 Abstract Classes and Interfaces 1. Abstract method New modifier for class and method: abstract An abstract method has no body Compare: abstract.
1 Course Lectures Available on line:
1 Graphs and Search Trees Instructor: Mainak Chaudhuri
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
1 Java Console I/O Introduction. 2 Java I/O You may have noticed that all the I/O that we have done has been output The reasons –Java I/O is based on.
1 Chapter 10 Object-Oriented Thinking. 2 Class Abstraction and Encapsulation Class abstraction means to separate class implementation details from the.
Console Input. So far… All the inputs for our programs have been hard-coded in the main method or inputted using the dialog boxes of BlueJ It’s time to.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Java Fundamentals 3 Input and Output statements. Standard Output Window Using System.out, we can output multiple lines of text to the standard output.
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
I/O in Java Dennis Burford
Java Fundamentals 5. Java Programming: From Problem Analysis to Program Design, Second Edition2 Parsing Numeric Strings  Integer, Float, and Double are.
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
Miscellaneous topics Chapter 2 Savitch. Miscellaneous topics Standard output using System.out Input using Scanner class.
Introduction to Programming G50PRO University of Nottingham Unit 11 : Files Input/Ouput Paul Tennent
CS100A, Fall 1997, Lecture 91 CS100A, Fall 1997 Lecture 9, Tuesday, 30 September Input/Output & Program Schema System.in, class Text, Some basic data processing,
 Definition: Accessing child class methods through a parent object  Example: Child class overrides default parent class methods  Example: Child class.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
CS 11 java track: lecture 2 This week: more on object-oriented programming (OOP) objects vs. primitive types creating new objects with new calling methods.
FUNDAMENTALS 2 CHAPTER 2. OPERATORS  Operators are special symbols used for:  mathematical functions  assignment statements  logical comparisons 
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
CONTENTS Wrapper Class Enumeration Garbage Collection Import static.
Chapter 2 Input, Variables and Data Types. JAVA Input JAVA input is not straightforward and is different depending on the JAVA environment that you are.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
I/O Basics 26 January Aside from print( ) and println( ), none of the I/O methods have been used significantly. The reason is simple: most real.
Converting string to integer class StringToInt { public static void main (String arg[]) { // Assume arg[0] is the input string int result = 0, pos; int.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
Wrapper Classes  Java offers a convenient way to incorporate, or wrap, a primitive data type into an object, for example, wrapping int into the class.
A Introduction to Computing II Lecture 1: Java Review Fall Session 2000.
A data type in a programming language is a set of data with values having predefined characteristics.data The language usually specifies:  the range.
Another example of input import java.io.*; //import java.lang.Integer.*; class ExampleofInput2 { private static BufferedReader stdin = new BufferedReader(
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Input Characters from the Keyboard tMyn1 Input Characters from the Keyboard We have been using console output, but not console (keyboard) input. The main.
I/O in java and Revision. 2 I/O in Java Many packages and libraries associated with Java provide sophisticated ways to input and output information, e.g.:
Object Oriented Programming Lecture 2: BallWorld.
 It is a pure oops language and a high level language.  It was developed at sun microsystems by James Gosling.
Java Programming Lecture 2
Static Members and Methods
Yanal Alahmad Java Workshop Yanal Alahmad
Lecture 2: Data Types, Variables, Operators, and Expressions
Chapter 10 Thinking in Objects
Interactive Standard Input/output
Objects, Classes, Program Constructs
Computer Programming Methodology Input and While Loop
Examples of class: Using System.in.read ()
OUTPUT STATEMENTS GC 201.
CMSC 202 Static Methods.
null, true, and false are also reserved.
An Introduction to Java – Part I, language basics
Classes and Objects 5th Lecture
Java Classes and Objects 3rd Lecture
Classes and Objects Static Methods
Chapter 10 Thinking in Objects Part 2
Presentation transcript:

1 Input/Output

2 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 integer class 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.in class 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 line class 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 class Each 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 methods public 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 Objects public 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 wrapper public 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 wrapper class 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