Java常用的輸入輸出方法

來源:互聯網
上載者:User

標籤:scanner   font   new   輸出資料流   str   highlight   16px   char   簡單   

對於經常上機刷題的來說,首先得解決輸入輸出方法,Java的輸入輸出資料流在Java學習過程的後面部分才會接觸,但是我們可以掌握一些簡單的,常用的輸入輸出方法

首先輸出

大家最熟悉的莫過於輸出方法,直接用System.out.println()或者System.out.print()了下面一個執行個體

public class Main{public static void main(String[] args){System.out.println("hello_1!");System.out.print("hello_2!");System.out.print("hello!_3");}}

System.out.print()用於直接輸出,System.out.println()也是直接輸出,但在結束的地方會加一個換行

接下來看輸入

如果你要進行輸入,請一定加上兩個包

import java.util.*;import java.io.*;

 

請看下面例子用於輸入單個字元

import java.io.*;import java.util.*;public class Main{public static void main(String[] args)throws IOException{char c=(char)System.in.read();System.out.println(c);}}

 

輸入整數或者字元(串)

import java.io.*;import java.util.*;public class Main{public static void main(String[] args)throws IOException{Scanner cin=new Scanner(System.in);int a=cin.nextInt();//輸入一個整數System.out.println(a);double b=cin.nextDouble();//輸入一個雙精確度的浮點數System.out.println(b);String str=cin.next();//輸入一個單詞,遇到分號則輸入終止System.out.println(str);String str2=cin.nextLine();//輸入一行,中間可有多個空格System.out.println(str2);}}

還可以用BufferedReader類輸入

import java.io.*;import java.util.*;public class Main{public static void main(String[] args)throws IOException{BufferedReader cin=new BufferedReader(new InputStreamReader(System.in));String str=cin.readLine();//輸入一行System.out.println(str);String str2=cin.readLine();int a=Integer.parseInt(str2);//將str2轉換為int,並複製給aSystem.out.println(a);String str3=cin.readLine();double b=Double.parseDouble(str3);//將str3轉換為double,並複製給bSystem.out.println(b);}}

 

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.