使用Scanner读取数据
System.out.println("") 用于向控制台输出数据。
我们还需要从控制台输入数据,所以需要用到Scanner类。
步骤 1 : 使用Scanner读取整数
注意: 使用Scanner类,需要在最前面加上
import java.util.Scanner;
表示导入这个类,才能够正常使用
![f65cbc4338685a457523fcde60fb8c0a.png](https://i-blog.csdnimg.cn/blog_migrate/a88cd9ddd3de7571d2dc0c060c3d8c42.jpeg)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int a = s.nextInt();
System.out.println("第一个整数:"+a);
int b = s.nextInt();
System.out.println("第二个整数:"+b);
}
}
步骤 2 : 使用Scanner读取浮点数
![01eeef32d6d9f09b622785ba36b26a03.png](https://i-blog.csdnimg.cn/blog_migrate/9c18bc275f704aa4f28532a145d74d01.png)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
float a = s.nextFloat();
System.out.println("读取的浮点数的值是:"+a);
}
}
步骤 3 : 使用Scanner读取字符串
![f91626f26ee48176c51688594366af2c.png](https://i-blog.csdnimg.cn/blog_migrate/e4df1150bc73038c7f8aac5b4acbc5c5.png)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String a = s.nextLine();
System.out.println("读取的字符串是:"+a);
}
}
步骤 4 : 读取了整数后,接着读取字符串
需要注意的是,如果在通过nextInt()读取了整数后,再接着读取字符串,读出来的是回车换行:"rn",因为nextInt仅仅读取数字信息,而不会读取回车换行"rn".
所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次nextLine(),第一次是取走回车换行,第二次才是读取真正的字符串
![36168da02e5c0188bad2d1c24764b1cf.png](https://i-blog.csdnimg.cn/blog_migrate/783473acdc5fe0b654fcf64665f5c5a0.jpeg)
import java.util.Scanner;
public class HelloWorld {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int i = s.nextInt();
System.out.println("读取的整数是"+ i);
String rn = s.nextLine();
String a = s.nextLine();
System.out.println("读取的字符串是:"+a);
}
}