用户交互Scanner
public static void main(String[] args) {
//创建一个扫描对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
//使用next方法输入 只会输入空格之前的内容
String str0 = scanner.next();//hello world
System.out.println("使用next输入"+str0);// hello
//使用nextline方法输入,会输入回车之前的内容
String str1 = scanner.nextLine();//hello world
System.out.println("使用nextline输入"+str1);//hello world
scanner.close();
- 这两种方法中还包括具体的数据类型(int、byte…)
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//求输入的多个数据的的平均值,数据之间以回车隔开
double sum = 0;
int m = 0;
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();//double 类型
sum = sum + x;
m++;
System.out.println("当前和为:"+sum);
System.out.println("当前个数为:"+m);
System.out.println("当前平均数为:"+sum/m);
}
scanner.close();
If分支结构
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入成绩:");
int score = scanner.nextInt();
if(score==100){
System.out.println("满分");
}else if(score<100 && score>=80){
System.out.println("优秀");
}else if(score<80 && score>=70){
System.out.println("良好");
}else if(score<70 && score>=60){
System.out.println("及格");
}else {
System.out.println("不及格");
}
scanner.close();
}
switch分支
- switch case判断一个变量与一系列值中的某个值是否相等
- 从Java SE 7开始支持字符串类型匹配
- case必须为字符常量或字面量
- break使用时,如果某一分支结束不添加break,会发生穿透现象,添加则推出循环
- continue使用时,添加continue推出某一次循环,跳过某种状态
- 使用字符串时,本质上还是使用的数字,具体可以通过反编译验证
public static void main(String[] args) {
char grade = 'C';
//case穿透,switch 匹配一个具体的值
switch (grade){
case 'A':
System.out.println("A");
break;
case 'B':
System.out.println("B");
break;
case 'C':
System.out.println("C");
break;
}
//switch 从7之后支持string类型
//反编译 将class文件复制到IDEA的java文件夹中打开,可以看到 字符串匹配时采用的是hashcode 还是数字
}
While 、Do While
- while时先判断,再执行
- do while 是先执行再判断
- 若判断条件永远为ture,则为死循环
public static void main(String[] args) {
int a = 4;
int b = 4;
while (a<4){
a++;
System.out.println(a);
}//空
System.out.println("===================================");
do{
b++;
System.out.println(b);
}while (b<4);//4
}
For循环
- 最先执行变量初始化,然后判断布尔值,最后更新变量
- 三个参数都可省略`for( ; ; )为死循环
- 用法灵活多样
- 给出一个输出乘法表格的例子:
public static void main(String[] args) {
// 打印九九乘法表
for (int j = 1; j <=9; j++) {
for (int i = 1; i <=j; i++) {
System.out.print(i+"*"+j+"="+(i*j)+'t');
}
System.out.println();
}
}
public static void main(String[] args) {
//打印三角形
for(int i=1;i<=5;i++){
for(int j=5;j>=i;j--){
System.out.print(" "+'t');
}
for(int j=1;j<=i;j++){
System.out.print("*"+'t');
}
for(int j=1;j