Reading Input from Text File

Similar documents
Computer Programming, I. Laboratory Manual. Experiment #5. Strings & Text Files Input

Loops. Eng. Mohammed Abdualal. Islamic University of Gaza. Faculty of Engineering. Computer Engineering Department

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn to write programs for executing statements repeatedly using a while, do while and for loop

ing execution. That way, new results can be computed each time the Class The Scanner

Building Java Programs

Computational Expression

A+ Computer Science -

Arrays. Eng. Mohammed Abdualal

Building Java Programs

A+ Computer Science -

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 19: NOV. 15TH INSTRUCTOR: JIAYIN WANG

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. File Input and Output

Experiment No: Group B_4

Building Java Programs

Building Java Programs

A token is a sequence of characters not including any whitespace.

Chapter 2 ELEMENTARY PROGRAMMING

Data Conversion & Scanner Class

Object Oriented Programming. Java-Lecture 1

CIS 110: Introduction to Computer Programming

CSCI 1103: File I/O, Scanner, PrintWriter

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Fundamentals of Programming Data Types & Methods

Eng. Mohammed Alokshiya

Eng. Mohammed S. Abdualal

CS 211: Existing Classes in the Java Library

Computer Science is...

Input. Scanner keyboard = new Scanner(System.in); String name;

Building Java Programs

Computational Expression

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Building Java Programs

COMP200 INPUT/OUTPUT. OOP using Java, based on slides by Shayan Javed

Building Java Programs

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

CSCI 1103: File I/O, Scanner, PrintWriter

ECE 122 Engineering Problem Solving with Java

AP Computer Science. File Input with Scanner. Copyright 2010 by Pearson Education

Computer Programming, I. Laboratory Manual. Experiment #2. Elementary Programming

Building Java Programs

H212 Introduction to Software Systems Honors

Programming with Java

Building Java Programs Chapter 6

A Quick and Dirty Overview of Java and. Java Programming

We now start exploring some key elements of the Java programming language and ways of performing I/O

CS244 Advanced Programming Applications

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

Methods. Eng. Mohammed Abdualal

Chapter 2 Elementary Programming

Chapter 2. Elementary Programming

Computer Programming, I. Laboratory Manual. Experiment #6. Loops

Java Console Input/Output The Basics. CGS 3416 Spring 2018

Programming II (CS300)

Topic 11 Scanner object, conditional execution

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

File I/O Array Basics For-each loop

Project 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java

Exception Handling. CSE 114, Computer Science 1 Stony Brook University

Welcome to the Using Objects lab!

Chapter 4 Classes in the Java Class Libraries

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Building Java Programs

Elementary Programming

A variable is a name for a location in memory A variable must be declared

C17a: Exception and Text File I/O

Text User Interfaces. Keyboard IO plus

Agenda & Reading. Python Vs Java. COMPSCI 230 S Software Construction

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

File class in Java. Scanner reminder. File methods 10/28/14. File Input and Output (Savitch, Chapter 10)

Full file at

Chapter 2: Data and Expressions

Excep&ons and file I/O

Chapter 2: Data and Expressions

COMP 202 File Access. CONTENTS: I/O streams Reading and writing text files. COMP File Access 1

File I/O Introduction to File I/O Text Files The File Class Binary Files 614

COSC 236 Section 101 Computer Science 1 -- Prof. Michael A. Soderstrand

Reading Text Files. 1 Reading from text files: Scanner

Java Console Input/Output The Basics

AL GHURAIR UNIVERSITY College of Computing. Objectives: Examples: Text-printing program. CSC 209 JAVA I

Input-Output and Exception Handling

JAVA Ch. 4. Variables and Constants Lawrenceville Press

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

Supplementary Test 1

EXCEPTIONS. Fundamentals of Computer Science I

CS 112 Introduction to Programming

Files. Reading data from files. File class. Compiler error with files. Checked exceptions. Exceptions. Readings:

Chapter 2 Primitive Data Types and Operations

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

Topic 11 Scanner object, conditional execution

Building Java Programs

CSC 222: Object-Oriented Programming. Fall 2017

Important Java terminology

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

File Processing. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. A Class for Representing a File

CS Programming I: File Input / Output

Transcription:

Islamic University of Gaza Faculty of Engineering Computer Engineering Department Computer Programming Lab (ECOM 2114) Lab 5 Reading Input from Text File Eng. Mohammed Alokshiya November 2, 2014

The simplest mechanism for reading an external text file is to use Scanner Class. You already know to use Scanner for reading console input. Instead of System.in, you first connect the file with a File object (defined in java.io package), then use that File object to construct a Scanner object. Scanner input = new Scanner(new File("input.txt")); This Scanner object (input) reads text from the file "input.txt". You can use the Scanner methods, such as next(), nextint(), nextline(), nextdouble(),to read data from the input file. input.next(); // read a string (one word only) delimited by a white-space (space, tab, newline) input.nextint(); // read an integer input.nextdouble(); // read a double input.nextline(); // read a string (the whole line) Note that the file input.txt must be in the main directory of the project, otherwise, you should specify the path of it. 2

Example: write a program to read student s information (full name, id, email, and mobile) from a file, and print them to the console. 1- Construct a Scanner object and connect the file "input.txt" using File Object. Scanner input = new Scanner(new File("input.txt")); 2- Add import statements for needed classes in external packages. Scanner defined in java.util package and File defined in java.io package, hence, add the following lines out of class body: import java.io.file; import java.util.scanner; Alternatively, use Netbeans shortcut (CTRL + SHIFT + I) to fix your imports. 3- Use Netbeans shortcuts to add throws clause for FileNotFoundException. [later you study Java Exceptions in details, but for now we do not have to know more about them] 3

Notice changes: 4- Use Scanner methods, such as nextint(), nextlong(), next(), nextline(), to read input from your file. ReadingInputFromTextFile.java import java.io.file; import java.io.filenotfoundexception; import java.util.scanner; public class ReadingInputFromTextFile { public static void main(string[] args) throws FileNotFoundException { Scanner input = new Scanner(new File("input.txt")); String name = input.nextline(); int id = input.nextint(); String email = input.next(); int mobile = input.nextint(); System.out.println(name); System.out.println(id); System.out.println(email); System.out.println(mobile); } } Output: 4

How Does Scanner Work? The nextbyte(), nextshort(), nextint(), nextlong(), nextfloat(), nextdouble(), and next() methods are known as token-reading methods, because they read tokens separated by delimiters. By default, the delimiters are whitespace characters. You can use the usedelimiter(string regex) method to set a new pattern for delimiters. How does an input method work? A token-reading method first skips any delimiters (whitespace characters by default), then reads a token ending at a delimiter. The token is then automatically converted into a value of the byte, short, int, long, float, or double type for nextbyte(), nextshort(), nextint(), nextlong(), nextfloat(), nextdouble(), respectively. For the next() method, no conversion is performed. If the token does not match the expected type, a runtime exception java.util.inputmismatchexception will be thrown. Both methods next() and nextline() read a string. The next() method reads a string delimited by delimiters, and nextline() reads a line ending with a line separator. The token-reading method does not read the delimiter after the token. If the nextline() method is invoked after a token-reading method, this method reads characters that start from this delimiter and end with the line separator. The line separator is read, but it is not part of the string returned by nextline(). Suppose a text file named test.txt contains a line 34 567 5

After the following code is executed, Scanner input = new Scanner(new File("test.txt")); int intvalue = input.nextint(); String line = input.nextline(); intvalue contains 34 and line contains the string " 567" (four characters ' ', 5, 6, and 7). What happens if the input is entered from the keyboard? Suppose you enter 34, press the Enter key, then enter 567 and press the Enter key for the following code: Scanner input = new Scanner(System.in); int intvalue = input.nextint(); String line = input.nextline(); You will get 34 in intvalue and an empty string in line. Why? Here is the reason. The token-reading method nextint() reads in 34 and stops at the delimiter, which in this case is a line separator (the Enter key). The nextline() method ends after reading the line separator and returns the string read before the line separator. Since there are no characters before the line separator, line is empty. You can read data from a file or from the keyboard using the Scanner class. You can also scan data from a string using the Scanner class. For example, the following code displays Scanner input = new Scanner("13 14"); int sum = input.nextint() + input.nextint(); System.out.println("Sum is " + sum); The sum is 27 6

Non-Assessed Exercise: (Evaluate simple expressions) Write a program to read 5 lines from a text file, each line representing a simple equations with one operator (*, /, +, -, %), and two operands (decimal numbers) (Ex. 5 * 6.3 ), and output the result of each one in separated line on the console. Sample input: Sample output: 7