1 命令行输入输出
1.1 好用的输入
使用 java.util.Scanner
类进行输入
nextInt()
方法获得下一个 intnextDouble()
方法获得下一个 doublenext()
获得下一个单词import java.util.Scanner;
class ScannerTest {
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in); // 写法是固定的
System.out.print("请输入一个整数:");
int a = scanner.nextInt();
System.out.printf("%d 的平方是 %d\n", a, a*a);
}
}
使用
System.out
中的方法进行输出:println()
打印一行(自动换行)print()
打印指定内容(不会自动换行)printf()
格式化输出,与 C 语言中的一样
1.2 读入一个字符
java.io
包
System.in.read()
System.out.print()
&println()
&printf()
char c = ' ';
System.out.print("Please input a char: ");
try {
c = (char)System.in.read();
} catch (IOException e) {
}
System.out.println("You have entered: " + c);
1.3 读入一行 & 读入数字
- 输入一行
import java.io.*
public class AppLineInOut {
public static void main(String args[]) {
String s = "";
System.out.print("Please input a line:");
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
s = in.readLine();
} catch (IOException e) {
}
System.out.println("You have entered: " + s);
}
}
System.in 一次只能读一个字符,通过流封装后可以输入一个字符串
输入数字
Integer.parseInt(s);
Double.parseDouble(s);
import java.io.*
public class AppNumInOut {
public static void main(String args[]) {
String s = "";
int n = 0;
double d = 0;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please input an int: ");
s = in.readLine();
n = Integer.parseInt(s);
System.out.print("Please input a double: ");
s = in.readLine();
d = Double.parseDouble(s);
} catch (IOException e) {
}
System.out.println("You have entered: " + n + " and " + d);
}
}
2 图形界面输入输出
add(xxxx)
加入对象btn.addActionListener()
处理事件actionPerformed()
具体处理事件 ```java import java.awt.; import java.awt.event.; import javax.swing.*;
public class AppGraphInOut { public static void main( String args[] ) { new AppFrame(); } }
class AppFrame extends JFrame { // 在 swing 中实现 JTextField in = new JTextField(10); JButton btn = new JButton(“求平方”); JLabel out = new JLabel(“用于显示结果的标签”);
public AppFrame() {
setLayout( new FlowLayout() ); // 流式布局,一行一行的放
getContentPane().add( in );
getContentPane().add( btn );
getContentPane().add( out );
btn.addActionListener( new BtnActionAdapter() );
setSize( 400,100 );
setDefaultCloseOperation(DISPOSE_ON_CLOSE); // 设置关闭按钮的动作
setVisible(true);
}
class BtnActionAdapter implements ActionListener {
public void actionPerformed( ActionEvent e ) {
String s = in.getText();
double d = Double.parseDouble( s );
double sq = d * d;
out.setText( d + "的平方是:" + sq );
}
}
}
在 Java8 中可以简写为 `e->{...}`
```java
btn.addActionListener(e->{
String s = in.getText();
double d = Double.parseDouble(s);
double sq = Math.sqrt(d);
out.setText(d + " 的平方根是:" + sq);
});