java自定義Scanner類似功能類的實例講解
讀取鍵盤輸入
package com.zjx.io;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;/** * 面試題 * 讀取鍵盤各個數(shù)據(jù)類型 * */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;/** * 讀取整數(shù) * @return */public static int readInt(){int num = Integer.parseInt(readString());return num;}/** * 讀取浮點數(shù) * @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);} }/** * 關(guān)閉 */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進(jìn)行編程通常涉及到人們喜歡使用的格式正確的數(shù)據(jù)的轉(zhuǎn)換。(機(jī)器翻譯的,有點拗口,歡迎大神幫忙翻譯的順口一點,總而言之,將數(shù)據(jù)轉(zhuǎn)換為人們喜歡的)
為了幫助您完成這些雜務(wù),Java平臺提供了兩個API。 掃描程序API將輸入分為與數(shù)據(jù)位相關(guān)聯(lián)的各個令牌。 格式API將數(shù)據(jù)組合成格式良好,易于閱讀的格式。(細(xì)心地人會發(fā)現(xiàn),掃描程序Scanner和格式化Fmatting是相反的兩個操作,一個是分散數(shù)據(jù),一個是組合數(shù)組)
Scanner
定義:Scanner類型的對象可用于將格式化的輸入分解為令牌,并根據(jù)其數(shù)據(jù)類型轉(zhuǎn)換單個令牌。
Scanner我看做用于格式化讀取文本文件
scanner掃描流。可以掃描文件與控制臺的輸入
默認(rèn)情況下,scanner (掃描器)使用空格分隔令牌。 (空白字符包括空格,制表符和行終止符。有關(guān)完整列表,請參閱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掃描儀根據(jù)某一個分割符號一行一行的打印數(shù)據(jù)。
Scanner用完必須關(guān)閉底層流
注意:類在處理Scanner對象時調(diào)用Scanner的close方法。即使Scanner掃描儀不是流,您也需要關(guān)閉它,以表明您已處理完其底層流。
Scanner可以自定義分隔符
若要使用其他標(biāo)記分隔符,請調(diào)用useDelimiter(),指定一個正則表達(dá)式。例如,假設(shè)您希望令牌分隔符是逗號,后面有空格。你會調(diào)用
s.useDelimiter(',s*');
Scanner掃描儀支持多種數(shù)據(jù)類型
上面的示例將所有輸入標(biāo)記視為簡單的字符串值
Scanner還支持所有Java語言的基元類型(char除外)以及BigInteger和BigDecimal的標(biāo)記。
此外,數(shù)值可以使用數(shù)千個分隔符。
因此,在US語言環(huán)境中,Scanner正確地讀取字符串“32767”表示整數(shù)值。
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.
譯文:
我們必須提到語言環(huán)境,因為數(shù)千個分隔符和十進(jìn)制符號是特定于語言環(huán)境的。 因此,如果我們未指定掃描儀應(yīng)使用美國語言環(huán)境,則以下示例在所有語言環(huán)境中均無法正常工作。 通常不必?fù)?dān)心,因為您的輸入數(shù)據(jù)通常來自與您使用相同語言環(huán)境的源。 但是此示例是Java教程的一部分,并在全世界范圍內(nèi)分發(fā)。
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文件內(nèi)容是:
8.532,7673.141591,000,000.1
program result:
輸出字符串為“ 1032778.74159”。
在某些語言環(huán)境( in some locales)中,句點將是一個不同的字符,因為System.out是一個PrintStream對象,并且該類沒有提供重寫默認(rèn)語言環(huán)境的方法。 我們可以覆蓋整個程序的語言環(huán)境,也可以只使用格式化,如下一主題“格式化”中所述。
重點:
設(shè)置語言環(huán)境
format
實現(xiàn)(格式fammatting)的流對象是字符流類PrintWriter或字節(jié)流類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.
譯文:
像所有字節(jié)和字符流對象一樣,PrintStream和PrintWriter的實例實現(xiàn)一組標(biāo)準(zhǔn)的寫Write方法,用于簡單的字節(jié)和字符輸出。 此外字節(jié)流輸出類PrintStream和字符流類PrintWriter都實現(xiàn)了將內(nèi)部數(shù)據(jù)轉(zhuǎn)換為格式化輸出的相同方法集。 提供了兩種格式設(shè)置:
print和println以標(biāo)準(zhǔn)方式格式化各個值。
Fammatting(格式)會基于一個格式字符串對幾乎任何數(shù)量的值進(jìn)行格式設(shè)置,并提供許多用于精確格式設(shè)置的選項。
原文:
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:
譯文:
調(diào)用print或println將輸出一個經(jīng)過toString方法轉(zhuǎn)換的值。 我們可以在以下示例中看到這一點:
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編譯器生成的的自動轉(zhuǎn)換代碼中
通過這種方式你可以格式化任何值,但是你對結(jié)果沒有任何控制權(quán)(重點是你對格式化的結(jié)果沒有控制權(quán))。
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方法基于格式化的字符串格式化多個參數(shù)。 格式字符串由嵌入了格式說明符的靜態(tài)文本組成。
除格式說明符外,格式字符串的輸出保持不變。(簡單點,格式符號起到占位的作用,其他的字符正常輸出)
格式字符串支持許多功能。 在本教程中,我們將僅介紹一些基礎(chǔ)知識。 有關(guān)完整說明,請參閱API規(guī)范中的格式字符串語法。
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個字符的轉(zhuǎn)換結(jié)尾,該轉(zhuǎn)換指定要生成的格式化輸出的種類
注意:
除%%和%n外,所有格式說明符必須與參數(shù)匹配。 如果沒有,則拋出異常。
原文:
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轉(zhuǎn)義始終生成換行符( u000A)。 除非特別需要換行符,否則請勿使用 n。 要為本地平臺獲取正確的行分隔符,請使用%n。(這里的言外之意是,一個是生成轉(zhuǎn)義字符,一個是格式化占位符,兩者有本質(zhì)區(qū)別,雖然在程序中看起來實現(xiàn)了一樣的效果。)
以上這篇java自定義Scanner類似功能類的實例講解就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Django視圖類型總結(jié)2. Xml簡介_動力節(jié)點Java學(xué)院整理3. Intellij IDEA 關(guān)閉和開啟自動更新的提示?4. Ajax引擎 ajax請求步驟詳細(xì)代碼5. 解析原生JS getComputedStyle6. idea設(shè)置自動導(dǎo)入依賴的方法步驟7. IntelliJ IDEA Java項目手動添加依賴 jar 包的方法(圖解)8. idea重置默認(rèn)配置的方法步驟9. intellij idea設(shè)置統(tǒng)一JavaDoc模板的方法詳解10. Spring @Profile注解實現(xiàn)多環(huán)境配置
