将较长的数据类型转换成较短的数据类型,只能用强制类型转换。形如:
short s;
Byte b = (byte)s;
7种类型的顺序排列如下:
byte < (short = char) < int < long < float < double
其中,short和char之间也必须强制转换。
这是一个简单的强制类型转换实例:
package Example;
import java.util.Scanner;
public class rant_2_4 {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);//创建一个Scanner对象接受键盘输入
System.out.print("Please input yearly interest rate,for example 8.25");
double annualrate = input.nextDouble();
double monthlyrate = annualrate/12;
double annualment,monthlyment;
annualment = (int)annualrate*100/100.0;
monthlyment = (int)monthlyrate*100/100.0;
System.out.println("The annualment is "+annualment);
System.out.println("The monthlyment is "+monthlyment);
}
}
运行结果:
Please input yearly interest rate,for example 8.2545
The annualment is 45.0
The monthlyment is 3.0
原文:https://www.cnblogs.com/Alic5/p/14423036.html