JAVA的輸入輸出

輸入/輸出是學習程序設計語言時首先遇到的問題。在JAVA中,我們有三種方法來提供輸入輸出。

標準輸入輸出

System.in表示標準輸入流
Sysem.out表示標準輸出流

標準輸出方法

  int  a;
      a=9;
      System.out.print("a"+a);   //print表示直接輸出不換行
      System.out.println("a"+a);   //println表示輸出之後自動換行
  

其代碼運行結果是將a輸出,即a=9

Scanner鍵盤輸入類

Scanner不像System可以直接可以拿來用,而Scanner則需要一個庫

import java.util.Scanner;    //庫文件調用Scanner


Scanner sc=new Scanner(System.in)
System.out.println("a");
int a=sc.nextlnt();
System.out.println("b");
int a=sc.nextlnt();
System.out.println("c");
int a=sc.nextlnt();

輸入六種數值數據類型的方法

Method Example
nextByte() byte b=scanner.nextByte();
nextDouble() double d=scanner.nextDouble();
nextFloat() float f=scanner.nextnextFloat();
nextInt() int i=scanner.nextInt();
nextLong() long l=scanner.nextLong();
nextShort short s=scanner.nextShort();

read方法的使用

System類含有標準輸入流的對象in,可以調用它的read方法來讀取鍵盤數據。

 import java.io.IOException;


System.out.println("請輸入:");
int i=0;
   while(true)
     {   

       try

     {

         
 i=System.in.read();

     }

   catch(IOException e){}

   System.out.println(i);
    }
 }

在Java程序中,使用System.in.read方法從鍵盤讀取一個字符時,必須引用“異常處理”機制。有兩種方法可以將其引入當前程序中。
1.直接在main函數後面用throw子句拋出IOException,形如throws java.io.IOException。(如上代碼所示)其中,IOException是輸入/輸出異常類,它定位於java.io系統包中。
注意
一般不建議使用read來讀取數據,首先,read讀入的是字符的ASCⅡ碼,其次,read自動識別換行,會佔用自己的函數。

命令行參數輸入法的應用

Application程序中主函數main的參數(String[] args)是一個String字符串類型的數組,用於接收命令行參數的輸入。在main函數中可以使用args數組中的元素,作爲一種交互輸入。

public class HelloArgs{
   public static void main(String arg[]{
   System.out.println(arg[0]+","+args[1]+"Hello!);
   }
   }

JOptionPane對話框輸入法

import javax.swing.JOptionPane;


int a;

        String str="";

       str=JOptionPane.showInputDialog(null,"a:");

       a=Integer.parseInt(str);

JOptionPane中可顯示對話框,對數字之後不會被顯示。因此最爲常用的爲System類。

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