상세 컨텐츠

본문 제목

[java] 파일 읽기 쓰기 (File I/O) 연습문제#1

java

by ~지우~ 2021. 7. 12. 17:07

본문

728x90

오늘은 「java_an_introduction_to_problem_solving_and_programming_6th_edition」 790페이지 7번 문제를 풀어보겠습니다.



<문제>

출처: java_an_introduction_to_problem_solving_and_programming_6th_edition  

 

격식을 차려야 하는 글을 쓸 때에는 약어 사용을 지양해야 합니다.

문장이 적혀진 txt파일에서 abbreviations.txt라는 파일에 쓰인 약어가 발견되면 <>로 약어를 감싸주는 코드를 작성하면 됩니다.

코드를 작성하기 전에 문장이 적혀진 txt파일과 abbreviations.txt파일을 미리 준비해주셔야 합니다.

 

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Abbreviation {

	public static void main(String[] args) {
		String[] arr = new String[100];
		String[] sen = new String[100];
		int i=0;
		Scanner inputStream = null;
		String fileName = "C:\\Users\\user\\JavaProject\\abbreviations.txt";
		System.out.println("The file contains the following lines:");
		try {
			inputStream = new Scanner(new File(fileName));
		}catch(FileNotFoundException e) {
			System.out.println("Error opening");
			System.exit(0);
		}
		while(inputStream.hasNextLine()) {
			String line = inputStream.nextLine();
			arr[i]=line;
			i++;
		}
		int len=i;
		for(int a=0;a<len;a++) {
			System.out.println(arr[a]);
		}
		inputStream.close();
		
		Scanner inputStream2 = null;
		String fileName2 = "C:\\Users\\user\\JavaProject\\sentence.txt";
		System.out.println("The file contains the following lines:");
		try {
			inputStream2 = new Scanner(new File(fileName2));
		}catch(FileNotFoundException e) {
			System.out.println("Error opening");
			System.exit(0);
		}
		while(inputStream2.hasNextLine()) {
			String line = inputStream2.nextLine();
			sen=line.split(" ");
		}
		
		for(int k=0;k<len;k++) {
			for(int l=0;l<sen.length;l++) {
				if(arr[k].equalsIgnoreCase(sen[l])) {
					sen[l]="<"+sen[l]+">";
				}
			}
		}
		for(int m=0;m<sen.length;m++) {
			System.out.print(sen[m]+" ");
		}
		inputStream2.close();
	}
}
728x90

관련글 더보기

댓글 영역