Scanner

示例

1

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);
}
scanner.close();
//使用next方式接收
//hello word
//输出的数据为:hello
//nextLine可以接收一个字符串的数据

}

}

2
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=scanner.nextLine();
System.out.println("输出的数据为:"+str);
}
scanner.close();
//使用nextLine方式接收
//hello word
//输出的数据为:hello word
//nextLine可以接收一行的数据
}
}

3
import java.util.Scanner;

public class Demo03 {
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("不是小数数据!");
}
}
}

4
import java.util.Scanner;

public class Demo04 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double sum=0;
int m=0;
while (scanner.hasNextDouble()){
Double x=scanner.nextDouble();
m++;
sum+=x;
}
System.out.println("个数的和为:"+sum);
System.out.println("个数的平均值为:"+(sum/m));
scanner.close();
}
}
posted @ 2023-02-02 17:21  惊鸿宴远赴人间  阅读(68)  评论(0)    收藏  举报