java中如何输入数据
从控制台输入数据
使用 Scanner 类从控制台读取输入数据。需导入 java.util.Scanner 包。
Scanner scanner = new Scanner(System.in);
System.out.print("请输入一个整数: ");
int num = scanner.nextInt();
System.out.print("请输入一个字符串: ");
String str = scanner.next();
scanner.close(); // 关闭Scanner
从文件输入数据
通过 Scanner 或 BufferedReader 读取文件内容。需处理 FileNotFoundException 异常。
// 使用Scanner读取文件
Scanner fileScanner = new Scanner(new File("input.txt"));
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
System.out.println(line);
}
fileScanner.close();
// 使用BufferedReader读取文件
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
从命令行参数输入
通过 main 方法的 args 数组获取命令行参数。
public static void main(String[] args) {
if (args.length > 0) {
System.out.println("第一个参数: " + args[0]);
}
}
使用对话框输入数据
通过 JOptionPane 显示图形化输入对话框。需导入 javax.swing.JOptionPane。
String input = JOptionPane.showInputDialog("请输入数据:");
System.out.println("输入的内容: " + input);
从网络或API输入数据
使用 HttpURLConnection 或第三方库(如 OkHttp)获取网络数据。
URL url = new URL("https://api.example.com/data");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String response = in.readLine();
in.close();
System.out.println("API响应: " + response);






