CS 121 Intro to Programming:Java - Lecture 11 Announcements



Similar documents
File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Using Files as Input/Output in Java 5.0 Applications

Course Intro Instructor Intro Java Intro, Continued

13 File Output and Input

Reading Input From A File

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Line-based file processing

Introduction to Java

Basics of Java Programming Input and the Scanner class

Introduction to Java. CS 3: Computer Programming in Java

System.out.println("\nEnter Product Number 1-5 (0 to stop and view summary) :

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Explain the relationship between a class and an object. Which is general and which is specific?

Chapter 2 Introduction to Java programming

JAVA ARRAY EXAMPLE PDF

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Topic 11 Scanner object, conditional execution

AP Computer Science File Input with Scanner

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

Chapter 2: Elements of Java

Install Java Development Kit (JDK) 1.8

Building Java Programs

Object-Oriented Programming in Java

Part I. Multiple Choice Questions (2 points each):

Sample CSE8A midterm Multiple Choice (circle one)

public static void main(string[] args) { System.out.println("hello, world"); } }

Building Java Programs

Building Java Programs

Using Two-Dimensional Arrays

Homework/Program #5 Solutions

AP Computer Science Java Mr. Clausen Program 9A, 9B

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Building Java Programs

Creating a Simple, Multithreaded Chat System with Java

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

CompSci 125 Lecture 08. Chapter 5: Conditional Statements Chapter 4: return Statement

D06 PROGRAMMING with JAVA

Lecture J - Exceptions

AP Computer Science Static Methods, Strings, User Input

JDK 1.5 Updates for Introduction to Java Programming with SUN ONE Studio 4

Chapter 3. Input and output. 3.1 The System class

The following program is aiming to extract from a simple text file an analysis of the content such as:

Building a Multi-Threaded Web Server

MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

D06 PROGRAMMING with JAVA

Chapter 2. println Versus print. Formatting Output withprintf. System.out.println for console output. console output. Console Input and Output

Interactive Applications (CLI) and Math

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Lesson: All About Sockets

COSC Introduction to Computer Science I Section A, Summer Question Out of Mark A Total 16. B-1 7 B-2 4 B-3 4 B-4 4 B Total 19

Scanner sc = new Scanner(System.in); // scanner for the keyboard. Scanner sc = new Scanner(System.in); // scanner for the keyboard

Arrays. Introduction. Chapter 7

CS 1302 Ch 19, Binary I/O

CSE 8B Midterm Fall 2015

Introduction to Programming

J a v a Quiz (Unit 3, Test 0 Practice)

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

Programming Languages CIS 443

Programming Fundamentals I CS 110, Central Washington University. November 2015

Files and input/output streams

WHAT ARE PACKAGES? A package is a collection of related classes. This is similar to the notion that a class is a collection of related methods.

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

OBJECT ORIENTED PROGRAMMING LANGUAGE

Question R11.3. R11.3 How do you open a file whose name contains a backslash, like c:\temp\output.dat?

CS 111 Classes I 1. Software Organization View to this point:

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Week 1: Review of Java Programming Basics

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

java.util.scanner Here are some of the many features of Scanner objects. Some Features of java.util.scanner

CS170 Lab 11 Abstract Data Types & Objects

CS 112/ Section 02 Hilal Ünal Aslıhan Ekim Merve Özkılınç Notes of March 11, 2008 and March 13, 2008: Pig Latin: add adday. main.

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Event-Driven Programming

Word Count Code using MR2 Classes and API

(Eng. Hayam Reda Seireg) Sheet Java

CS506 Web Design and Development Solved Online Quiz No. 01

Unit 6. Loop statements

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Programming and Data Structures with Java and JUnit. Rick Mercer

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

JAVA Program For Processing SMS Messages

Crash Course in Java

LOOPS CHAPTER CHAPTER GOALS

Assignment 4 Solutions

WRITING DATA TO A BINARY FILE

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

MIDTERM 1 REVIEW WRITING CODE POSSIBLE SOLUTION

Token vs Line Based Processing

6.1. Example: A Tip Calculator 6-1

Comp 248 Introduction to Programming

Division of Informatics, University of Edinburgh

Designing with Exceptions. CSE219, Computer Science III Stony Brook University

Transcription:

CS 121 Intro to Programming:Java - Lecture 11 Announcements Next Owl assignment up, due Friday (it s short!) Programming assignment due next Monday morning Preregistration advice: More computing? Take 191B, or - if you re really thriving in this class - 187 (come see me about this) Final exam: 12/19, 8 AM

Topics for today: File IO - How to read from, write to external files Exceptions will also get some attention

import java.util.scanner; import java.io.*; public class DisplayFile{ public static void main(string[] args) throws IOException { String filename; Scanner namereader = new Scanner(System.in); System.out.println("Enter a file name"); filename = namereader.nextline(); Scanner scan = new Scanner(new FileReader(fileName)); while(scan.hasnext()){ System.out.println(scan.nextLine()); scan.close();

import java.util.scanner; import java.io.*; public class Echo{ String filename; // external file name Scanner scan; // reads from external file public Echo(String f) throws IOException { filename = f; scan = new Scanner(new FileReader(fileName));

public void readlines(){ while(scan.hasnext()){ processline(scan.nextline()); scan.close(); public void processline(string line){ System.out.println(line);

import java.util.scanner; import java.io.*; public class ReadDriver{ public static void main(string[] args) { throws IOException String filename; Scanner namereader = new Scanner(System.in); System.out.println("Enter a file name"); filename = namereader.nextline(); Echo e = new Echo(fileName); e.readlines();

import java.io.*; public class LineCount extends Echo{ private int count = 0; public LineCount(String f) throws IOException { super(f); public void processline(string line){count++; public void reportlinecount(){ System.out.println("Line count: " + count);

import java.io.*; import java.util.*; public class WriteFile{ public static void main(string[] args) throws IOException { String filename; System.out.println("Enter a file name. It will hold output"); Scanner namereader = new Scanner(System.in); filename = namereader.nextline(); PrintWriter writer = new PrintWriter(fileName); Scanner scan = new Scanner(System.in); String s = " "; // a String of length 1 System.out.println("Enter text, end with 2 returns"); while(s.length() > 0){ s = scan.nextline(); writer.println(s);

writer.close(); // now echo the file back to the console Echo e = new Echo(fileName); System.out.println("Here comes the echo"); System.out.println(); e.readlines();

Our next example ilatlstrues a bizzare anodecte that ciurctaled on the web seevral years ago, and casued wiesrpdead giglges among all who saw it. The story corecnns an exereipmnt by Brtiish reehrsaecrs that put forawrd the foiwlolng arguemnt: it turns out that if you take a seibsnle body of text, exartct each word, leave the first two and last two letters of every word unoctuhed, but then raondmly rernaarge the rest - that is, the mildde, then the enuisng text is colpmteely unbdasdearnlte.

import java.util.*; import java.io.*; public class ScrambleDriver{ public static void main(string[] args) throws IOException { Scanner scan = new Scanner(System.in); System.out.println("enter file name"); String filename = scan.next(); TextScramble scram = new TextScramble(fileName); scram.readlines();

import java.io.*; import java.util.*; public class TextScramble extends Echo{ Random r = new Random(); String blank = " "; public TextScramble(String f) throws IOException { super(f);

public void processline(string line){ String s = blank; String answer = ""; char[] mid; StringTokenizer str = new StringTokenizer(line); while(str.hasmoretokens()){ s = str.nexttoken(); if (s.length() < 6) answer = answer+ s + blank; else { // carve up the token.. String front = s.substring(0,2); String back = s.substring(s.length() - 2, s.length()); String middle = s.substring(2,s.length() -2); mid = middle.tochararray(); // make middle an array shuffle(mid); // shuffle middle = new String(mid); // transform back to a String answer = answer +front + middle + back + blank; // end loop processing all tokens in line System.out.println(answer);

Java has a shadow system for handling errors: Exceptions This is a system of classes and objects that employ special machinery for detectings errors and shifting responsibilites for handling these problems Java recognized two kinds of errors: Unchecked exceptions: errors that occur because of flaws in logical thinking on the part of the programmer (e.g. division by 0) Checked exceptions: errors that can be expected to occur, and may occur despite your best efforts to avoid them (trying to read from a file that doesn t exist)

public class Except0{ public static void main(string[] args){ int k; int a = 3; ; int b = 0; k = a/b; Java reports: Exception in thread "main" java.lang.arithmeticexception: / by zero ÏÏ Ï at Except0.main(Except0.java:7)

Java has special machinery, the try/catch construction, for dealing with exceptions (handling exceptions) An exception is handled if your code detects the error and takes some action in response -- as in the next example.

public static void main(string[] args){ int k; int a = 3; int b = 0; try{ k = a/b; catch(arithmeticexception e) { System.out.println( e); Java reports: Ïjava.lang.ArithmeticException: / by zero ÏÏ Ï

public class Except3{ public static void main(string[] args){ String s = "98.6"; int n; try{ n = Integer.parseInt(s); System.out.println(n*n); catch(exception e) { e.printstacktrace();

Ïjava.lang.NumberFormatException: For input string: "98.6" ÏÏ Ï at java.lang.numberformatexception.forinput String(NumberFormatException.java:48) ÏÏ Ï at java.lang.integer.parseint(integer.java:456) ÏÏ Ï at java.lang.integer.parseint(integer.java:497) ÏÏ Ï at Except3.main(Except3.java:8) ÏÏ Ï

A more realistic example - you are supposed to enter an integer, representing your name (the program then reports your age for next year..) Some interaction: Ïenter your age ¼¼ Ï39e ÏÏ ÏBad input. 39e is not an integer. You must input an integer Ïenter your age ¼¼ Ï39 ÏÏ Ïnext year you will be 40 ÏÏ Ï

import java.io.*; import java.util.*; public class IntegerInput{ public static void main(string[] args){ int n = -1; Scanner scan = new Scanner(System.in); while (n < 0) { System.out.println("enter your age"); try { if (scan.hasnextint()) n = scan.nextint(); else { // non integer submitted String userinput = scan.next(); throw new Exception("Bad input. "+ userinput + " is not an integer. You must input an integer");

catch (Exception e) { System.out.println(e.getMessage()); System.out.println("next year you will be " + (n + 1)); What does throw do: it presents an exception object of the indicated kind at a new location in the program..

What if you enter a negative number? Not handled very well (No message).. enter your age ¼¼ Ï-39 enter your age

One way to handle this: make a new kind of Exception.. public class NegativeException extends Exception{ public NegativeException() { ; public NegativeException(String msg){ super(msg); And then:

while (n < 0) { System.out.println("enter your age"); try { if (scan.hasnextint()) n = scan.nextint(); else { String userinput = scan.next(); throw new Exception("Bad input. "+ userinput + "is not an integer. You must input an integer"); if (n < 0) throw new NegativeException();

catch (NegativeException e) { System.out.println("age must be >= 0"); catch (Exception e) { System.out.println(e.getMessage()); // end while System.out.println("next year you will be " + (n + 1)); Notice: two kinds of exceptions, more specific one first

One more example: You have a data file of numerical data, integers, one per line It may contain errors (deep space information?) You want to compute the average value of the entries - but you re happy just to skip over the bad data

Here is nums.txt 50 60 3e 10 Here s the output: ÏBad Entry: 3e Ï40.0

import java.io.*; import java.util.*; public class NumberReader { String filename; int sum = 0; int count = 0; Scanner scan; Handle IOEX when I m called public NumberReader(String f) throws IOException { filename = f; scan = new Scanner(new FileReader(fileName)); public void readlines(){while(scan.hasnext()){ processline(scan.nextline()); scan.close();

public void processline(string line){ try{ int num = Integer.parseInt(line); sum += num; count++; catch(exception e) {System.out.println("Bad Entry: " + line); public void printresult(){ System.out.println((double)sum/count);

public class NumDriver{ public static void main(string[] args){ try{ NumberReader num = new NumberReader("nums.txt"); num.readlines(); num.printresult(); catch(exception e) {e.printstacktrace();

This is tacky: public class ReadDriver{ public static void main(string[] args) { throws IOException String filename; Scanner namereader = new Scanner(System.in); System.out.println("Enter a file name"); filename = namereader.nextline(); Echo e = new Echo(fileName); e.readlines();

public class ReadDriver{ public static void main(string[] args) { try{ String filename; Scanner namereader = new Scanner(System.in); System.out.println("Enter a file name"); filename = namereader.nextline(); Echo e = new Echo(fileName); e.readlines(); Catch(IOException e){system.out.println(e);