Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Reading from a text file The easiest way to read data from a text file is to use the Scanner class. You are already very

Reading from a text file
The easiest way to read data from a text file is to use the Scanner class. You are already very familiar with the scanner class. Reading from a file is not different from readying from the keyword. To read the entire data from the file, the condition in the loop must check to see if there's more input. For example, if you are reaching each line until the end of the file, you would use scanner.hasNextLine() as the loop condition. It returns true if there's no more line to read and the loop terminates.
You can use the followings:
hasNextInt()
hasNextDouble()
hasNext()
hasNextLine()
The example below read from the file "input.txt" line by line until there's no more line to read.
File file = new File("input.txt");
Scanner s = new Scanner(file);
while( s.hasNextLine()){
String line = s.nextLine();
System.out.println(line);
}
As for reading data from the file, you can use the same scanner methods that you used in your previous programs.
nextInt()
nextDouble()
next()
nextLine()
When you use nextInt() on an input that is not an integer, nextInt() will throw the exception InputMismatchException.
So, write a program to read a text file containing integers and words and print the sum of the integers. You will use nextInt() to read the input. If an exception is thrown, it means that the input is not an integer. You want to handle the exception. If there's no exception, nextInt() is successful and you will want to add the value to the
First, you will need to create a file "data.txt" and manually type in at least 5 integers. Then write your program to read from the file "data.txt".
Sample file content
10
1
54
Sample run:
The sum is 20

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

DB2 Universal Database V7.1 Application Development Certification Guide

Authors: Steve Sanyal, David Martineau, Kevin Gashyna, Michael Kyprianou

1st Edition

0130913677, 978-0130913678

More Books

Students also viewed these Databases questions

Question

identify and evaluate a range of recruitment and selection methods

Answered: 1 week ago