歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java從控制台讀入數據的幾種方法

Java從控制台讀入數據的幾種方法

日期:2017/3/1 10:40:37   编辑:Linux編程

這裡記錄Java中從控制台讀入信息的幾種方式,已備後查!

(1)JDK 1.4(JDK 1.5和JDK 1.6也都兼容這種方法)

 
  1. public class TestConsole1 {
  2. public static void main(String[] args) {
  3. String str = readDataFromConsole("Please input string:);
  4. System.out.println("The information from console: + str);
  5. }
  6. /**
  7. * Use InputStreamReader and System.in to read data from console
  8. *
  9. * @param prompt
  10. *
  11. * @return input string
  12. */
  13. private static String readDataFromConsole(String prompt) {
  14. BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  15. String str = null;
  16. try {
  17. System.out.print(prompt);
  18. str = br.readLine();
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. return str;
  23. }
  24. }


 

(2)JDK 1.5(利用Scanner進行讀取)

 
  1. public class TestConsole2 {
  2. public static void main(String[] args) {
  3. String str = readDataFromConsole("Please input string:");
  4. System.out.println("The information from console:" + str);
  5. }
  6. /**
  7. * Use java.util.Scanner to read data from console
  8. *
  9. * @param prompt
  10. *
  11. * @return input string
  12. */
  13. private static String readDataFromConsole(String prompt) {
  14. Scanner scanner = new Scanner(System.in);
  15. System.out.print(prompt);
  16. return scanner.nextLine();
  17. }
  18. }


 
Scanner還可以很方便的掃描文件,讀取裡面的信息並轉換成你要的類型,比如對“2 2.2 3.3 3.33 4.5 done”這樣的數據求和,見如下代碼:
 
  
  1. public class TestConsole4 {
  2. public static void main(String[] args) throws IOException {
  3. FileWriter fw = new FileWriter("num.txt");
  4. fw.write("2 2.2 3.3 3.33 4.5 done");
  5. fw.close();
  6. System.out.println("Sum is "+scanFileForSum("num.txt"));
  7. }
  8. public static double scanFileForSum(String fileName) throws IOException {
  9. double sum = 0.0;
  10. FileReader fr = null;
  11. try {
  12. fr = new FileReader(fileName);
  13. Scanner scanner = new Scanner(fr);
  14. while (scanner.hasNext()) {
  15. if (scanner.hasNextDouble()) {
  16. sum = sum + scanner.nextDouble();
  17. } else {
  18. String str = scanner.next();
  19. if (str.equals("done")) {
  20. break;
  21. } else {
  22. throw new RuntimeException("File Format is wrong!");
  23. }
  24. }
  25. }
  26. } catch (FileNotFoundException e) {
  27. throw new RuntimeException("File " + fileName + " not found!");
  28. } finally {
  29. if (fr != null)
  30. fr.close();
  31. }
  32. return sum;
  33. }
  34. }
Copyright © Linux教程網 All Rights Reserved