Назад | Начало урока | Вперед
Содержание

Глава 4

Задача 4.2 "Усовершенствование класса Filer. "

Расширьте класс Filer, добавив к нему другой метод, который тоже называется open, но имеет параметр, показывающий сколько попыток можно сделать.

Решение

Код программы:



import java.io.*;
import javagently.*;

class Filer {

public static Stream open (String filename) throws IOException {

Stream in = new Stream (System.in);

for (int count = 0; count < 5; count ++) {

try {
return new Stream(filename, Stream.READ);
}
catch (FileNotFoundException e) {
System.out.println(filename+" does not exist.");
if (count < 4) {
System.out.println("Try again");
}
filename = in.readString();
}
}
throw new FileNotFoundException ();
}

public static Stream open (String filename, int num) throws IOException {

Stream in = new Stream (System.in);

for (int count = 0; count < num; count ++) {

try {
return new Stream(filename, Stream.READ);
}
catch (FileNotFoundException e) {
System.out.println(filename+" does not exist.");
if (count < (num-1)) {
System.out.println("Try again");
}
filename = in.readString();
}
}
throw new FileNotFoundException ();
}
}

class TableIndex {

TableIndex() throws IOException {

Stream in = new Stream(System.in);
// default the file to the keyboard
Stream fin = new Stream(System.in);

try {

System.out.print("What file for read table conversion?");
String filename = in.readString();
fin = Filer.open(filename,5);
}

catch (FileNotFoundException e) {

System.out.println("Five tries up");
System.out.println("Connecting to keyboard by default");
}

System.out.println("Conversion Table mile to kilometer");
System.out.println("============================");
System.out.println();
System.out.println("mile\tkilometer");

int mile; double km;

try {

for (;;) {
mile = fin.readInt();
km = fin.readDouble();
System.out.println(mile+"\t\t"+ Stream.format((km), 4, 2));
}
}


catch (EOFException e) {

System.out.println(" All data is reading ");
}


}


public static void main (String[] args) throws IOException {

new TableIndex ();
}
}


Результат :

Подсказка


Назад | Начало урока | Вверх | Вперед
Содержание

Hosted by uCoz