convert.java
来自「Java 入门书的源码」· Java 代码 · 共 83 行
JAVA
83 行
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.
/* Tests the structure of the program
* to convert length using a menu to
* get the user's choice. Uses stubs
* for the actual conversion methods.
*/
import iopack.Io;
public class Convert {
public static void MetricToEnglish() {
double meters; // number of meters to convert
double toYards; // meters converted to yards
int yards; // integer part of toYards
double excessYards; // fractional part of toYards
double toFeet; // excessYards converted to feet
int feet; // integer part of toFeet
double excessFeet; // fractional part of toFeet
float toInches; // excessFeet converted to inches
meters = Io.readDouble("Enter the number of meters to convert");
toYards = meters / .9144;
yards = (int)Math.floor(toYards);
excessYards = toYards - yards;
toFeet = 3 * excessYards;
feet = (int)Math.floor(toFeet);
excessFeet = toFeet - feet;
toInches = (float)(12 * excessFeet);
if (meters <= 1)
System.out.println(meters+ " meter converts to");
else
System.out.println(meters+ " meters convert to");
System.out.print('\t');
if (yards > 0)
if (yards <= 1) System.out.print(yards + " yard ");
else System.out.print(yards + " yards ");
if (feet > 0)
if (feet <= 1) System.out.print(feet + " foot ");
else System.out.print(feet + " feet ");
if (toInches > 0)
if (toInches <= 1) System.out.println(toInches + " inch");
else System.out.println(toInches + " inches");
if (yards == 0 && feet == 0 && toInches == 0)
System.out.println(0 + " yards");
}
public static void EnglishToMetric() {
double yards, feet, inches; // amount to convert
double total; // input converted to inches
float meters; // converted amount
yards = Io.readDouble("Enter yards");
feet = Io.readDouble("Enter feet");
inches = Io.readDouble("Enter inches");
total = 36*yards + 12*feet + inches;
meters = (float)(.0254*total);
if (meters <= 1)
System.out.println("Your input converts to " + meters + " meter");
else
System.out.println("Your input converts to " + meters + " meters");
}
public static void main(String [] args) {
int choice;
do {
System.out.println();
System.out.println("Choose from the following list");
System.out.println("1. Convert from meters to yds,ft,in");
System.out.println("2. Convert from yds,ft,in to meters");
System.out.println("3. Quit");
choice = Io.readInt("Enter your choice, 1, 2 or 3");
switch (choice) {
case 1:
MetricToEnglish();
break;
case 2:
EnglishToMetric();
break;
case 3: System.out.println("Bye, Have a nice day");
}
} while (choice != 3);
Io.readString("Press any key to exit"); // Added for IDE use
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?