实训第五课上-常用工具、转换、三元运算
星期二
常用工具类
-
random:生成一个Int随机数
取值范围:(2^31)-1 ~ (-2^31)
调用方法: import java. util.Random
举个栗子:
import java. util.Random//导包 util类中的Random
public class 文件名{
public static void main(String [] ages){
Random r = new Random)():
int num = r.nextInt();// ( ) 中可以输入数字,随机会在n-1值内
System.out.print(num);}
}
拓展:已知结果取值在0-4,问:如何输出为1-5
import java. util.Random
public class 文件名{
public static void main(String [] ages){
Random r = new Random)():
int num = r.nextInt(5)
System.out.print(num);}
}
答:int num = r.nextInt(5)+1
.
-
Math:生成一个Double随机数
Double的取值范围:0.0~1.0之间的小数
public class 文件名{
public static void main(String [] ages){
Random r = Math.random)():
int num = r.nextInt()
System.out.print(r);}
}
拓展:已知下面代码可以输出0.0-1.0之间的小数,问:怎么样才可以输出0-9和1-3
public class 文件名{
public static void main(String [] ages){
Random r = Math.random)():
int num = r.nextInt()
System.out.print(r);}
}
答1:Random r = (int)(Math.random)()*10)??/0-9
答2:Random r = (int)(Math.random)()*3)+1;//1-3
.
拓展2:已知下面代码可以四舍五入输出2.0,问:怎么样才可以输出为2.2
public class new1{
public static void main(String [] args){
double a = Math.round(2.15);
System.out.print(a);
}
}答:
-
自动转换:
-
类型相互兼容
-
目标类型比原类型大
-
举个栗子:
int c = 123;
double a = c;
System.out.print(a);//123.0
-
-
-
强制转换:
-
类型相互兼容
-
原类型比目标类型大
-
举个栗子:
int c = 123;
byte a = (byte)c;
System.out.print(a);//123
-
-
三元运算符
- ? : (a > 0) ? 1 : 2;
- 成立则输出?后的值,否则输出:后的值