java.Scanner类(next&nextLine)

mac2022-06-30  96

创建对象格式

Scanner scan = new Scanner(System.in)

next方法

next(): 1、一定要读取到有效字符后才可以结束输入 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符 next() 不能得到带有空格的字符串

nextLine方法

1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符 2、可以获得空白

next&nextLine Demo

//导入Scanner类 import java.util.Scanner; public class ScannerDemo {      public static void main(String[] args) {          //从键盘接收数据          Scanner scan = new Scanner(System.in);                    //next方式接收字符串          System.out.println("输入方式:next +回车 + nextLine"); // System.out.println("输入方式:next +空格 + nextLine"); System.out.println("请输入:");              //声明接收对象的类型          String str = scan.next();                    //打印结果          System.out.println("str输入的数据为:"+ str); //声明接收对象的类型          String str1 = scan.nextLine();                  //打印结果          System.out.println("str1输入的数据为:"+ str1);      } }
输出结果1
输入方式:next +回车 + nextLine 请输入: next str输入的数据为:next str1输入的数据:
解析
1.有效字符之前的空白会自动去掉;所以前面的四个空格不会输出 2.输入有效字符将其后面的空白作为分隔符或者结束符;java前面的空格是表示结束,所以不会输出java 3.本来是想next后接回车输入nextLine的数据,但是“nextLine()方法返回的是输入回车之前的所有字符”,所以输出回车之后整个程序就结束的,相当于没有输入nextLine的数据
输出结果2
输入方式:next +空格 + nextLine 请输入: next nextLine str输入的数据为:next str1输入的数据: nextLine
解析
1.nextLine()方法返回的是输入回车之前的所有字符; 在第一个数据之后接空格第二个数据之后接回车,这样两个数据就都录入了

转载于:https://www.cnblogs.com/youngleesin/p/11494782.html

最新回复(0)