Java基础--Scanner类
Scanner类:
Java5: java.util.Scanner包
基础语法:Scanner s = new Scanner(System.in);
package Scanner;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方法接收:");
if (scanner.hasNext()){
String str = scanner.next();
System.out.println("输入的内容为:" + str);
}
// 凡是属于IO流的类,如果不关闭会一直占用资源,养成良好的习惯。
scanner.close();
}
}
package Scanner;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("使用nextLine方法接收:");
if (scanner.hasNextLine()){
String str = new String();
str = scanner.nextLine();
System.out.println("输入的内容为:" + str);
}
scanner.close();
}
}
package Scanner;
import java.util.Scanner;
public class Demo04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int i = 0;
float f = 0.0f;
System.out.println("请输入整数:");
if(scanner.hasNextInt()){
i = scanner.nextInt();
System.out.println("整数数据:"+i);
}else{
System.out.println("输入的不是整数数据。");
}
System.out.println("请输入小数:");
if(scanner.hasNextFloat()){
f = scanner.nextFloat();
System.out.println("小数数据:"+f);
}else{
System.out.println("输入的不是浮点数据。");
}
}
}
package Scanner;
import java.util.Scanner;
public class Demo05 {
public static void main(String[] args) {
// 输入多个数字,求和和平均数
Scanner scanner = new Scanner(System.in);
double sum = 0;
int n = 0;
while(scanner.hasNextDouble()){
double x = scanner.nextDouble();
n++;
sum += x;
}
System.out.println("总和:"+ sum);
System.out.println("平均数:"+ (sum /n));
System.out.println();
scanner.close();
}
}