我们可以通过Scanner来获取用户的输入
Scanner对象
-
基本语法:
Scanner s = new Scanner(System.in);
通过Scanner类的next()与nextLine()方法获取输入的字符串,在读取前我们一般需要使用hasNext()与hasNextLine()判断是否还有输入的数据。
Scanner scanner = new Scanner(System.in);//创建一个扫描器对象,用于接收键盘数据。 System.out.println("使用next方式接收:"); //判断用户有没有输入字符串 if (scanner.hasNext())//这里可以写成if (Scanner.hasNext()==true),不写==true也是对的,不写就是默认为true { //使用next方式接收 String str = scanner.next(); System.out.println("输入的内容为:"+str); } //用完Scanner之后就把它关闭 //凡是属于IO流的东西,用完就要把它关闭! //凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉 //IO流就是输入输出流(in out) scanner.close(); //运行,输入hello world,这时我们会发现,输入的是hello world,输出的是hello,没有world,是因为我们的用的是next方法 //下面我们用nextLine方法。
Scanner scanner = new Scanner(System.in);//创建一个扫描器对象,用于接收键盘数据。 System.out.println("使用nextLine方式接收:"); //判断用户有没有输入字符串 if (scanner.hasNextLine())//这里变成了nextLine { //使用nextLine方式接收 String str = scanner.nextLine();//这里变成了nextLine System.out.println("输入的内容为:" + str); } scanner.close(); //然后我们输入hello world发现,hello 和world完整输入输出,说明扫描器把hello world两个对象都接收到了
原因: next(); 1.以空格为结束符。 2.一定要读取到有效字符后才可以结束输入。 3.对输入有效字符之前遇到的空白,next()方法会自动将其去掉。 4.只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。 5.next()不能的到带有空格的字符串。
nextLine(); 1.以Enter为结束符。也就是说,nextLine()方法返回的是输入回车之前的所有字符。 2.可以获得空白。
凡是属于IO流的类如果不关闭会一直占用资源,要养成好习惯用完就关掉
Scanner 进阶使用
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("输入的不是小数数据!"); } scanner.close();