1.5 Input and Output Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October.

Slides:



Advertisements
Similar presentations
Chapter 18 Building the user interface. This chapter discusses n Javas graphical user interface. n Swing: an enhancement of a library called the Abstract.
Advertisements

Week 8 - Monday.  What did we talk about last time?  StdAudio.
Week 7: Input and Output 1.  Now we are going to talk a little bit about output  You have a lot of experience with System.out.println() and System.out.print()
Video Game Design Lesson 1. Game Designer Person involved in the development of a video game Person involved in the development of a video game Usually.
INPUT, OUTPUT, And STORAGE DEVICE
Discovering Computers Fundamentals, Third Edition CGS 1000 Introduction to Computers and Technology Fall 2006.
Announcement About HW-2 Deadline Extended – 11:55 PM Thursday 5% Extra Credit if you meet the original deadline See the from the TAs for the details.
Graphical User Interfaces
Computer Parts There are many parts that work together to make a computer work.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
Programming Task: Task 1 Controlled Assessment Practice.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
Io package as Java’s basic I/O system continue’d.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 1 Introduction to Computers and Programming.
CSC 125 Introduction to C++ Programming Chapter 1 Introduction to Computers and Programming.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington User Interface COMP 112 #30.
2-3 note. 2 Peripheral Devices “Peripheral devices” are hardware plugged into ports or connected to a computer wirelessly. These devices can be for input,
Introduction to Computers
Intro to GUIs (Graphical User Interfaces) Section 2.5Intro. to GUIs: a GUI Greeter Section 3.7Graphical/Internet Java: Einstein's Equation.
Lesson 27: Introduction to the Java GUI. // helloworldbutton.java import java.awt.*; import javax.swing.*; class HelloButton{ public static void main.
Layout Management Containers can arrange their components. Our container is a JPanel, and it can set the way it’s components will be laid out : mypanel.setLayout.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Chapter 2: Java Fundamentals
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
GUIs for Video Games. The Plan ● Layout suggestions ● Observer/Observable ● Steps to writing Observer/Observables ● Sample Code ● Practice.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
CS177 RECITATION WEEK 7 Input and Output (Text & Graphical)
An Introduction to Programming and Object Oriented Design using Java 3 rd Edition. Dec 2007 Jaime Niño Frederick Hosch Chapter 18 Integrating user interface.
ITEC 109 Lecture 27 GUI. GUIs Review Sounds –Arrays hold sample values –Creating a keyboard –Sound effects Homework 3 –The big two –Due after break –Lab.
2.1 Functions Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · 9/10/08 9/10/08.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
Lesson 39: More wrapup on GUIs. 1.This presentation will focus on the decisions around software architecture and the decisions that will drive the code.
 GUI – Graphic User Interface  Up to now in the programs we have written all output has been sent to the standard output device i.e.: the DOS console.
Lesson No: 6 Introduction to Windows XP CHBT-01 Basic Micro process & Computer Operation.
Recap of Functions. Functions in Java f x y z f (x, y, z) Input Output Algorithm Allows you to clearly separate the tasks in a program. Enables reuse.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
A simple swing example GETTING STARTED WITH WIND CHILL.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 1 Introduction to Computers and Programming.
File Input and Graphics An extract of slides from set 05_inout.ppt Designed to get you ready for the HW3.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Tutorial 2 – Welcome Application Introduction to Graphical.
Basics of GUI Programming Chapter 11 and Chapter 22.
Lecture # 6 Graphical User Interface(GUI). Introduction A graphical user interface (GUI) presents a user- friendly mechanism for interacting with an application.
1 Introduction to Computers Prof. Sokol Computer and Information Science Brooklyn College.
Brief Version of Starting Out with C++ Chapter 1 Introduction to Computers and Programming.
1 IM103 week 10 Enhancing the user interface By the end of lecture you should be able to:  distinguish between heavyweight and lightweight components;
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Graphical User Interface (GUI)
CHARACTER INPUT / OUTPUT AND INPUT VALIDATION. Introduction Input and output devices: keyboards, disk drives, mouse, monitors, printers. I/O functions.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
CS 112 Introduction to Programming Java Graphics Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
2.4 A Case Study: Percolation Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 1: Introduction to Computers and Programming.
CPCS 391 Computer Graphics Lab One. Computer Graphics Using Java What is Computer Graphics: Computer graphics are graphics created using computers and,
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
GUI.1 Graphical User Interfaces GUIs. GUI.2 The Plan Components Flat Layouts Hierarchical Layouts Designing a GUI Coding a GUI.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A Quick Java Swing Tutorial
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
A First Look at GUI Applications
Ellen Walker Hiram College
1.5 Input and Output Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2002–2010 2/14/11.
Windows Operating System
Presentation transcript:

1.5 Input and Output Introduction to Programming in Java: An Interdisciplinary Approach · Robert Sedgewick and Kevin Wayne · Copyright © 2008 · October 1, :26 tt

2 Input and Output Input devices. Output devices. Goal. Java programs that interact with the outside world. Display Speakers MP3 Player Printer MouseKeyboard Digital camera Microphone Hard driveNetwork Hard drive Network

3 Input and Output Input devices. Output devices. Our approach. n Define Java libraries of functions for input and output. n Use operating system (OS) to connect Java programs to: file system, each other, keyboard, mouse, display, speakers. Display Speakers MP3 Player Printer MouseKeyboard Digital camera Microphone Hard driveNetwork Hard drive Network

4 Digital Michelangelo Project Goal. Precise 3D description of the David. n Laser rangefinder. n 5,000 hours of scanning, 32 Gigabytes !

5 Terminal. Application where you can type commands to control the operating system. Terminal Mac OS XMicrosoft Windows

6 Command-Line Input and Standard Output Command-line input. Read an integer N as command-line argument. Standard output. n Flexible OS abstraction for output. In Java, output from System.out.println() goes to stdout. By default, stdout is sent to Terminal. public class RandomSeq { public static void main(String[] args) { int N = Integer.parseInt(args[0]); for (int i = 0; i < N; i++) { System.out.println(Math.random()); } % java RandomSeq

7 Old Bird's Eye View

8 New Bird's Eye View

Standard Input and Output

10 Command-line Input vs. Standard Input Command line inputs. n Use command line inputs to read in a few user values. n Not practical for many user inputs. n Input entered before program begins execution. Standard input. n Flexible OS abstraction for input. By default, stdin is received from Terminal window. n Input entered while program is executing.

11 Standard Input and Output Standard input. We provide library StdIn to read text input. Standard output. We provide library StdOut to write text output.

12 Standard Input and Output To use. Download StdIn.java and StdOut.java from booksite, and put in working directory (or use classpath). public class Add { public static void main(String[] args) { StdOut.print("Type the first integer: "); int x = StdIn.readInt(); StdOut.print("Type the second integer: "); int y = StdIn.readInt(); int sum = x + y; StdOut.println("Their sum is " + sum); } % java Add Type the first integer: 1 Type the second integer: 2 Their sum is 3 see booksite

13 Averaging A Stream of Numbers Average. Read in a stream of numbers, and print their average. public class Average { public static void main(String[] args) { double sum = 0.0; // cumulative total int n = 0; // number of values while (!StdIn.isEmpty()) { double x = StdIn.readDouble(); sum = sum + x; n++; } StdOut.println(sum / n); } % java Average is OS X/Linux/Unix EOF is Windows analog currently no DrJava analog

Redirection and Piping

15 % java RandomSeq 1000 > data.txt redirect stdout Redirecting Standard Output Redirecting standard output. Use OS directive to send standard output to a file for permanent storage (instead of terminal window).

16 % more < data.txt … % java Average < data.txt redirect stdin Redirecting Standard Input Redirecting standard input. Use OS directive to read standard input from a file (instead of terminal window).

17 Connecting Programs Piping. Use OS directive to make the standard output of one program become the standard input of another. % java RandomSeq | java Average

Standard Drawing

19 Standard Draw Standard drawing. We provide library StdDraw to plot graphics. To use. Download StdDraw.java and put in working directory. (0, 0) (1, 0) (½, ½  3) public class Triangle { public static void main(String[] args) { double t = Math.sqrt(3.0) / 2.0; StdDraw.line(0.0, 0.0, 1.0, 0.0); StdDraw.line(1.0, 0.0, 0.5, t); StdDraw.line(0.5, t, 0.0, 0.0); StdDraw.point(0.5, t/3.0); } % java Triangle

20 Data Visualization Plot filter. Read in a sequence of (x, y) coordinates from standard input, and plot using standard drawing. public class PlotFilter { public static void main(String[] args) { double xmin = StdIn.readDouble(); double ymin = StdIn.readDouble(); double xmax = StdIn.readDouble(); double ymax = StdIn.readDouble(); StdDraw.setXscale(xmin, xmax); StdDraw.setYscale(ymin, ymax); while (!StdIn.isEmpty()) { double x = StdIn.readDouble(); double y = StdIn.readDouble(); StdDraw.point(x, y); } rescale coordinate system read in points, and plot them

21 Data Visualization % more < USA.txt % java PlotFilter < USA.txt coordinates of 13,509 US cities bounding box

22 Plotting a Function double[] a = new double[N+1]; for (int i = 0; i <= N; i++) a[i] = Math.sin(4*Math.PI*i/N) + Math.sin(20*Math.PI*i/N); StdDraw.setXscale(0, N); StdDraw.setYscale(-2.0, +2.0); for (int i = 0; i < N; i++) StdDraw.line(i, a[i], i+1, a[i+1]);

23 Chaos Game Chaos game. Play on equilateral triangle, with vertices R, G, B. n Start at R. Repeat the following N times: – pick a random vertex – move halfway between current point and vertex – draw a point in color of vertex Q. What picture emerges? R: (0, 0) G: ( 1, 0) B: ( ½, ½  3) B B G R B G …

24 Chaos Game public class Chaos { public static void main(String[] args) { int T = Integer.parseInt(args[0]); double[] cx = { 0.000, 1.000, }; double[] cy = { 0.000, 0.000, }; double x = 0.0, y = 0.0; for (int t = 0; t < T; t++) { int r = (int) (Math.random() * 3); x = (x + cx[r]) / 2.0; y = (y + cy[r]) / 2.0; StdDraw.point(x, y); } ½  3 (avoid hardwired constants like this) between 0 and 2

25 Chaos Game Easy modification. Color point according to random vertex chosen using StdDraw.setPenColor(StdDraw.RED) to change the pen color. R G B Sierpinski triangle % java Chaos 10000

26 Commercial Break

27 Barnsley Fern Barnsley fern. Play chaos game with different rules. Q. What does computation tell us about nature? Q. What does nature tell us about computation? 20 th century sciences. Formulas. 21 st century sciences. Algorithms? 2%.50.27y probabilitynew xnew y 15% -.14x +.26y x +.22y %.17x -.21y x +.18y %.78x +.03y x +.74y +.27

28 Animation Animation loop. Repeat the following: n Clear the screen. n Move the object. n Draw the object. n Display and pause for a short while. Ex. Bouncing ball. Ball has position (rx, ry) and constant velocity (vx, vy). n Detect collision with wall and reverse velocity. (rx, ry) (vx, vy) (-1, -1) (+1, +1)

29 Bouncing Ball public class BouncingBall { public static void main(String[] args) { double rx =.480, ry =.860; double vx =.015, vy =.023; double radius =.05; StdDraw.setXscale(-1.0, +1.0); StdDraw.setYscale(-1.0, +1.0); while(true) { if (Math.abs(rx + vx) > 1.0) vx = -vx; if (Math.abs(ry + vy) > 1.0) vy = -vy; rx = rx + vx; ry = ry + vy; StdDraw.clear(StdDraw.GRAY); StdDraw.setPenColor(StdDraw.BLACK); StdDraw.filledCircle(rx, ry, radius); StdDraw.show(50); } bounce position constant velocity update position clear background draw the ball turn on animation mode: display and pause for 50ms rescale coordinates radius

30 Special Effects Images. Put.gif,.png, or.jpg file in the working directory and use StdDraw.picture() to draw it. Sound effects. Put.wav,.mid, or.au file in the working directory and use StdAudio.play() to play it. Ex. Modify BouncingBall to display image and play sound upon collision. Replace StdDraw.filledCircle() with: n Add following code upon collision with wall: StdAudio.play("boing.wav"); StdDraw.picture(rx, ry, "earth.gif");

1.5 Extra Slides

32 User Interfaces Command line interface. n User types commands at terminal. n Easily customizable. n Extends to complex command sequences. Point and click. n User launches applications by clicking. – File  Open  HelloWorld.java n Restricted to pre-packaged menu options.

33 Swing Graphical User Interface "Swing" is Java's GUI. n Buttons. n Menus. n Scrollbars. n Toolbars. n File choosers. Ignore details. import javax.swing.*; import java.awt.*; import java.awt.event.*; public class GUI implements ActionListener { private int clicks = 0; private JFrame frame = new JFrame(); private JLabel label = new JLabel("Number of clicks: 0 "); public GUI() { JButton button = new JButton("Click Me"); button.addActionListener(this); JPanel panel = new JPanel(); panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30)); panel.setLayout(new GridLayout(0, 1)); panel.add(button); panel.add(label); frame.add(panel, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setTitle("GUI"); frame.pack(); frame.show(); } public void actionPerformed(ActionEvent e) { clicks++; label.setText("Number of clicks: " + clicks); }; public static void main(String[] args) { GUI gui = new GUI(); } a sample Swing application

34 Computer animation. Display a sequence of closely related images in rapid succession to produce the illusion of movement. Frame rate. Use frames per second to "trick" human eye and brain into seeing smooth motion. Ex 1. Television and motion pictures. Ex 2. Java mascot Duke cart-wheeling. Computer Animation

35 Java Implementation public class Duke { public static void main(String[] args) { int images = 17; int WIDTH = 130, HEIGHT = 80; StdDraw.setCanvasSize(WIDTH, HEIGHT); for (int t = 0; true; t++) { int i = 1 + (t % images); String file = "T" + i + ".gif"; StdDraw.picture(0.5, 0.5, file); StdDraw.show(100); } T1.gif - T17.gif

36 Operating System Specific Details Common OS abstractions., | Redirection, pipes Ctrl-d Ctrl-z End of file more less more less more Scroll through text, one screenful at a time File system List files in current directory Newline character File name completion Cycle through recent command Operation \n \n or \r \r\n ls dir C:\introcs\Hi.java Tab Up, down arrows Windows XP /u/introcs/Hi.java Tab Up, down arrows UnixOS X Unix means Unix variants (Linux, Solaris, Aix) Most Windows XP commands also supported in other version of Windows.

37 Twenty Questions Twenty questions. User thinks of an integer between one and 1 million. Computer tries to guess it. Binary search. Each question removes half of possible remaining values. Consequence. Always succeeds after 20 questions. public class TwentyQuestions { public static void main(String[] args) { int lo = 1, hi = ; while (lo < hi) { int mid = (lo + hi) / 2; StdOut.println("Is your number <= " + mid + "?"); boolean response = StdIn.readBoolean(); if (response) hi = mid; else lo = mid + 1; } StdOut.println("Your number is " + lo); } 2 20  1 million invariant: user's number always between lo and hi