java如何输入
使用 Scanner 类进行输入
Scanner 是 Java 中最常用的输入工具,位于 java.util 包中。它可以读取用户从控制台输入的数据。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数: ");
int num = scanner.nextInt();
System.out.println("你输入的整数是: " + num);
scanner.close();
}
}
使用 BufferedReader 进行输入
BufferedReader 是另一种输入方式,效率较高但使用稍复杂。需要配合 InputStreamReader 使用。
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("请输入字符串: ");
String input = reader.readLine();
System.out.println("你输入的字符串是: " + input);
}
}
命令行参数输入
程序可以通过 main 方法的参数接收命令行输入。
public class Main {
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("第一个参数是: " + args[0]);
} else {
System.out.println("没有提供参数");
}
}
}
读取文件输入
Java 也可以从文件中读取输入内容。
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}
处理不同类型输入
Scanner 支持多种数据类型的输入方法:

Scanner scanner = new Scanner(System.in);
int i = scanner.nextInt(); // 读取整数
double d = scanner.nextDouble(); // 读取双精度浮点数
String s = scanner.next(); // 读取单词(空格分隔)
String line = scanner.nextLine(); // 读取整行
boolean b = scanner.nextBoolean(); // 读取布尔值






