1.用户交互scanner
通过java.util.Scanner类来获取用户的输入。
- 基本语法
Scanner s = new Scanner(System.in);
- 通过Scanner类的 next() 与 nextLine() 方法获取输入的字符串,在读取前一般需要使用 hasNext() 与 hasNextLine() 来判断是否还有输入的数据。next()和nextLine()的区别在于前者不能得到带有空格的字符串,而后者可以输出空格,因此用的多些。
**示例:**输入多个数字,并求其总和与平均值,每输入一个数字用回车确认,通过输入非数字来结束输入并输出结果。
public class Demo03 {
public static void main(String[] args) {
double sum = 0.0;
int count = 0;
Scanner scanner = new Scanner(System.in);
System.out.println("输入数字:");
while(scanner.hasNextDouble()){
double x = scanner.nextDouble();
count = count + 1;
sum = sum + x;
System.out.println("输入的第" + count + "个数字:" + x);
}
scanner.close();
System.out.println("和:" + sum);
System.out.println("均值:" + sum / count);
}
}
2.switch选择结构
public class SwitchDemo {
public static void main(String[] args) {
char grade = ' ';
switch (grade){
case 'a':
System.out.println("优秀");
break;
case 'b':
System.out.println("良好");
break;
case 'd':
System.out.println("及格");
break;
default:
System.out.println("未知等级");
}
}
}
3.while 和 do-while循环
while是先判断后执行,do-while是先执行后判断。
public class DowhileDemo {
public static void main(String[] args) {
//计算0-100的和
int sum = 0;
int i = 0;
do {
sum = sum + i;
i++;
}while (i <= 100);
System.out.println(sum); //5050
}
}
4.for循环
package com.zq.struct;
public class ForDemo {
public static void main(String[] args) {
//输出1-1000能被5整除的数,且每行输出3个
for (int i=1; i<=1000; i++){
if (i%5==0){
System.out.print(i + "\t");
}
if (i%15==0){
System.out.println();
//System.out.print("\n");
}
}
}
}
print输出完不会换行,println输出完会换行。
打印九九乘法表:
11=1
12=2 22=4
13=3 23=6 33=9
14=4 24=8 34=12 44=16
15=5 25=10 35=15 45=20 55=25
16=6 26=12 36=18 46=24 56=30 66=36
17=7 27=14 37=21 47=28 57=35 67=42 77=49
18=8 28=16 38=24 48=32 58=40 68=48 78=56 88=64
19=9 29=18 39=27 49=36 59=45 69=54 79=63 89=72 9*9=81
public class ForDemo01 {
public static void main(String[] args) {
//打印九九乘法表
for (int i=1; i<=9; i++){
for (int j=1; j<=i; j++){
System.out.print(j + "*" + i + "=" + (i*j) + "\t");
}
System.out.println();
}
}
}
5.增强for循环
public class ForDemo02 {
public static void main(String[] args) {
int [] numbers = {10, 20, 30, 40, 50};
for (int x: numbers){
System.out.println(x);
}
}
}
6.练习:打印三角形
public class TestDemo01 {
public static void main(String[] args) {
for (int i=1; i<=5; i++){
for (int j=5; j>=i; j--){
System.out.print(" ");
}
for (int j=1; j<=i; j++){
System.out.print("*");
}
for (int j=1; j<i; j++){
System.out.print("*");
}
System.out.println();
}
}
}
输出:
*
***
*****
*******
*********