java——擷取從控制台輸入的資料的方法,java控制台

來源:互聯網
上載者:User

java——擷取從控制台輸入的資料的方法,java控制台

一、使用標準輸入串System.in

  System.in.read();     //一次唯讀入一個位元組資料,但是我們往往希望獲得的是一個字串或者一組數字

 

二、使用Scanner獲得一個字串或一組數字

  //Scanner的next()方法用以取得使用者輸入的字串;nextInt()將取得的輸入字串轉換為整數類型;同樣,nextFloat()轉換成浮點型;nextBoolean()轉換成布爾型。

  //Scanner取得的輸入以space, tab, enter 鍵為結束符;

  System.out.print("輸入n:");
      Scanner scan = new Scanner(System.in);
      String read = scan.nextLine();
      int n = Integer.parseInt(read);
      System.out.println("輸入資料n="+n);

 

三、使用BufferedReader取得含空格的輸入

  //要想取得包含空格在內的輸入,可以用java.io.BufferedReader類來實現;

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String read1 = null;
        System.out.print("輸入資料:");
        try {
            read1 = br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("輸入資料:" + read1);
        String[] split_num = read1.split(" ");
        int[] split_num2int = new int[n];
        for(int i=0;i<split_num.length;i++) {
            System.out.print(split_num[i] + " ");
            split_num2int[i] = Integer.parseInt(split_num[i]);

   }


       

聯繫我們

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