Глава 3
Задача 3.6 "Другие таблицы "
Программу, которую мы использовали для печати таблицы преобразований, модифицируйте так, чтобы она позволяла выводить на печать таблицы для выполнения других преобразований, например:
- миль в километры
Для выполнения преобразований используйте типизированные методы
Решение
Типизированные методы - это методы, которые возвращают результат-значение определенного вида. Напишем простой метод перевода миль в километры и в главной программе вызовем этот метод в цикле.
// a simple conversion function
double kilometer(double mile) {
Код программы "Большая таблица преобразования миль в километры":
import java.text.*;
import javagently.*;
import java.util.*;
import java.io.*;
class LargeTable {
int colsPerLine = 5;
int maxLineNo = 20;
String gap = "\t\t";
LargeTable () {
// First print the headings
System.out.println("\t\tConversion Table mile to kilometer");
System.out.println("\t\t===================================");
System.out.println();
for (int col = 0; col < colsPerLine; col++)
System.out.print("mile km\t" + gap);
System.out.println();
// Seconnd, print the table:
// For each of the lines required, the outaLine
// method is called with the line number as a parameter
for (int r = 0; r < maxLineNo; r++)
outaLine(r);
}
void outaLine(int thisline) {
/* Using the information given by the parameter as
* to which line this is, the method calculates the
* celsius values for that line and displays them with
* their Fahrenheit equivalents
*/
for (int col = 0; col < colsPerLine; col++) {
int c = thisline * colsPerLine + col;
System.out.print(c + "\t\t");
System.out.print(Stream.format(kilometer(c), 3, 2) + gap);
}
System.out.println();
}
// a simple conversion function
double kilometer(double mile) {
return (mile*1.6);
}
public static void main(String[] args) {
new LargeTable () ;
}
}
Результат :
Назад |
Начало урока |
Вверх |
Вперед
Содержание