Java程序可以通过以下几种方式与用户进行交互:
System.in
和System.out
来获取用户的输入和向用户输出信息。可以使用Scanner
类来读取用户的输入。import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("请输入您的名字:"); String name = scanner.nextLine(); System.out.println("您好," + name + "!"); System.out.print("请输入您的年龄:"); int age = scanner.nextInt(); System.out.println("您的年龄是:" + age); scanner.close(); } }
args
数组来获取传入的参数。public class Main { public static void main(String[] args) { if (args.length > 0) { String name = args[0]; System.out.println("您好," + name + "!"); } else { System.out.println("请输入您的名字作为命令行参数!"); } } }
import javax.swing.*; public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Hello"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); JButton button = new JButton("点击我"); button.addActionListener(e -> JOptionPane.showMessageDialog(frame, "Hello World!")); JPanel panel = new JPanel(); panel.add(button); frame.add(panel); frame.setVisible(true); }); } }
以上是几种常见的与用户交互的方式,根据具体的需求和场景选择适合的方式。