用next方法接收
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.print("输出内容为:"+str);
}
scanner.close();
}
}
用nextLine方法接收
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.print(str);
}
scanner.close();
}
}
Scanner进阶
public class Demo03 {
public static void main(String[] args) {
int num = 0;
double d = 0;
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextDouble()){
d += scanner.nextDouble();
num++;
System.out.println("你输入第"+num+"个数据,当前和为:"+d);
}
System.out.print(num+"个数的平均值为:"+d/num);
scanner.close();
}
}