java自定義Scanner類似功能類的實例講解
讀取鍵盤輸入
package com.zjx.io;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 面試題 * 讀取鍵盤各個數據類型 * */public class TestFaceIo {public static void main(String[] args) {System.out.print('請輸入姓名: ');String name = MyInput.readString();System.out.print('請輸入年齡: ');int age = MyInput.readInt();System.out.print('請輸入體重:');double weight = MyInput.readDouble();System.out.print('請輸入性別:');char sex = MyInput.readChar();System.out.println(name + 't' + age + 't' + weight + 't' + sex);MyInput.close();}}class MyInput{static BufferedReader reader = null;/** * 讀取整數 * @return */public static int readInt(){int num = Integer.parseInt(readString());return num;}/** * 讀取浮點數 * @return */public static double readDouble(){double num = Double.parseDouble(readString());return num;}/** * 讀取char單個字符 * @return */public static char readChar(){char ch = readString().charAt(0);return ch;}/** * 讀取字符串 * @return */public static String readString(){try {reader = new BufferedReader(new InputStreamReader(System.in));String line = reader.readLine();return line;} catch (Exception e) {//編譯異常--》運行異常throw new RuntimeException(e);} }/** * 關閉 */public static void close(){if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}}
補充知識:java的Scanner與Fmatting
Scanner掃描儀與Fmatting
Programming I/O often involves translating to and from the neatly formatted data humans like to work with. 譯文:對I / O進行編程通常涉及到人們喜歡使用的格式正確的數據的轉換。(機器翻譯的,有點拗口,歡迎大神幫忙翻譯的順口一點,總而言之,將數據轉換為人們喜歡的)
為了幫助您完成這些雜務,Java平臺提供了兩個API。 掃描程序API將輸入分為與數據位相關聯的各個令牌。 格式API將數據組合成格式良好,易于閱讀的格式。(細心地人會發現,掃描程序Scanner和格式化Fmatting是相反的兩個操作,一個是分散數據,一個是組合數組)
Scanner
定義:Scanner類型的對象可用于將格式化的輸入分解為令牌,并根據其數據類型轉換單個令牌。
Scanner我看做用于格式化讀取文本文件
scanner掃描流。可以掃描文件與控制臺的輸入
默認情況下,scanner (掃描器)使用空格分隔令牌。 (空白字符包括空格,制表符和行終止符。有關完整列表,請參閱Character.isWhitespace的文檔。)要查看掃描的工作方式,讓我們看一下案例,該程序可讀取文本文件中的各個單詞。 并打印出來,每行一個。
package ff;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.util.Scanner;public class CopyCytes {public static void main(String[] args) throws IOException {Scanner s=null;try {s=new Scanner(new BufferedReader(new FileReader('txt/input.txt')));//s.useDelimiter(',s*');也可以自定義分隔符while(s.hasNext()) {System.out.println(s.next());}}finally {if(s!=null) {s.close();}}}}
programe result:
Bydefault,ascanneruseswhitespacetoseparatetokens.
從以上程序測試可以看出來Scanner掃描儀根據某一個分割符號一行一行的打印數據。
Scanner用完必須關閉底層流
注意:類在處理Scanner對象時調用Scanner的close方法。即使Scanner掃描儀不是流,您也需要關閉它,以表明您已處理完其底層流。
Scanner可以自定義分隔符
若要使用其他標記分隔符,請調用useDelimiter(),指定一個正則表達式。例如,假設您希望令牌分隔符是逗號,后面有空格。你會調用
s.useDelimiter(',s*');
Scanner掃描儀支持多種數據類型
上面的示例將所有輸入標記視為簡單的字符串值
Scanner還支持所有Java語言的基元類型(char除外)以及BigInteger和BigDecimal的標記。
此外,數值可以使用數千個分隔符。
因此,在US語言環境中,Scanner正確地讀取字符串“32767”表示整數值。
We have to mention the locale, because thousands separators and decimal symbols are locale specific. So, the following example would not work correctly in all locales if we didn’t specify that the scanner should use the US locale. That’s not something you usually have to worry about, because your input data usually comes from sources that use the same locale as you do. But this example is part of the Java Tutorial and gets distributed all over the world.
譯文:
我們必須提到語言環境,因為數千個分隔符和十進制符號是特定于語言環境的。 因此,如果我們未指定掃描儀應使用美國語言環境,則以下示例在所有語言環境中均無法正常工作。 通常不必擔心,因為您的輸入數據通常來自與您使用相同語言環境的源。 但是此示例是Java教程的一部分,并在全世界范圍內分發。
package ff;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.util.Locale;import java.util.Scanner;public class CopyCytes {public static void main(String[] args) throws IOException {Scanner s = null;double sum = 0;try {s = new Scanner(new BufferedReader(new FileReader('txt/input.txt')));//s.useDelimiter(',s*');s.useLocale(Locale.US);while (s.hasNext()) {if (s.hasNextDouble()) {sum = sum + s.nextDouble();} else {s.next();}}} finally {if (s != null) {s.close();}System.out.println(sum);}}}
input.txt文件內容是:
8.532,7673.141591,000,000.1
program result:
輸出字符串為“ 1032778.74159”。
在某些語言環境( in some locales)中,句點將是一個不同的字符,因為System.out是一個PrintStream對象,并且該類沒有提供重寫默認語言環境的方法。 我們可以覆蓋整個程序的語言環境,也可以只使用格式化,如下一主題“格式化”中所述。
重點:
設置語言環境
format
實現(格式fammatting)的流對象是字符流類PrintWriter或字節流類PrintStream的實例。
Note: The only PrintStream objects you are likely to need are System.out and System.err. (See I/O from the Command Line for more on these objects.) When you need to create a formatted output stream, instantiate PrintWriter, not PrintStream.
原文:
Like all byte and character stream objects, instances of PrintStream and PrintWriter implement a standard set of write methods for simple byte and character output. In addition, both PrintStream and PrintWriter implement the same set of methods for converting internal data into formatted output. Two levels of formatting are provided: print and println format individual values in a standard way. format formats almost any number of values based on a format string, with many options for precise formatting.
譯文:
像所有字節和字符流對象一樣,PrintStream和PrintWriter的實例實現一組標準的寫Write方法,用于簡單的字節和字符輸出。 此外字節流輸出類PrintStream和字符流類PrintWriter都實現了將內部數據轉換為格式化輸出的相同方法集。 提供了兩種格式設置:
print和println以標準方式格式化各個值。
Fammatting(格式)會基于一個格式字符串對幾乎任何數量的值進行格式設置,并提供許多用于精確格式設置的選項。
原文:
Invoking print or println outputs a single value after converting the value using the appropriate toString method. We can see this in the Root example:
譯文:
調用print或println將輸出一個經過toString方法轉換的值。 我們可以在以下示例中看到這一點:
package ff;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.util.Locale;import java.util.Scanner;public class CopyCytes {public static void main(String[] args) throws IOException {Scanner s = null;double sum = 0;int i = 2;double r = Math.sqrt(i);System.out.print('the square root of ');// i的第一次格式化,使用的是print的重載System.out.print(i);System.out.print(' is ');// r的第一次格式化也是使用的Print的重載System.out.print(r);System.out.println('.');i = 5;r = Math.sqrt(i);// i 和 r的第二次格式化是使用的編譯器隱藏的自動的格式化System.out.println('The square root of ' + i + ' is ' + r + '.');}}
原文:
The i and r variables are formatted twice: the first time using code in an overload of print, the second time by conversion code automatically generated by the Java compiler,which also utilizes toString You can format any value this way, but you don’t have much control over the results.
譯文:
變量i和r被格式化兩次,第一次使用在一個print的重載中
第二次使用在使用了tostring方法的java編譯器生成的的自動轉換代碼中
通過這種方式你可以格式化任何值,但是你對結果沒有任何控制權(重點是你對格式化的結果沒有控制權)。
Format方法
原文:
The format method formats multiple arguments based on a format string. The format string consists of static text embedded with format specifiers; except for the format specifiers, the format string is output unchanged.
譯文:
format方法基于格式化的字符串格式化多個參數。 格式字符串由嵌入了格式說明符的靜態文本組成。
除格式說明符外,格式字符串的輸出保持不變。(簡單點,格式符號起到占位的作用,其他的字符正常輸出)
格式字符串支持許多功能。 在本教程中,我們將僅介紹一些基礎知識。 有關完整說明,請參閱API規范中的格式字符串語法。
Format案例:
package ff;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.PrintWriter;import java.util.Locale;import java.util.Scanner;public class CopyCytes {public static void main(String[] args) throws IOException {int i=2;double r=Math.sqrt(i);System.out.format('The square root of %d is %f.%n', i,r);}}
Like the three used in this example, all format specifiers begin with a % and end with a 1- or 2-character conversion that specifies the kind of formatted output being generated. The three conversions used here are://所有格式說明符都以%開頭,并以1或2個字符的轉換結尾,該轉換指定要生成的格式化輸出的種類
注意:
除%%和%n外,所有格式說明符必須與參數匹配。 如果沒有,則拋出異常。
原文:
In the Java programming language, the n escape always generates the linefeed character (u000A). Don’t use n unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n.
譯文:
在Java編程語言中, n轉義始終生成換行符( u000A)。 除非特別需要換行符,否則請勿使用 n。 要為本地平臺獲取正確的行分隔符,請使用%n。(這里的言外之意是,一個是生成轉義字符,一個是格式化占位符,兩者有本質區別,雖然在程序中看起來實現了一樣的效果。)
以上這篇java自定義Scanner類似功能類的實例講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。
相關文章:
