Coding Class

231012_Java

Seungyeon.Jung 2023. 10. 17. 11:16

김성래 님 실습1 작업물

package practice_Ex05;

import java.io.*;

public class HomeWork1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// Chapter 15 입출력(I/O)
		// https://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html		
		// https://www.w3schools.com/java/java_files_read.asp
		try {	// 예외처리(exception handling)
			String fileName = "/Users/syahnn11/Documents/Workspace-Java/Study/src/practice_Ex02/Ex02_04.java";
			// 문자데이터를 입출력할 때는 문자기반 스트림(FileReader/FileWriter)을 사용한다.
			FileReader fileReader = new FileReader(fileName);	// FileReader 클래스로 fileReader를 생성.
			int data;			// 파일의 데이터.
			int row = 1;		// 행.
			
			while((data = fileReader.read()) != -1) {	// 마지막 데이터에 도달할 때까지 계속하기.
				if(row == 1) {							// 데이터의 시작에
					System.out.printf("%d ", row++); 	// row number 출력 후 +1 한다.
				}
				System.out.print((char)data);			// FileReader를 이용해서 읽어온 파일 내용을 화면에 출력.
				if(data == '\n') {						// 공백일 때.
					System.out.printf("%d ", row++);	// row number 출력 후 +1 한다.
				}
			}
			fileReader.close();							// FileReader 종료.
		} catch(IOException e) {
			System.out.println("ERROR");
		}
	}
}

 

김성래 님 실습2 작업물

package practice_Ex05;

public class HomeWork2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String para = "Once when I was six years old I saw a magnificent picture\n"
				+ "in a book, called True Stories from Nature, about the\n"
				+ "primeval forest. It was a picture of a boa constrictor in the\n"
				+ "act of swallowing an animal. Here is a copy of the drawing.\n"
				+ "In the book it said: \"Boa constrictors swallow their prey\n"
				+ "whole, without chewing it. After that they are not able to\n"
				+ "move, and they sleep through the six months that they need\n"
				+ "for digestion.\n";
		System.out.printf("어린 왕자의 첫 번째 문 :\n%s\n", para);
		System.out.printf("공백/기호를 포함한 문자의 개수는 %d개입니다.\n", para.length());
		
		int letter = 0, blank = 0;
		int a = 0, b = 0, c = 0, d = 0, e = 0, f = 0, g = 0, h = 0, i = 0, j = 0, k = 0, l = 0, m = 0, 
				n = 0, o = 0, p = 0, q = 0, r = 0, s = 0, t = 0, u = 0, v = 0, w = 0, x = 0, y = 0, z = 0;
		
		for(int init = 0; init < para.length(); init++) {
			char para_char = para.charAt(init);
			if('A' <= para_char && para_char <= 'Z' || 'a' <= para_char && para_char <= 'z') {
				letter++; 
			} else {
				blank++;
			}
		}
		
		for(int init = 0; init < para.length(); init++)	{
			char para_char = para.charAt(init);
			switch(para_char) {
			case 'a': case 'A':
				a++;
				break;
			case 'b': case 'B':
				b++;
				break;
			case 'c': case 'C':
				c++;
				break;
			case 'd': case 'D':
				d++;
				break;
			case 'e': case 'E':
				e++;
				break;
			case 'f': case 'F':
				f++;
				break;
			case 'g': case 'G':
				g++;
				break;
			case 'h': case 'H':
				h++;
				break;
			case 'i': case 'I':
				i++;
				break;
			case 'j': case 'J':
				j++;
				break;
			case 'k': case 'K':
				k++;
				break;
			case 'l': case 'L':
				l++;
				break;
			case 'm': case 'M':
				m++;
				break;
			case 'n': case 'N':
				n++;
				break;
			case 'o': case 'O':
				o++;
				break;
			case 'p': case 'P':
				p++;
				break;
			case 'q': case 'Q':
				q++;
				break;
			case 'r': case 'R':
				r++;
				break;
			case 's': case 'S':
				s++;
				break;
			case 't': case 'T':
				t++;
				break;
			case 'u': case 'U':
				u++;
				break;
			case 'v': case 'V':
				v++;
				break;
			case 'w': case 'W':
				w++;
				break;
			case 'x': case 'X':
				x++;
				break;
			case 'y': case 'Y':
				y++;
				break;
			case 'z': case 'Z':
				z++;
				break;
				
			}

		}
		
		System.out.printf("공백/기호를 제외한 문자의 개수는 %d개입니다.\n", letter);
		System.out.printf("공백과 기호의 개수는 %d개입니다.\n\n", blank);
		System.out.printf("문단 내 각각 알파벳의 개수는 아래와 같습니다.\n", a, b);
//		System.out.printf("a:%2d개\nb:%2d개\nc:%2d개\nd:%2d개\ne:%2d개\nf:%2d개\ng:%2d개\nh:%2d개\ni:%2d개\nj:%2d개\nk:%2d개\n", a, b, c, d, e, f, g, h, i, j, k);
//		System.out.printf("l:%2d개\nm:%2d개\nn:%2d개\no:%2d개\np:%2d개\nq:%2d개\nr:%2d개\ns:%2d개\nt:%2d개\nu:%2d개\nv:%2d개\n", l, m, n, o, p, q, r, s, t, u, v);
//		System.out.printf("w:%2d개\tx:%2d개\ny:%2d개\nz:%2d개\n", w, x, y, z);
		System.out.printf("a:%2d개\tb:%2d개\tc:%2d개\td:%2d개\te:%2d개\tf:%2d개\tg:%2d개\th:%2d개\ti:%2d개\tj:%2d개\tk:%2d개\n", a, b, c, d, e, f, g, h, i, j, k);
		System.out.printf("l:%2d개\tm:%2d개\tn:%2d개\to:%2d개\tp:%2d개\tq:%2d개\tr:%2d개\ts:%2d개\tt:%2d개\tu:%2d개\tv:%2d개\n", l, m, n, o, p, q, r, s, t, u, v);
		System.out.printf("w:%2d개\tx:%2d개\ty:%2d개\tz:%2d개\n", w, x, y, z);
	}

}

강태진 님 실습2 작업물

package myproject;

import java.util.Arrays;

//실습: 어린왕자 텍스트 중 'a'의 개수 세기
//-대소문자 구분 X
public class StringPrince {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//텍스트 변수에 저장
		String little = "Once when I was six years old I saw a magnificent picture in a book, "
				+ "called True Stories from Nature, about the primeval forest. "
				+ "It was a picture of a boa constrictor in the act of swallowing an animal. "
				+ "Here is a copy of the drawing.";
		
		//a갯수, 단어 갯수 변수 선언 및 초기화
		int sum_a = 0;
		int sum_space = 0;
		
		String[] alpha = new String[26];//a~z까지 들어갈 배열 선언,생성
		for(char i = 'a'; i <= 'z'; i++) {//a~z까지
			String ch = Character.toString(i);//char를 String으로 형변환
			alpha[i - 97] = ch;//초기화
		}//for
		System.out.println(Arrays.toString(alpha));//배열 출력	
		
		int[] num = new int[26];//알파벳별 갯수가 들어갈 배연 선언, 생성
		System.out.println(Arrays.toString(num));//알파벳 카운팅 배열 출력
		
		for(int i = 0; i < little.length(); i++) {//어린왕자 텍스트 읽기
			for(int j = 0; j < alpha.length; j++) {//알파벳 갯수만큼 맷칭
				String li = Character.toString(little.charAt(i));//문자열비교를위한 형변환
				if(alpha[j].equalsIgnoreCase(li))//맷칭된 알파벳이 일치하면 
					num[j]++;//맷칭된 알파벳 카운팅
			}//for
//			if(little.charAt(i) == 'a' || little.charAt(i) == 'A')//a 또는 A가 맞으면
//				sum_a++;//카운팅
//			if(little.charAt(i) == ' ')//공백 이면
//				sum_space++;//공백 카운팅
		}//for
		
//		System.out.print(sum_a);//a 갯수 누적합 출력
//		System.out.println("\n" + (sum_space + 1));// 단어의 갯수(공백 +1) 출력
		System.out.println(Arrays.toString(num));//알파벳 카운팅 배열 출력
		
		for(int i = 0; i < alpha.length; i++) {
			alpha[i] += "=" + num[i];//알파벳 배열에 카운팅 갯수 추가
		}//for
		System.out.println(Arrays.toString(alpha));//알파벳 갯수 배열 출력
		
		int[] alpha2 = new int[26];
		for(int i = 0; i < little.length(); i++) {
			char a = little.charAt(i);
			if(a >= 'a' && a <= 'z')
				alpha2[a - 97]++;
			else if(a >= 'A' && a <= 'Z')
				alpha2[a - 65]++;
		}
		System.out.println(Arrays.toString(alpha2));
		
	}//main

}//class

 

이혁준 님 실습2 작업물

package myproject;

public class AlphabetPrince {

	public static void main(String[] args) {
		 // 어린왕자 테스트 중 알파벳의 개수 세기
	    //-대소문자 구분 안 함.
	    String str = "Once when I was six years old I saw a magnificent picture in a book, called True Stories from Nature,\r\n" + "about the primeval forest. It was a picture of a boa constrictor in the act of swallowing an animal. Here is a\r\n" + "copy of the drawing.";
	    
	    //대소문자 구분 안하니 소문자만 보게 모두를 소문자화.
	    str = str.toLowerCase();
	    
	    //어린왕자 문자열을 char형 배열로 전환. 
	     char[] charArray = str.toCharArray();
	     
	     //int형 배열 count 생성.
	      int[] count = new int[99];

	    //전체 어린왕자 문자열
	            for (int i=0; i<str.length();i++) {
	            	//알파벳이면 조건 발생, 공백이나 특수 문자는 안셈
	              if (charArray[i]>='a' && charArray[i]<='z') {
	            	  //현재 알파벳의 index번호를 찾음.
 	                int index = charArray[i]-'a';
	                //count배열의 인덱스(해당 알파벳의 인덱스 번호) 번에 1만큼 계속 누적.
	                 count[index]++;
	                }
	                }
	      
	            //알파벳 순서대로 반복문.
	    for (char s = 'a'; s<='z';s++) {
	    	//현재 알파벳의 index번호를 찾음.
	      int index = s-'a';
	      //알파벳 순서대로 누적값 출력.
	      System.out.println(s+": "+count[index]+"개");
	    }
	}

}