Java一點輸入輸出技巧

來源:互聯網
上載者:User

標籤:for   截取   一點   scale   轉換   line   優勢   res   date   

輸入:

格式1:Scanner sc = new Scanner(System.in);

格式2:Scanner sc = new Scanner(new BufferedInputStream(System.in));

資料量大時,格式2更快。

 

Split方法:

String str = scanner.next();

String[] date = str.split("/");

System.out.println(date[0]+"年"+date[1]+"月"+date[2]+"日");

 

DecimalFormat

NumberFormat

保留小數位元!!

BigDecimal.setScale(2,BigDecimal.ROUND_HALF_UP);

 

 

子串:

String ss = "wo ai zhou";

System.out.println(ss.substring(3,7));

截取子串從第3個到第7個(從0開始,第7位不算)

結果是:ai z

 

高精度:

BigInteger和BigDecimal 是Java作為解題工具來說具有較大優勢的地方

BigInteger bigN = new BigInteger(st,base); //base表示進位

 

進位轉換

同樣也是Java非常具有優勢的一個地方

int a = Integer.parseInt("12534",8);

System.out.println(a);

String res = Integer.toString(12345,16);

System.out.println(res);

 

檔案輸入輸出

這裡只記錄比較高效的方法:

寫檔案:

FlieWriter類:

FileWriter fw = new FileWriter("my.txt");

fw.write("Hello");

fw.close();

讀檔案:

File file = new File("my.txt");

FileInputStream fis = new FileInputStream(file);

InputStreamReader isReader = new InputStreamReader(fis);

BufferedReader br = new BufferedReader(isReader);

String ss;

while((ss = br.readLine())!=null){

    System.out.println(ss);

}

 

 

或者直接:

File file = new File("my.txt");

BufferedReader br =

new BufferedReader(new InputStreamReader(new FileInputStream(file)));

String ss;

while((ss = br.readLine())!=null){

    System.out.println(ss);

}

(我其實更喜歡這種,寫的時候不拖泥帶水)

Java一點輸入輸出技巧

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.