Java中读取控制台输入的多种方式

avatar
作者
筋斗云
阅读量:0

  1. 使用Scanner类读取控制台输入:
import java.util.Scanner;  public class Main {     public static void main(String[] args) {         Scanner scanner = new Scanner(System.in);                  // 读取字符串         System.out.print("Enter a string: ");         String str = scanner.nextLine();         System.out.println("You entered: " + str);                  // 读取整数         System.out.print("Enter an integer: ");         int num = scanner.nextInt();         System.out.println("You entered: " + num);                  scanner.close();     } } 
  1. 使用BufferedReader类读取控制台输入:
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;  public class Main {     public static void main(String[] args) throws IOException {         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));                  // 读取字符串         System.out.print("Enter a string: ");         String str = reader.readLine();         System.out.println("You entered: " + str);                  // 读取整数         System.out.print("Enter an integer: ");         int num = Integer.parseInt(reader.readLine());         System.out.println("You entered: " + num);                  reader.close();     } } 

注意:使用BufferedReader类读取整数时,需要将读取的字符串转换为整数类型。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!