5.Java输入-Scanner

1.导入Scanner包

类似C语言中的添加头文件

import java.util.Scanner;

2.定义

Scanner input=new Scanner(System.in);

3.输入基本数据类型

应该先检测输入的数据然后再处理

if(input.hasNextType()){
    Typt = input.nextType();
}else{
    ...
}

具体实例:

Scanner input=new Scanner(System.in);
		
System.out.print("输入一个整数:");
if(input.hasNextInt()) {
    int integer=input.nextInt();
    System.out.println(integer);
}else {
    System.out.println("输入的不是整数!");
}
		
System.out.print("输入一个单精度浮点数:");
if(input.hasNextFloat()) {
    float singlePrecision=input.nextFloat();
    System.out.println(singlePrecision);
}else {
    System.out.println("输入的不是单精度浮点数!");
}
		
System.out.print("输入一个双精度浮点数:");
if(input.hasNextDouble()) {
    double doublePrecision=input.nextDouble();
    System.out.println(doublePrecision);
}else {
    System.out.println("输入的不是双精度浮点数!");
}
		
System.out.print("输入一个字符:");
char character=input.next().charAt(0);  //取输入字符串的第一个字符
System.out.println(character);

执行结果:

1)如果输入的数据不正确,就自动填入下一个输入入口,直到符合数据类型的入口,如果没有符合的数据类型就结束输入

2)输入char类型数据时,就算在字符串前面打空格和换行也不会影响,程序直到读到字符时才会结束

4.String字符串的输入

1)nextLine();

2)next();

Scanner input=new Scanner(System.in);
String str1="";
String str2="";
		
System.out.print("输入字符串(nextLine()方式输入):");
if(input.hasNextLine()) {
    str1=input.nextLine();
}
		
System.out.print("输入字符串(next()方式输入):");
if(input.hasNext()) {
    str2=input.next();
}
		
System.out.println(str1);
System.out.println(str2);

执行结果:

next() 与 nextLine() 区别

next():

  • 1、一定要读取到有效字符后才可以结束输入。

  • 2、对输入有效字符之前遇到的空白,next() 方法会自动将其去掉。

  • 3、只有输入有效字符后才将其后面输入的空白作为分隔符或者结束符。

  • next() 不能得到带有空格的字符串。

nextLine():

  • 1、以Enter为结束符,也就是说 nextLine()方法返回的是输入回车之前的所有字符。

  • 2、可以获得空白。

改变上面代码中next()和nextLine()执行顺序:

Scanner input=new Scanner(System.in);
String str1="";
String str2="";
		
System.out.print("输入字符串(next()方式输入):");
if(input.hasNext()) {
    str1=input.next();
}
		
System.out.print("输入字符串(nextLine()方式输入):");
if(input.hasNextLine()) {
    str2=input.nextLine();
}	
		
System.out.println(str1);
System.out.println(str2);

执行结果:

这是什么原因呢

next读了前面的空格到hello的o字符,next发现字符o后面的空格就不读了,空格以及后面的字符串就自动给nextLine读了,nextLine又以换行结束,所以得出了这个结果

参考来源:Java Scanner类

猜你喜欢

转载自blog.csdn.net/qq_33757398/article/details/81517445