상세 컨텐츠

본문 제목

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

java

by ~지우~ 2021. 7. 13. 10:14

본문

728x90

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



<문제>

출처: java_an_introduction_to_problem_solving_and_programming_6th_edition   

 

words.txt 파일에서 "dous" 로 끝나는 단어를 출력하는 코드를 작성하면 됩니다.

주의할 점은 "dous"가 단어 중간에 있는 것은 출력하면 안되고 "dous"로 끝나는 단어만을 출력해야 한다는 점입니다.

이 문제를 해결하기 위해 contains라는 함수를 사용했습니다.

contains("dous ")처럼 함수를 사용하여 "dous" 뒤에는 아무 문자도 없는 단어만을 출력하였습니다.

 

 

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Dous {
	public static void main(String[] args) {
		String[] words = new String[87314];
		int i=0;
		Scanner inputStream = null;
		String fileName = "C:\\Users\\user\\JavaProject\\words.txt";
		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();
			words[i]=line+" ";
			i++;
		}
		for(int j=0;j<87314;j++) {
			if(words[j].contains("dous ")) System.out.println(words[j]);
		}
		inputStream.close();
		
		
	}

}
728x90

관련글 더보기

댓글 영역