1. 使用Scanner读取字符和字符串
3 /** 4 * Created by SheepCore on 2020-2-26 5 */ 7 public class Main { 8 public static void main(String[] args) { 9 Scanner scan = new Scanner(System.in); //声明一个Scanner对象,初始输入流为控制台 10 String name = scan.nextLine(); //读取键盘输入字符串(包括空格、Tab,不包括最后的Enter) 11 String id = scan.nextLine(); 12 int age; 13 float height; 14 double weight; 15 age = scan.nextInt(); //读取下一个int(光标停在本行的空格之前) 16 height = scan.nextFloat(); //读取下一个float 17 weight = scan.nextDouble(); //读取下一个double 18 19 System.out.println("name: " + name + "\nid: " + id); 20 System.out.println("age: " + age + " height: " + height + " weight: " + weight); 21 } 22 }
sheepcore 11001100 22 178.3 68.5name: sheepcore id: 11001100 age: 22 height: 178.3 weight: 68.5
2. 使用System.in.read()读取单个字符
如果只要读取一个字符可以通过read()方法实现。
/** * Created by SheepCore on 2020-2-26 */ public class Main { public static void main(String[] args) { char read; System.out.print("Enter a char: "); try { //如果输入有误或者没有输入则会抛出IOException,所以这里需要在try_catch_block中捕获 read = (char) System.in.read(); //通过控制台读取一个字符 System.out.println(read); } catch(Exception e) { e.printStackTrace(); //打印错误信息 } } }
3. 通过BufferedReader以缓冲方式读取字符串
这种方法可以读取一行中的空格(space and tab),而Scanner读取时按空格分隔,空格后面无法读取,如果想要读取含有空格的字符串就需要使用这种方法。
1 /** 2 * Created by SheepCore on 2020-2-26 3 * 4 * how to deal with BufferedReader 5 * try and catch the IOException 6 * read a line with readLine() 7 */ 8 public class Main { 9 public static void main(String[] args) { 10 String name; 11 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 System.out.print("What‘s your name? "); 13 try { 14 name = br.readLine(); 15 System.out.println("My name is " + name + "."); 16 } catch(Exception e) { 17 e.printStackTrace(); 18 } 19 } 20 }
What‘s your name? Sheep Core My name is Sheep Core.
4.Summary:
这三种方法几乎可以应对所有的控制台输入,如果想多行输入,只需使用循环控制语句多次输入就可以了!掌握这些就可以开启刷题之旅了! Let‘s go get LeetCode!
水滴石穿,笨鸟先飞!
原文地址:https://www.cnblogs.com/sheepcore/p/12366661.html
时间: 2024-10-08 08:50:43