目录
1.用户交互Scanner
可以通过Scanner类来获取用户的输入。
基本语法:
Scanner s = new Scanner(System.in);
通过Sacnner类的next()与nextLine()方法获取输入的字符串,在读取前一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。
public class ScannerStudy {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
/*
next():
1.一定要读到有效字符后才可以结束(按回车键 也会一直等待输入)
2.对输入有效字符之前的空白next()会自动将其去掉
3.只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符
4.next()只能得到有效字符之后 第一个空格之前的内容 eg: hello word 只能输出hello
nextLine():
1.以Enter为结束符 nextLine()返回输入回车之前的所有字符包括空格
2.可以获得空格
*/
// System.out.println("========使用next()方式获取========");
// //判断用户有没有输入字符串
// if(scanner.hasNext()){
// String s = scanner.next();
// System.out.println(s);
// }
System.out.println("========使用nextLine()方式获取========");
//判断用户有没有输入字符串
if(scanner.hasNextLine()){
String s = scanner.nextLine();
System.out.println(s);
}
//凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯 用完就关掉
scanner.close();
}
}
利用Scanner编写一个简单的求和算法实例:
public class Scanner_test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Double num = 0D;
int m = 0;
//hasNextDouble()判断输入是否为double类型数据 不是则跳出循环(终止求和算法)
while (scanner.hasNextDouble()){
Double a = scanner.nextDouble();
m++;
num += a;
System.out.println("输入了"+m +"个数据,和为"+num);
}
scanner.close();
}
}
结果:
1.5
输入了1个数据,和为1.5
2.5
输入了2个数据,和为4.0
5.5
输入了3个数据,和为9.5
0.5
输入了4个数据,和为10.0
x
2.顺序结构
自上而下顺序执行。
3.选择结构
3.1 if单选择结构 if(){}
3.2 if双选择结构 if(){}esle{}
3.3 if多选择结构 if(){}else if()......else{}
3.4 switch多选择结构
public class Switch_test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入编码判断性别:");
while(scanner.hasNextInt()){
int f = scanner.nextInt();
switch(f){
case 1:
System.out.println("1对应男生");
break;
case 2:
System.out.println("2对应女生");
break;
default:
System.out.println("请输入正确内容");
}
}
}
}
结果:
请输入编码判断性别:
1
1对应男生
2
2对应女生
3
请输入正确内容
x
4.循环结构
4.1 while循环结构 while(布尔表达式)
4.2 do...while循环结构
do{ }while(布尔表达式) 保证循环体至少执行一次(先执行一次在判断)
4.3 for循环
利用for循环打印九九乘法表:
public class For_test {
public static void main(String[] args) {
for (int i = 1; i <=9; i++) {
for (int j = 1; i <= j ; j++) {
int sum = i*j;
System.out.print(i+"*"+j + "=" + sum+"\t");
}
System.out.println();
}
}
}
结果:
1*1=1
2*1=2 2*2=4
3*1=3 3*2=6 3*3=9
4*1=4 4*2=8 4*3=12 4*4=16
5*1=5 5*2=10 5*3=15 5*4=20 5*5=25
6*1=6 6*2=12 6*3=18 6*4=24 6*5=30 6*6=36
7*1=7 7*2=14 7*3=21 7*4=28 7*5=35 7*6=42 7*7=49
8*1=8 8*2=16 8*3=24 8*4=32 8*5=40 8*6=48 8*7=56 8*8=64
9*1=9 9*2=18 9*3=27 9*4=36 9*5=45 9*6=54 9*7=63 9*8=72 9*9=81
5.break、continue
break:跳出整个循环体
continue:结束本次循环,进入下一次循环