Java从控制台读取数据

一、读取整数

 1 import java.util.Scanner;
 2  
 3 public class HelloWorld {
 4     public static void main(String[] args) {
 5         Scanner s = new Scanner(System.in);
 6         int a = s.nextInt();
 7         System.out.println("第一个整数:"+a);
 8         int b = s.nextInt();
 9         System.out.println("第二个整数:"+b);
10     }
11 }

二、读取浮点数

 1 import java.util.Scanner;
 2   
 3 public class HelloWorld {
 4     public static void main(String[] args) {
 5         Scanner s = new Scanner(System.in);
 6         float a = s.nextFloat();
 7         System.out.println("读取的浮点数的值是:"+a);
 8  
 9     }
10 }

三、读取字符串

1 import java.util.Scanner;
2   
3 public class HelloWorld {
4     public static void main(String[] args) {
5         Scanner s = new Scanner(System.in);
6         String a = s.nextLine();
7         System.out.println("读取的字符串是:"+a);
8     }
9 }

四、读取整数之后读取字符串

需要注意的是,如果在通过nextInt()读取了整数后,再接着读取字符串,读出来的是回车换行:"\r\n",因为nextInt仅仅读取数字信息,而不会读取回车换行"\r\n".

所以,如果在业务上需要读取了整数后,接着读取字符串,那么就应该连续执行两次nextLine(),第一次是取走回车换行,第二次才是读取真正的字符串

 1 import java.util.Scanner;
 2    
 3 public class HelloWorld {
 4     public static void main(String[] args) {
 5         Scanner s = new Scanner(System.in);
 6         int i = s.nextInt();
 7         System.out.println("读取的整数是"+ i);
 8         String rn = s.nextLine();
 9         String a = s.nextLine();
10         System.out.println("读取的字符串是:"+a);
11     }
12 }

猜你喜欢

转载自www.cnblogs.com/zhuangbijingdeboke/p/12077225.html
今日推荐