一、Scanner对象
Scanner类来获取用户的输入
- 通过Scanner类的next()和nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据
next():
- 一定要读取到有效字符后才可以结束输入
- 对输入有效字符之前遇到的空白,next()方法会自动将其去掉
- 只有输入有效字符后才将其后面输入的空白作为分隔符或结束符
- next()不能得到带有空格的字符串
java
public class Demo {
public static void main(String[] args) {
// 创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
// 判断用户有没有输入字符串
if (scanner.hasNext()) {
// 使用next方式接收
String str = scanner.next(); // 程序会等待用户输入完毕
System.out.println("输出的内容为:" + str);
}
// 凡是属于IO流的类,如果不关闭会一直占用资源
scanner.close();
}
}
nextLine():
- 以Enter为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符
- 可以获得空白
方法一:
java
public class Demo2 {
public static void main(String[] args) {
// 创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方式接收:");
// 判断用户有没有输入字符串
if (scanner.hasNextLine()) {
// 使用next方式接收
String str = scanner.nextLine(); // 程序会等待用户输入完毕
System.out.println("输出的内容为:" + str);
}
// 凡是属于IO流的类,如果不关闭会一直占用资源
scanner.close();
}
}
方法二:
java
public class Demo2 {
public static void main(String[] args) {
// 创建一个扫描器对象,用于接收键盘数据
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数据:");
// 使用next方式接收
String str = scanner.nextLine(); // 程序会等待用户输入完毕
System.out.println("输出的内容为:" + str);
// 凡是属于IO流的类,如果不关闭会一直占用资源
scanner.close();
}
}
二、选择结构
java
if
if...else
if...else if ...else if
public class SwitchDemo {
public static void main(String[] args) {
// case 穿透
char grade = 'C';
switch (grade) {
case 'A':
System.out.println("优秀");
break;
case 'B':
System.out.println("良好");
break;
case 'C':
System.out.println("及格");
break;
case 'D':
System.out.println("再接再厉");
break;
case 'E':
System.out.println("挂科");
break;
default:
System.out.println("未知");
}
}
}
三、循环结构
while 循环
java
public class WhileDemo {
public static void main(String[] args) {
int i = 0;
while (i<100) {
i++;
System.out.println(i);
}
}
}
do...while 循环
java
public class DoWhileDemo {
public static void main(String[] args) {
int i = 0;
int sum = 0;
do {
sum = sum + i;
i++;
} while (i<=100);
System.out.print(sum);
}
}
while和do...while的区别
java
public class DoWhileDemo {
public static void main(String[] args) {
int i = 0;
while (i<0) {
System.out.println(i);
i++;
}
System.out.println("==================");
do {
System.out.println(i);
i++;
}while (i<0);
}
}
for 循环
打印九九乘法表
java
public class ForDemo {
public static void main(String[] args) {
for (int i = 1; i <= 9; i++) {
for (int x =1; x <= i; x++) {
System.out.print(i+"*"+ x +"="+ i*x + "\t");
}
System.out.println();
}
}
}
增强 for 循环
java
public class ForDemo1 {
public static void main(String[] args) {
int[] list = {1,2,3,4,5};
for(int x:list) {
System.out.println(x);
}
}
}
打印三角形
java
public class ForDemo {
public static void main(String[] args) {
for (int i = 0; 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();
}
}
}