- 用户交互
- 顺序结构
- 选择结构
- 循环结构
- break&& continue
- Excrise
用户交互Scanner
我们可以通过Scanner类来获取用户的输入
import java.util.Scanner;
基本语法: Scanner sc = new Scanner(System.in)
通过Scanner类的next()和nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据,但是两者又有所区别:
1. 使用hasNext()方式判断用户是否输入,使用next()来接受用户输入的内容
Scanner sc = new Scanner (System.in);
if(sc.hasNext()){
String str = new String(sc.next());
System.out.println("str"+str);
}
sc.close();
/* input: Hello World
* out: Hello
*/
2. 使用hasNextLine()方式判断用户是否输入,使用nextLine()来接受用户输入的内容
Scanner sc = new Scanner (System.in);
if(sc.hasNextLine()){
String str = new String(sc.nextLine());
System.out.println("str"+str);
}
sc.close();
/* input: Hello World
* out: Hello World
*/
结论:
next():
- 一定要读取到有效数字以后才开始结束输入
- 对输入有效字符之前遇到的空白,next()方法会自动将其去掉.
- 对只有输入有效字符后才浆其后面的输入的空白作为分隔符或者结束符
- next()不能得到带有空格的字符串
nextLine(): - 以Enter作为结束符,也就是说nextLine()方法返回的是输入回车之前的所有字符
- 也可以获得空白
使用scanner进行的一些计算:
package com.Scanner;
import java.util.Scanner;
public class demo03 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double sum=0;
int count=0;
System.out.println("请输入你要计算的数据,可以计算出数字的个数,平均数,总和;\n以非数字为终止;");
while (scanner.hasNextDouble()){
double x = scanner.nextDouble();
sum=sum+x;
count=count+1;
System.out.println("你输入的是第"+count+"个数字, 总和为: "+sum);
}
System.out.println("你共计输入了:"+count+"个数字;数字的总和是: "+sum+
";平均数字为:"+sum/count);
scanner.close();
}
}