Scanner基础
Scanner对象
可以通过Scanner类来获取用户的输入
基本语法:
Scanner sc= new Scanner(System.in);
next()与nextline()有何不同?
![]()
使用nextLine()方法时,不将空格看做是两个字符串的间隔,而是看作字符串的一部分,返回时,空格也作为String类型一并返回
使用next()方法时,将空格看作是两个字符串的间隔,截断字符串并返回
去代码里看看
package com.vis_yang.base;
import java.util.Scanner;
//学习new一个Scanner对象实现简单的交互
public class Demo {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
Scanner sc =new Scanner(System.in);
System.out.println("使用next方式接收:");
//判断用户有没有输入字符串
if (sc.hasNext()){
String str =sc.next();
System.out.println("输出内容为:"+str);
}
//凡是属于io流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
sc.close();
}
} 运行结果:
使用next方式接收:
hello world
输出内容为:hello
package com.vis_yang.base;
import java.util.Scanner;
public class Demo01 {
public static void main(String[] args) {
//创建一个扫描器对象,用于接收键盘数据
Scanner sc=new Scanner(System.in);
System.out.println("使用nextline方式接收:");
//判断用户有没有输入字符串
if (sc.hasNextLine()){
String str=sc.nextLine();
System.out.println("输出内容为:"+str);
}
//凡是属于io流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
sc.close();
}
} 运行结果:
使用nextline方式接收:
hello world
输出内容为:hello world
为啥输出到一半就没撩?😏
不使用if
package com.vis_yang.base;
import java.util.Scanner;
//除去if判断也可以用
public class Demo02 {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("请输入你想输入的内容:");
String str=sc.nextLine();//nextline常用
System.out.println(str);
}
} 运行结果:
请输入你想输入的内容:
你好 我是Vis.Yang
你好 我是Vis.Yang
Scanner进阶
尝试实现:
输入多个数字,并求其总和与平均数,每输入一个数字用回车确认,通过输入非数字来结束输入并输出执行结果

京公网安备 11010502036488号