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

Глава 3

Задача 3.6 "Другие таблицы "

Программу, которую мы использовали для печати таблицы преобразований, модифицируйте так, чтобы она позволяла выводить на печать таблицы для выполнения других преобразований, например:

- градусов Цельсия в градусы Фаренгейта
- миль в километры
- литров в галлоны
- долларов в национальную валюту

Для выполнения преобразований используйте типизированные методы

Решение

Типизированные методы - это методы, которые возвращают результат-значение определенного вида. Напишем простой метод перевода температуры из градусов Цельсия в градусы Фаренгейта и в главной программе вызовем этот метод в цикле.

// a simple conversion function
long fahrenheit(int celsius) {

return Math.round(celsius*9.0/5 + 32);
}

Код программы "Таблица преобразования температуры из градусов Цельсия в градусы Фаренгейта":


class LargeTable {

/* Large Temperature Table Program by JM Bishop Sept 1996
* ------------------------------- Java 1.1
* updated April 2000
* Produces a conversion table from Celsius to Fahrenheit
* for values from 0 to 99.
*
* Illustrates for-loops, methods for structuring,
* typed methods and parameters.
*/

int colsPerLine = 5;
int maxLineNo = 20;
String gap = "\t\t";

LargeTable () {

// First print the headings System.out.println("\t\tTemperature Conversion Table");
System.out.println("\t\t============================");
System.out.println();

for (int col = 0; col < colsPerLine; col++)
System.out.print("C F" + 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 + " "); System.out.print(fahrenheit(c) + gap);
}
System.out.println();
}

// a simple conversion function
long fahrenheit(int celsius) {

return Math.round(celsius*9.0/5 + 32);
}

public static void main(String[] args) {

new LargeTable () ;
}
}


Результат :

Подсказка


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

Hosted by uCoz