Reading Input From A File



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

Using Files as Input/Output in Java 5.0 Applications

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

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

AP Computer Science File Input with Scanner

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

CS 121 Intro to Programming:Java - Lecture 11 Announcements

Object-Oriented Programming in Java

Chapter 2: Elements of Java

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

13 File Output and Input

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

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

Introduction to Java. CS 3: Computer Programming in Java

Building a Multi-Threaded Web Server

Introduction to Java

Programming Languages CIS 443

Visit us at

JAVA.UTIL.SCANNER CLASS

Basics of Java Programming Input and the Scanner class

Token vs Line Based Processing

Chapter 2 Introduction to Java programming

D06 PROGRAMMING with JAVA

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Course Intro Instructor Intro Java Intro, Continued

Topics. Parts of a Java Program. Topics (2) CS 146. Introduction To Computers And Java Chapter Objectives To understand:

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

Line-based file processing

CS 106 Introduction to Computer Science I

Importing Data from a Dat or Text File into SPSS

Building Java Programs

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

Comp 248 Introduction to Programming

Iteration CHAPTER 6. Topic Summary

Building Java Programs

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

Some Scanner Class Methods

In this Chapter you ll learn:

Files and input/output streams

CS506 Web Design and Development Solved Online Quiz No. 01

Lecture 1 Introduction to Java

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

Building Java Programs

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

Decision-making Computer Science Lesson to Prepare for UIL Computer Science Contest

Moving from CS 61A Scheme to CS 61B Java

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

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

Topic 11 Scanner object, conditional execution

Reading and writing files

Sample CSE8A midterm Multiple Choice (circle one)

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

Time Clock Import Setup & Use

ECE 122. Engineering Problem Solving with Java

10 Database Utilities

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

Chapter 3. Input and output. 3.1 The System class

AP Computer Science Java Subset

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

Install Java Development Kit (JDK) 1.8

JavaScript: Control Statements I

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

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

Arrays. Introduction. Chapter 7

IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

UIL Computer Science for Dummies by Jake Warren and works from Mr. Fleming

Help File. Version February, MetaDigger for PC

Creating a Simple, Multithreaded Chat System with Java

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

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

Lecture 5: Java Fundamentals III

qwertyuiopasdfghjklzxcvbnmqwerty uiopasdfghjklzxcvbnmqwertyuiopasd fghjklzxcvbnmqwertyuiopasdfghjklzx cvbnmqwertyuiopasdfghjklzxcvbnmq

Event-Driven Programming

How To Use Optimum Control EDI Import. EDI Invoice Import. EDI Supplier Setup General Set up

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

SPSS for Windows importing and exporting data

Introduction to Python

Lesson: All About Sockets

Bulk Downloader. Call Recording: Bulk Downloader

CS 1302 Ch 19, Binary I/O

LOOPS CHAPTER CHAPTER GOALS

Division of Informatics, University of Edinburgh

CSE 1020 Introduction to Computer Science I A sample nal exam

Compiler Construction

Exception Handling. Overloaded methods Interfaces Inheritance hierarchies Constructors. OOP: Exception Handling 1

Setting up Auto Import/Export for Version 7

2 Getting Started with jgrasp 2.0

Basics of I/O Streams and File I/O

JAVA - QUICK GUIDE. Java SE is freely available from the link Download Java. So you download a version based on your operating system.

While and Do-While Loops Summer 2010 Margaret Reid-Miller

User Guide for Payroll Service (APS+)

10 Java API, Exceptions, and Collections

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

Programming and Data Structures with Java and JUnit. Rick Mercer

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

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

csce4313 Programming Languages Scanner (pass/fail)

Transcription:

Reading Input From A File In addition to reading in values from the keyboard, the Scanner class also allows us to read in numeric values from a file. 1. Create and save a text file (.txt or.dat extension) in the same folder with the.java file. 2. At the very top of your program add the line import java.io.*; //for File and IOException //for Scanner 3. Add throws IOException after the header of the main method. When working with files, a program may encounter errors that it cannot handle. Examples are the file could be missing when the program tries to open it, or the file s data may be corrupted. At a minimum, a program must acknowledge that an I/O exception might be thrown. 4. In the main method, create a Scanner object (this one is named reader) to read from a file (this one is named myfile.txt). Scanner reader = new Scanner(new File( myfile.txt )); 5. In the main method, create a sentinel-controlled loop. The idea of a sentinel controlled loop is that there is a special value (the sentinel) that is used to say when the loop is done. In this case, the loop will continue to read from the file until the hasnext() method returns false (when the end of the file has been reached). //statement //statement 6. Close the scanner object when your program is done using it. reader.close(); Useful Methods reader.hasnext() Returns true if the scanner has another token in its input reader.hasnextline() Returns true if the scanner has another line reader.hasnextint() Returns true if the next token in the scanner can be interpreted as an int reader.hasnextdouble() Returns true if the next token in the scanner can be interpreted as a double

User input is not part of the AP Java subset. There are many possible ways for supplying user input. If reading input is necessary, it will be indicated in a way similar to the following: or double x = call to a method that reads a floating-point number; double x = IO.readDouble(); // read user input A Sample Program This program reads in numerical data from a file, token by token. Remember, the Scanner object assumes that whitespace characters (spaces, tabs, and new lines) are used to separate the input elements (tokens) from each other. public class ComputeAverage Scanner reader = new Scanner(new File( numbers.txt )); double number, sum=0; int count = 0; number = reader.nextdouble(); sum += number; count++; if(count == 0) System.out.println( The file has no numbers. ); else System.out.println( The average of + count + numbers is + sum / count); reader.close(); //close the Scanner

Another Sample Program This program reads in data line by line (the first loop) then reads each line token by token (the nested loop). One scanner is used to read in the lines; a second scanner is used to public class ComputeAverage //does something Scanner readfile = new Scanner(new File( numbers.txt )); Scanner readline = new Scanner double number, sum=0; int count = 0; number = reader.nextdouble(); sum += number; count++; if(count == 0) System.out.println( The file has no numbers. ); else System.out.println( The average of + count + numbers is + sum / count); reader.close(); //close the Scanner

Errors You May Encounter InputMismatchException: This exception can be thrown if you try to get the next token using a next method that does not match the type of the token FileNotFound Exception: Thrown when the file is missing when the program tries to open it Defining Your Own Delimiter By default, the Scanner will read data as tokens separated by whitespace. If you want to read in data separated by something else (comma, colon, etc.) you can create your own delimiter. scan.usedelimiter(",\\s*"); //comma followed by spaces scan.usedelimiter("\\s*dog\\s*"); //space then the word dog then space scan.usedelimiter("/"); //slash A Comma Delimited Program public class UseCommas //reads a file of numbers separated by commas Scanner scan3 = new Scanner(new File( commadata.txt )); String line = null; while(scan3.hasnext()) line = scan3.nextline(); Scanner scan4 = new Scanner(line); scan4.usedelimiter(", "); //a comma while(scan4.hasnextint()) System.out.println(scan4.nextInt()); scan3.close();