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();

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