Java获取键盘输入(使用Scanner类获取键盘输入) |
您所在的位置:网站首页 › java怎么从键盘输入多个数据 › Java获取键盘输入(使用Scanner类获取键盘输入) |
部分来自《疯狂Java讲义》(第二版) Scanner是一个基于正则表达式的文本扫描器,它可以从文件、数据流、字符串中解析出基本类型值和字符串值。 Scanner主要提供两个方法来扫描输入: (1)nextXxx():获取下一个输入项。(其中Xxx可以是Int、Long等代表基本数据类型的字符串)nextInt() 、nextFloat、nextLine、next等等 【例 1】从键盘获取用户输入的一个整数(int型) //sc.nextInt(); Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) int num = sc.nextInt();//获取输入的一个整数(只接受int型,如何输入其他类型将报错) System.out.println(num); 【例 2】获取一系列的输入(使用Scanner可以输入不同的类型) // sc.nextLine(); 和 sc.nextInt(); 和sc.nextFloat(); Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) System.out.println("请输入你的姓名:"); String name = sc.nextLine(); System.out.println("请输入你的年龄:"); int age = sc.nextInt(); System.out.println("请输入你的工资:"); float salary = sc.nextFloat(); System.out.println("姓名:"+name+" 年龄:"+age+" 工资:"+salary);【例 3】Scanner中next()和nextLine()的区别 Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) System.out.println("请输入第一个字符串"); String s1 = sc.nextLine(); System.out.println("你输入的内容为:"+s1+"\n"); System.out.println("请输入第二个字符串"); String s2 = sc.next(); System.out.println("你输入的内容为:"+s2);运行效果: 如何改成: Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) System.out.println("请输入第一个字符串"); String s1 = sc.next(); System.out.println("你输入的内容为:"+s1+"\n"); System.out.println("请输入第二个字符串"); String s2 = sc.nextLine(); System.out.println("你输入的内容为:"+s2);当用户输入完第一个字符串之后,程序就已经停止了,也即不能再录入第二个字符串了!!! (2)hasNextXxx():是否还有下一个输入项。如果只是判断是否包含下一个字符串,则直接使用haxNext()【例 1】不断从键盘读取输入内容,并将每次读入的内容直接打印出来 Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) //sc.hasNext():用来判断是否包含下一个字符串 while(sc.hasNext()) { System.out.println("输入的内容是:"+sc.next()); }运行效果: 如果希望改变Scanner的分隔符(不使用空格作为分隔符): 为Scanner设置分隔符使用useDelimiter(String pattern)即可,该方法的参数是一个正则表达式。 例如:每次读入一行,不管这一行中是否包含空格,Scanner都把它当作一个输入项。在这种需求下,我们可以把Scanner的分隔符设置成回车符(\n),不再使用默认的空白作为分隔符。 Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) //只把回车作为分隔符(即:不管这一行中是否包含空格,Scanner都将它看成一个输入项) sc.useDelimiter("\n"); String str = sc.next(); System.out.println("str="+str);运行效果: 【例1】连续输入两个整形数字,并输出他们的和 Scanner sc = new Scanner(System.in);//System.in代表标准输入(即键盘输入) Integer a = sc.nextInt();//默认以空格作为分隔符 Integer b = sc.nextInt(); System.out.println(a+b);运行效果: 【例2】分别输入一个字符和一个整数,并输出 Scanner sc = new Scanner(System.in); char ch = sc.next().charAt(0);//获取用户输入的字符 Integer a = sc.nextInt(); //获取用户输入的整数 System.out.println("ch="+ch+" a="+a); |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |