注意区分Scanner类中的获取输入字符串的两种方法:
next() 和 nextLine()
next() | nextLine() |
---|---|
一定要读取到有效字符后才可以结束输入 | 以Enter回车键作为结束符 |
有效字符前的空格会自动忽略 | 返回输入回车之前的所有字符 |
有效字符后的空格会被作为结束符 | 可以获得空白字符串 |
综上,next()不能得到带有空格的字符串 | 综上,nextLine()可以得到有空格的字符串 |
- 使用next()
import java.util.Scanner;
public class Demo1 {
public static void main(String[] args) {
//创建一个Scanner类的对象,准备从键盘接收数据
Scanner scanner = new Scanner(System.in);
System.out.println("使用next方式接收:");
if (scanner.hasNext()) {
//scanner.hasNext() 判断用户是否还有输入
String str=scanner.next(); //如果还有输入,通过scanner.next()接收用户的输入
String str=scanner.next();
System.out.println("输出内容:"+str);
}
scanner.close();//属于I/O流的类,使用结束后及时关闭,否则将一直占用资源
}
}
示例:
- 使用nextLine()
import java.util.Scanner;
public class Demo2 {
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()进行字符串的获取,写法如下:
import java.util.Scanner;
public class Demo3 {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str=scanner.nextLine();
//接收用户输入,直至敲下回车结束,将输入保存为字符串
System.out.println("输出的内容:"+str);
scanner.close();
}
}