Scanner

 

Scanner对象

常用nextLine()

 

 

 

通过Scanner类的next()与nextLine()的方法获取字符串,在读取前用hasNext()或hasNextLine判断是否还有输入数据

next方式
 1 package com.stx.zx;
 2 
 3 import java.util.Scanner;
 4 
 5 public class w3 {
 6     public static void main(String[] args) {
 7         Scanner scanner = new Scanner(System.in);  //创建扫描器对象,用于接收键盘数据
 8         //输入new Scanner(System.in) 快捷键Alt+enter自动补全
 9         System.out.println("使用next方式接收:");
10 
11         if (scanner.hasNext()==true){    //判断用户有没有输入字符串
12             //==true可省略,省略后默认为true
13             String str=scanner.next();  //用next的方式接收
14             //String是类,后写字符串
15             System.out.println("输入的内容为:"+str);  //输出str字符串
16 
17             scanner.close();   //关闭scanner
18 
19         }
20     }
21     }
22           /*主要语句:Scanner scanner = new Scanner(System.in);
23                       scanner.close();*/

 

nextLine方式
 1 package com.stx.zx;
 2 
 3 import java.util.Scanner;
 4 
 5 public class w4 {
 6     public static void main(String[] args) {
 7         Scanner lsb = new Scanner(System.in);
 8         System.out.println("用nextLine方式输入:");
 9 
10         if (lsb.hasNextLine()){
11             String dd=lsb.nextLine();
12             System.out.println("输出的内容为:"+dd);
13         }
14         lsb.close();
15     }
16 }

 

 


 1 package com.stx.zx;
 2 
 3 import java.util.Scanner;
 4 
 5 public class w5 {
 6     public static void main ( String[] args ) {
 7         Scanner lss = new Scanner(System.in);
 8         int i = 0;
 9         float f = 1.1f;
10         String m;
11         System.out.println("请输入:");
12         if (lss.hasNextInt()) {
13             i=lss.nextInt();
14             System.out.println("整数数据:"+i);
15         }else if (lss.hasNextFloat()){
16             f=lss.nextFloat();
17             System.out.println("小数数据:"+f);
18         }else if (lss.hasNextLine()){
19             m=lss.nextLine();
20             System.out.println("字符串:"+m);
21         }
22         }
23 }

 



 

posted @ 2022-02-23 16:34  VVMgAI  阅读(165)  评论(0)    收藏  举报