Scanner类
导包:java.util
创建对象:Scanner input =new Scanner(System.in);
使用: int value = input.nextInt();
String value = input.nextLine();
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import java.util.Scanner;
public class Main { public static void main(String[] args) { String name; int password;
Scanner input = new Scanner(System.in); System.out.println("请输入账号:"); name = input.nextLine(); System.out.println("请输入密码:"); password = input.nextInt(); System.out.println("输入的账号为:"+name); System.out.println("输入的密码为:"+password); } }
结果为: 请输入账号: liufanghan 请输入密码: 123 输入的账号为:liufanghan 输入的密码为:123
先输入密码,再输入账号时:
结果: 请输入密码: 123 请输入账号: 输入的账号为: 输入的密码为:123
|
运行结果显示在输入时不会等待用户输入账号直接执行下面的代码
方法特性
nextLine方法会以回车符作为截止,将回车符连同之前的所有字符都读取出来,将回车符扔掉,通过new String()的方法把之前的所有字符组合成一个完整的字符串交还给我们
nextInt方法会以回车符作为截止,但它只会读取回车符之外的所有字符,回车符留在队列中,先读出来,读取之后先判断是不是数字,是的话按字符串读出来之后再转换为数字,即”123”—》123
nextFloat、nextDouble、nextByte与nextInt工作机制一样
next方法看到回车或者空格都认为结束,nextLine只认为回车符结束
next—>String nextLine—>String
解决方法
1.多加一行nextLine方法读出回车符,清除消息队列中的回车符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import java.util.Scanner;
public class Main { public static void main(String[] args) { String name; int password;
Scanner input = new Scanner(System.in); System.out.println("请输入密码:"); password = input.nextInt(); input.nextLine(); System.out.println("请输入账号:"); name = input.nextLine();
System.out.println("输入的账号为:"+name); System.out.println("输入的密码为:"+password); } }
结果: 请输入密码: 123 请输入账号: liufanghan 输入的账号为:liufanghan 输入的密码为:123
|
2.使用next方法读取字符串,next方法读取方式与nextInt一致,不读取回车符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import java.util.Scanner;
public class Main { public static void main(String[] args) { String name; int password;
Scanner input = new Scanner(System.in); System.out.println("请输入密码:"); password = input.nextInt();
System.out.println("请输入账号:"); name = input.next();
System.out.println("输入的账号为:"+name); System.out.println("输入的密码为:"+password); } }
结果: 请输入密码: 456 请输入账号: liufanghan 输入的账号为:liufanghan 输入的密码为:456
|
3.将账号和密码都统一用nextLine来读
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import java.util.Scanner;
public class Main { public static void main(String[] args) { String name; int password;
Scanner input = new Scanner(System.in); System.out.println("请输入密码:");
password = Integer.parseInt(input.nextLine()); System.out.println("请输入账号:"); name = input.nextLine();
System.out.println("输入的账号为:"+name); System.out.println("输入的密码为:"+password); } }
结果: 请输入密码: 789 请输入账号: LFH 输入的账号为:LFH 输入的密码为:789
|
int–>String
int+””====String
基本类型和引用类型相连接结果为引用类型
1 2 3 4
| System.out.println(5+5+"5"+5+5);
结果: 10555
|