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]);

   }


       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM