SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Walter Savitch ,kenrick Mock
Chapter:
File Io
Exercise:
Programming Projects
Question:2 | ISBN:9780132830317 | Edition: 5

Question

Write a program that will search a text file of strings representing numbers of type int and will write the largest and the smallest numbers to the screen. The file contains nothing but strings representing numbers of type int , one per line.


TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

import java.util.*;
import java.io.*;
public class SearchNumbers
{
	public static void main(String args[])
	{
		int maxNum,minNum;
		int nextSearch;
		Scanner inputFile = null;
		try
		{
			inputFile = new Scanner(new FileInputStream("numbersFile.txt"));
		}
		catch(FileNotFoundException e)
		{
			System.out.println("Sorry, this file could not not be found.");
		}
		maxNum = inputFile.nextInt();
		minNum = maxNum;
		while(inputFile.hasNextInt())
		{	
			nextSearch= inputFile.nextInt();

			if(minNum > nextSearch)
				minNum = nextSearch;
			if(maxNum < nextSearch)
				maxNum = nextSearch;
		}
		System.out.println("Smallest number in the file: " + minNum);
		System.out.println("Largest number in the file: " + maxNum);
	
	}
}

Input data in numbersFile.txt:

100
70
50
11
94
30
4
8
6
99
4

OUTPUT:

Smallest number in the file: 4
Largest number in the file: 100

 

1 0

Discussions

Post the discussion to improve the above solution.