자바 사용자 정의 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();
			}
		}
	}
}

자바 의 Scanner 와 Fmatting
Scanner 스캐너 와 Fmatting
Programming I/O often involves translating to and from the neatly formatted data humans like to work with.번역 이 좀 까다 롭 습 니 다.대신 이 번역 을 도와 주 시 는 것 을 환영 합 니 다.한 마디 로 하면 데 이 터 를 사람들 이 좋아 하 는 것 으로 바 꿉 니 다)
자바 플랫폼 은 이러한 잡 무 를 완성 하 는 데 도움 을 주기 위해 두 개의 API 를 제공 합 니 다.스 캔 프로그램 API 는 입력 을 데이터 비트 와 연 결 된 각 토 큰 으로 나 눕 니 다.형식 API 는 데 이 터 를 형식 이 좋 고 읽 기 쉬 운 형식 으로 조합 합 니 다.(세 심하게 보면 스캐너 스캐너 스캐너 와 포맷 fmatting 은 상 반 된 두 동작 이 고 하 나 는 분산 데이터 이 며 하 나 는 조합 수조 이다)
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:

By
default,
a
scanner
uses
white
space
to
separate
tokens.
위의 프로그램 테스트 를 통 해 Scanner 스캐너 가 특정한 분할 기호 에 따라 한 줄 한 줄 인쇄 된 데 이 터 를 알 수 있 습 니 다.
Scanner 가 다 쓰 면 바 텀 스 트림 을 닫 아야 합 니 다.
메모:클래스 가 Scanner 대상 을 처리 할 때 Scanner 를 호출 하 는 close 방법 입 니 다.Scanner 스캐너 가 흐 르 지 않 더 라 도 바 텀 스 트림 을 처 리 했 음 을 나타 내기 위해 서 는 닫 아야 합 니 다.
Scanner 는 구분자 를 사용자 정의 할 수 있다
다른 태그 구분 자 를 사용 하려 면 useDelimiter()를 호출 하여 정규 표현 식 을 지정 하 십시오.예 를 들 어 영패 구분자 가 쉼표 이 고 뒤에 빈 칸 이 있다 고 가정 합 니 다.당신 은 호출 할 수 있 습 니 다.
s.useDelimiter(",\\s*");
Scanner 스캐너 는 다양한 데이터 형식 을 지원 합 니 다.
위의 예제 에 서 는 모든 입력 표 시 를 간단 한 문자열 값 으로 봅 니 다.
Scanner 는 모든 자바 언어의 기본 형식(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.
번역문:
수천 개의 구분자 와 십 진법 기호 가 언어 환경 에 특정 되 어 있 기 때문에 우 리 는 언어 환경 을 언급 해 야 한다.따라서 스캐너 가 미국 언어 환경 을 사용 해 야 한 다 는 것 을 지정 하지 않 으 면 다음 과 같은 예 는 모든 언어 환경 에서 정상적으로 작 동 하지 못 한다.입력 데 이 터 는 일반적으로 같은 언어 환경 을 사용 하 는 원본 에서 나 오기 때문에 걱정 할 필요 가 없습니다.그러나 이 예 는 자바 튜 토리 얼 의 일부분 으로 전 세계 적 으로 배포 된다.

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.5
32,767
3.14159
1,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 방법 을 사용 한 자바 컴 파일 러 가 만 든 자동 변환 코드 에 사 용 됩 니 다.
이런 방식 을 통 해 당신 은 어떤 값 도 포맷 할 수 있 지만,당신 은 결과 에 대해 어떠한 통제 권 도 가지 고 있 지 않다.
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 규범 의 형식 문자열 문법 을 참조 하 십시오.
형식 사례:

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 escape always generates the linefeed character (\u000A). Don't use unless you specifically want a linefeed character. To get the correct line separator for the local platform, use %n.
번역문:
자바 프로 그래 밍 언어 에서\n 전 의 는 항상 줄 바 꿈 자 를 생 성 합 니 다(\u000A).줄 바 꾸 기 가 특별히 필요 하지 않 으 면\n 을 사용 하지 마 십시오.로 컬 플랫폼 에 올 바른 줄 구분 자 를 가 져 오 려 면%n 을 사용 하 십시오.(하 나 는 전의 문 자 를 만 드 는 것 이 고,하 나 는 포맷 자리 표시 자 이 며,둘 은 본질 적 인 차이 가 있다.프로그램 에서 똑 같은 효 과 를 거 둔 것 처럼 보이 지만.)
이상 의 자바 사용자 정의 Scanner 와 유사 한 기능 류 의 인 스 턴 스 설명 은 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 저희 도 많이 사랑 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기