Java 控制台輸入 Scanner

來源:互聯網
上載者:User

標籤:

1,Java 中 擷取 控制台輸入(System.in)的方法,一般有兩種:(1) BufferedReader  scin=new BufferedReader(new InputStreamReader(System.in));(2) Java.util.Scanner scin=new Jave.util.Scanner (System.in);2,使用Scanner 的方法:(1)是否有輸入:hasNext()====>該方法是的終端一直處於等待控制台輸入的狀態,若自己不去控制,則始終處於控制台輸入狀態;(2)擷取輸入的資料:(String) next(),(Int) nextnt()  和 hasNextInt(),(Long) nextLong()  hasNextLong(),。。。。。。;注意邏輯判斷,因為Java中與C/C++同樣具有隱形類型轉換(低類型自動轉換高類型)即若想擷取Int 和double,先判斷是否是 hasNextInt ,在判斷hasNextDouble;3,使用執行個體:

class TestScanner{public void input(){Scanner sc=new Scanner(System.in);String exit="exit";System.out.println("請輸入資料:(exit表示退出指令)");while(sc.hasNext()){if(sc.hasNextByte()){System.out.println("輸入了一個位元組: "+sc.nextByte());}else if(sc.hasNextInt()){System.out.println("輸入了一個整數: "+sc.nextInt());}else if(sc.hasNextDouble()){System.out.println("輸入了一個浮點數: "+sc.nextDouble());}else if(sc.hasNextBoolean()){System.out.println("輸入了一個布爾值: "+sc.nextBoolean());}else if(sc.next().contentEquals(exit)){System.out.println("退出!");break;}}}}
4,結果分析:
請輸入資料:(exit表示退出指令)123 876 9.0 true false exit輸入了一個位元組: 123輸入了一個整數: 876輸入了一個浮點數: 9.0輸入了一個布爾值: true輸入了一個布爾值: false退出!




</pre><p></p><p></p><p></p><pre name="code" class="java">

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java 控制台輸入 Scanner

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.