第十课 输入输出
一、 在输入出中,我利用System.out.println()可以非常容易实现了,比如以下输出:
public class outputTest{
public static void main(String args[]){
float x;
x=100.0f/3.0f;
System.out.println(x);
System.out.println(100.0/3.0);
}
}
结果:
33.333332
33.333333333333336
在输出中我们看到结果是不一样的,当然我们知道是由于精度的不同造成的,因为在100.0和3.0中默认为双精度的。
我们这节课中讨论的并不是这个结果,而是如何输出一个格式化的数字,比如货币或是百分比的。
在java.text包中,提供了NumberFormat类可以产生这种格式,然后我们再用format方法来得到格式化的字符
import java.text.*;
public class outputTest{
public static void main(String args[]){
double x;
x=100.0/3.0;
NumberFormat f1=NumberFormat.getNumberInstance();//数字格式
String s=f1.format(x);
System.out.println(s);
NumberFormat f2=NumberFormat.getPercentInstance();//百分比格式
s=f2.format(x);
System.out.println(s);
NumberFormat f3=NumberFormat.getCurrencyInstance();//货币格式,这跟系统区域有关
s=f3.format(x);
System.out.println(s);
}
}
输出结果分别为:
33.333
3,333%
$33.33
三、 键盘输入:我们选看下面的例子
import javax.swing.*;
public class inputTest{
public static void main(String args[]){
String name=JOptionPane.showInputDialog("please input you name:");
String input=JOptionPane.showInputDialog("please input you age:");
int age=Integer.parseInt(input);
System.out.println("your name:"+name+" you age:"+age);
System.exit(0);
}
}
现在我们给出的键盘输入的包在javax.swing中,我们利用JOptionPane类的showInputDialog()方法来实现。Integer类的parseInt()方法实现由字符串转换成了数值。在最后中,我们利用java.lang.System类的exit(0)方法是把运行状态码传递给操作系统,并退出。