Java(四)輸出和輸入函數
介紹一下Java裏簡單常用的輸入輸出方法。
Java的輸出函數很簡單,直接調用System類的out對象的print函數即可。
代碼:
System.out.print(a);//輸出變量a的值 System.out.print("214214");//輸出字符串 System.out.print("123"+a);//混合輸出字符串和變量值 /* 當然也可以使用System.out.println();表示換行輸出,相當於System.out.print("\n");
其中System是一個類,out是java.io.PrintStream的對象,也就是System這個類中含有java.io.PrintStream的對象out。
print()是java.io.PrintStream類裏的一個方法,也就是out對象的一個方法。
*/
Java的輸入比較麻煩,找了好多書都講的不詳細,網上也看了些方法,像BufferedReader類和InputStreamReader類法,Scanner類法等等。綜合發現還是Scanner類最好用,它既可以讀字符,也可以讀字符串和整數。
代碼:
import java.util.Scanner; public static void main(String [] args) { Scanner sc = new Scanner(System.in); System.out.println("請輸入你的姓名:"); String name = sc.nextLine(); System.out.println("請輸入你的年齡:"); int age = sc.nextInt(); System.out.println("請輸入你的工資:"); float salary = sc.nextFloat(); System.out.println("你的信息如下:"); System.out.println("姓名:"+name+"\n"+"年齡:"+age+"\n"+"工資:"+salary); }
另外,該對象的next()方法和nextLine()方法的區別:
在java中,next()方法是不接收空格的,在接收到有效數據前,所有的空格或者tab鍵等輸入被忽略,若有有效數據,則遇到這些鍵退出。nextLine()可以接收空格或者tab鍵,其輸入應該以enter鍵結束。
再學習Java的輸入時,有個有趣的發現,感興趣的朋友可以往下看。
Java版的getchar()函數:
當時想的是,既然輸出用的是out對象,那麽必然有個in對象的方法能完成輸入的功能。於是就發現了System.in.read()這個東東,它實現的功能是:從鍵盤讀一個字符。好嘛^_^,那麽就輸下這個東東
System.out.println(System.in.read());
運行結果:
結果很意外,輸入5,輸出53 13 10;輸入a,輸出97 13 10;什麽也不輸直接回車,輸出13 10。即輸出了輸入字符、回車控制字符和換行控制字符的ASCLL碼!!
不,我不要ASCLL數字,我要字符型!那麽就強轉一下吧。改下代碼:
System.out.println((char)System.in.read());
果然如願輸出了字符型,而且回車控制字符和換行控制字符都不見了!而且經測試,結果完全符合算法題中的輸入的要求,即在Java中實現了類似C++中的getchar()函數!
再進一步思考,加個while(true)能否用字符數組形式輸出字符串呢?
代碼如下:
import java.io.IOException; public class dd { public static void main(String[] args) throws IOException { while(true){ System.out.print((char)System.in.read()); } } }
運行結果:
成功得到了字符串是不是?
然而並沒有。。
這個方法有極大的缺陷:
System.out.println((char)System.in.read());
實際就相當於:
InputStream a=System.in; char ch=(char)a.read(); System.out.print(ch);
果然還是沒有擺脫緩沖區的束縛,把剛才輸出字符串的代碼的while(true)換成for循環:
import java.io.IOException; public class dd { public static void main(String[] args) throws IOException { //while(true){ for(int i=0;i<5;i++){ System.out.print((char)System.in.read()); //} } } }
運行結果:
只能讀for循環限制的5個字符。。while(true)只是用一個死循環把輸入緩沖區的字符都讀完了而已,才造成了這種方法能讀字符串的假象- -!
再回到C/C++想想,這個真的和getchar()一毛一樣。。
參考下面代碼:
#include<stdio.h> int main() { while(1) { char a=getchar(); printf("%c",a); } return 0; }
運行結果:
曾經,getchar()是否給了你它能輸出字符串的假象呢?
Java(四)輸出和輸入函數