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();
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();
}
}