java的数据输入

1.java程序控制台输入数据的一种方法

import java.awt.*;
import javax.swing.*;
class Aa {
     public static void main(String args[]) {
       String ss=JOptionPane.showInputDialog("","请输入一个数");
       try {
           int i=Integer.parseInt(ss);
           System.out.println("i="+i);
       }catch(Exception e) {
          System.out.println("输入的数据类型不对,程序将退出");
          System.exit(0);
          }
     }
}

关键代码:
String ss=JOptionPane.showInputDialog("","请输入一个数");
然后再根据自己的需要,进行类型转换.
转换成整型:int i=Integer.parseInt(ss);
转换成单精度类型:float f=Float.parseFloat(ss);
转换成双精度类型:double d=Double.parseDouble(ss);

2.使用字符串BufferedReader实现输入

import java.io.*;

public class Input{
     public static void main(String args[]) throws IOException{
         String str;
         int a;
         BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
         System.out.println("请输入一个数:");
         str=buf.readLine();
         a=Integer.parseInt(str);
         System.out.println("输入的数为:"+a);
     }
}

关键代码:
BufferedReader buf=new BufferedReader(new InputStreamReader(System.in));
str=buf.readLine();

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章