字符串参与运算:其实做的不是加法运算,而是做的字符串的拼接 (当常量在前要先运算在拼接)如:
int a = 10;int b = 20
System.out.println("hello" + a + b )===>>hello1020
int a = 10;int b = 20
System.out.println(a + b + "hello")===>>30hello
三元运算符:
关系表达式?表达式1:表达式2
A.执行流程:a.计算关系表达式的值,看是ture还是false
b.如果是ture,表达式1执行,如果是false,执行表达式2
如:class Dome2 { //比较三个数最大值
public static void main(String[] args) {
int a = 30;
int b = 40;
int c = 90;
int temp = (a<b)?b:a;
int max = (temp>c)?temp:c;
System.out.println("max = " + max);
}
}
键盘录入的基本步骤和使用:
键盘录入:
为了提高程序的灵活性,我们就把数据改进为键盘录入.
使用步骤:a.导包
import java.util.Scanner;
在一个类中顺序:package>import>class
b.创建键盘录入对象:
Scanner sc = new Scanner(System.in);
c.接收数据(调用Scannner对象)
int i = sc.nextInt();
例子:
import java.util.Scanner;
class Dome2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请键盘输入一个值");
int i= sc.nextInt();
System.out.println("i = " + i);
}
}
键盘录入两个值,求两个值的和:
例子: import java.util.Scanner;
class Dome2 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("请输入第一个值");
int a = sc.nextInt();
System.out.println("请输入二个值");
int b = sc.nextInt();
int sum = a + b ;
System.out.println("sum = " + sum);
}
}
/*import java.util.Scanner;
class Dome2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请键盘输入一个值");
int i= sc.nextInt();
System.out.println("i = " + i);
}
}
import java.util.Scanner;
class Dome2 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("请输入第一个值");
int a = sc.nextInt();
System.out.println("请输入二个值");
int b = sc.nextInt();
int sum = a + b ;
System.out.println("sum = " + sum);
}
}*/
Random:用于产生随机数,
使用步骤:
A.导包
import java.util.Random;
B.创建对象
Random r = new Random();
C.获取随机数
int number = r.nextInt(10);
获取数据的范围[0,10).包括0,不包括10
如何获取[0,10]之间的数?
int number = r.nextInt(100)+1
Random 练习猜数字小游戏:
分析:a.首先利用 Random 获取一个0-100之间的随机数字
b.然后键盘输入一个感觉能够猜中的数字
c.比较这两个数据,用if语句实现
1.当猜的数字比随机生成的数字大,提示猜的数字大了
1.当猜的数字比随机生成的数字大,提示猜的数字小了
1.当猜的数字与随机生成的数字相等,提示恭喜您猜中了
d.但是在竞猜过程中不太现实一次就能猜中,所以需要进行多次竞猜,利用while语句的死循环进行操作
例: import java.util.Random; //导包
public class RandomTest { //创建的类
public static void main(String[] args) {
//系统产生一个随机数字
Random r = new.Random();
//这个随机数字在0-100之间
int number = r.nextInt(100)+1;
while(true) { //多次猜数字
//键盘录入我们要猜的数据
Scanner sc = new Scanner(System.in);
System.out.println("请输入你要猜的数据(0-100):");
int a = sc.nextInt();
//判断输入的数据与产生的随机数字是否相等
if (a>number) {
System.out.println("你输入的数据" + a + "大了");
} else if (a<number) {
System.out.println("你输入的数据" + a + "小了");
} else {
System.out.println("恭喜你猜中了");
break;
}
}
}
}