欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java自定義Scanner類似功能類的實(shí)例講解

 更新時(shí)間:2020年08月21日 10:15:35   作者:AppWhite_Star  
這篇文章主要介紹了java自定義Scanner類似功能類的實(shí)例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

讀取鍵盤(pán)輸入

package com.zjx.io;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 面試題
 * 讀取鍵盤(pán)各個(gè)數(shù)據(jù)類型
 *
 */
public class TestFaceIo {
	public static void main(String[] args) {
		System.out.print("請(qǐng)輸入姓名: ");
		String name = MyInput.readString();
		System.out.print("請(qǐng)輸入年齡: ");
		int age = MyInput.readInt();
		System.out.print("請(qǐng)輸入體重:");
		double weight = MyInput.readDouble();
		System.out.print("請(qǐng)輸入性別:");
		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;
	}
	
	/**
	 * 讀取浮點(diǎn)數(shù)
	 * @return
	 */
	public static double readDouble(){
		double num = Double.parseDouble(readString());
		return num;
	}
	
	/**
	 * 讀取char單個(gè)字符
	 * @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) {
			//編譯異常--》運(yùn)行異常
			throw new RuntimeException(e);
		} 
	}
	
	/**
	 * 關(guān)閉
	 */
	public static void close(){
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}

補(bǔ)充知識(shí):java的Scanner與Fmatting

Scanner掃描儀與Fmatting

Programming I/O often involves translating to and from the neatly formatted data humans like to work with. 譯文:對(duì)I / O進(jìn)行編程通常涉及到人們喜歡使用的格式正確的數(shù)據(jù)的轉(zhuǎn)換。(機(jī)器翻譯的,有點(diǎn)拗口,歡迎大神幫忙翻譯的順口一點(diǎn),總而言之,將數(shù)據(jù)轉(zhuǎn)換為人們喜歡的)

為了幫助您完成這些雜務(wù),Java平臺(tái)提供了兩個(gè)API。 掃描程序API將輸入分為與數(shù)據(jù)位相關(guān)聯(lián)的各個(gè)令牌。 格式API將數(shù)據(jù)組合成格式良好,易于閱讀的格式。(細(xì)心地人會(huì)發(fā)現(xiàn),掃描程序Scanner和格式化Fmatting是相反的兩個(gè)操作,一個(gè)是分散數(shù)據(jù),一個(gè)是組合數(shù)組)

Scanner

定義:Scanner類型的對(duì)象可用于將格式化的輸入分解為令牌,并根據(jù)其數(shù)據(jù)類型轉(zhuǎn)換單個(gè)令牌。

Scanner我看做用于格式化讀取文本文件

scanner掃描流??梢話呙栉募c控制臺(tái)的輸入

默認(rèn)情況下,scanner (掃描器)使用空格分隔令牌。 (空白字符包括空格,制表符和行終止符。有關(guān)完整列表,請(qǐng)參閱Character.isWhitespace的文檔。)要查看掃描的工作方式,讓我們看一下案例,該程序可讀取文本文件中的各個(gè)單詞。 并打印出來(lái),每行一個(gè)。

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:

By
default,
a
scanner
uses
white
space
to
separate
tokens.

從以上程序測(cè)試可以看出來(lái)Scanner掃描儀根據(jù)某一個(gè)分割符號(hào)一行一行的打印數(shù)據(jù)。

Scanner用完必須關(guān)閉底層流

注意:類在處理Scanner對(duì)象時(shí)調(diào)用Scanner的close方法。即使Scanner掃描儀不是流,您也需要關(guān)閉它,以表明您已處理完其底層流。

Scanner可以自定義分隔符

若要使用其他標(biāo)記分隔符,請(qǐng)調(diào)用useDelimiter(),指定一個(gè)正則表達(dá)式。例如,假設(shè)您希望令牌分隔符是逗號(hào),后面有空格。你會(huì)調(diào)用

s.useDelimiter(",\\s*");

Scanner掃描儀支持多種數(shù)據(jù)類型

上面的示例將所有輸入標(biāo)記視為簡(jiǎn)單的字符串值

Scanner還支持所有Java語(yǔ)言的基元類型(char除外)以及BigInteger和BigDecimal的標(biāo)記。

此外,數(shù)值可以使用數(shù)千個(gè)分隔符。

因此,在US語(yǔ)言環(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.

譯文:

我們必須提到語(yǔ)言環(huán)境,因?yàn)閿?shù)千個(gè)分隔符和十進(jìn)制符號(hào)是特定于語(yǔ)言環(huán)境的。 因此,如果我們未指定掃描儀應(yīng)使用美國(guó)語(yǔ)言環(huán)境,則以下示例在所有語(yǔ)言環(huán)境中均無(wú)法正常工作。 通常不必?fù)?dān)心,因?yàn)槟妮斎霐?shù)據(jù)通常來(lái)自與您使用相同語(yǔ)言環(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.5
32,767
3.14159
1,000,000.1

program result:

輸出字符串為“ 1032778.74159”。

在某些語(yǔ)言環(huán)境( in some locales)中,句點(diǎn)將是一個(gè)不同的字符,因?yàn)镾ystem.out是一個(gè)PrintStream對(duì)象,并且該類沒(méi)有提供重寫(xiě)默認(rèn)語(yǔ)言環(huán)境的方法。 我們可以覆蓋整個(gè)程序的語(yǔ)言環(huán)境,也可以只使用格式化,如下一主題“格式化”中所述。

重點(diǎn):

設(shè)置語(yǔ)言環(huán)境

format

實(shí)現(xiàn)(格式fammatting)的流對(duì)象是字符流類PrintWriter或字節(jié)流類PrintStream的實(shí)例。

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é)和字符流對(duì)象一樣,PrintStream和PrintWriter的實(shí)例實(shí)現(xiàn)一組標(biāo)準(zhǔn)的寫(xiě)Write方法,用于簡(jiǎn)單的字節(jié)和字符輸出。 此外字節(jié)流輸出類PrintStream和字符流類PrintWriter都實(shí)現(xiàn)了將內(nèi)部數(shù)據(jù)轉(zhuǎn)換為格式化輸出的相同方法集。 提供了兩種格式設(shè)置:

print和println以標(biāo)準(zhǔn)方式格式化各個(gè)值。

Fammatting(格式)會(huì)基于一個(gè)格式字符串對(duì)幾乎任何數(shù)量的值進(jìn)行格式設(shè)置,并提供許多用于精確格式設(shè)置的選項(xiàng)。

原文:

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將輸出一個(gè)經(jīng)過(guò)toString方法轉(zhuǎn)換的值。 我們可以在以下示例中看到這一點(diǎ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的第二次格式化是使用的編譯器隱藏的自動(dòng)的格式化
		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被格式化兩次,第一次使用在一個(gè)print的重載中

第二次使用在使用了tostring方法的java編譯器生成的的自動(dòng)轉(zhuǎn)換代碼中

通過(guò)這種方式你可以格式化任何值,但是你對(duì)結(jié)果沒(méi)有任何控制權(quán)(重點(diǎn)是你對(duì)格式化的結(jié)果沒(méi)有控制權(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方法基于格式化的字符串格式化多個(gè)參數(shù)。 格式字符串由嵌入了格式說(shuō)明符的靜態(tài)文本組成。

除格式說(shuō)明符外,格式字符串的輸出保持不變。(簡(jiǎn)單點(diǎn),格式符號(hào)起到占位的作用,其他的字符正常輸出)

格式字符串支持許多功能。 在本教程中,我們將僅介紹一些基礎(chǔ)知識(shí)。 有關(guān)完整說(shuō)明,請(qǐng)參閱API規(guī)范中的格式字符串語(yǔ)法。

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://所有格式說(shuō)明符都以%開(kāi)頭,并以1或2個(gè)字符的轉(zhuǎn)換結(jié)尾,該轉(zhuǎn)換指定要生成的格式化輸出的種類

注意:

除%%和%n外,所有格式說(shuō)明符必須與參數(shù)匹配。 如果沒(méi)有,則拋出異常。

原文:

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編程語(yǔ)言中,\ n轉(zhuǎn)義始終生成換行符(\ u000A)。 除非特別需要換行符,否則請(qǐng)勿使用\ n。 要為本地平臺(tái)獲取正確的行分隔符,請(qǐng)使用%n。(這里的言外之意是,一個(gè)是生成轉(zhuǎn)義字符,一個(gè)是格式化占位符,兩者有本質(zhì)區(qū)別,雖然在程序中看起來(lái)實(shí)現(xiàn)了一樣的效果。)

以上這篇java自定義Scanner類似功能類的實(shí)例講解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論