package day17_io;

/*

2.

- 회원아이디,비밀번호,이메일에 대한 정보를 갖는 클래스를 만들고 member.data파일로 저장하세요.

- 조회할 회원의 비밀번호와 이메일주소를 입력받아 회원아이디를 출력해 보세요.

회원아이디는 앞글자 3자만 보여지고 나머지는 *로 채워집니다.

==> ObjectInputStream,ObjectOutputStream을 사용합니다.

*/

import java.io.Serializable;

import java.util.Scanner;

import java.io.EOFException;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

class Account implements Serializable {

private String id;

private String pw;

private String email;

 

 

public Account(String id, String pw, String email) {

this.id=id;

this.pw=pw;

this.email=email;

}

public String getId() {return id;}

public String getPw() {return pw;}

public String getEmail() {return email;}

}

public class Task2 {

public static void main(String[] args) {

try {

output();

input();

}catch(ClassNotFoundException ce) {

System.out.println(ce.getMessage());

}catch(IOException ie) {

System.out.println(ie.getMessage());

}

}

public static void output() throws IOException {

 

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("member.data"));

oos.writeObject(new Account("jhta123","a12345","java@jhta.net"));

oos.writeObject(new Account("jhta1234","b12345","jsp@jhta.net"));

oos.writeObject(new Account("jhta12345","c12345","spring@jhta.net"));

oos.close();

System.out.println("회원아이디,비밀번호,이메일 정보를 담는 객체 저장완료..");

}

public static void input() throws IOException,ClassNotFoundException{

Scanner scan = new Scanner(System.in);

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("member.data"));

System.out.println("조회 할 회원님의 아이디를 찾기위해 비밀번호와 이메일주소를 입력하세요.");

System.out.print("검색할 ID의 비밀번호:");

String searchPw = scan.next();

System.out.print("검색할 ID의 이메일주소:");

String searchEmail = scan.next();

 

while(true) {

try {

Account ob = (Account)ois.readObject();

//꺼내오는 내용의 데이터 타입이 Account 타입인데 Object타입으로 받았으므로 자식메소드못씀->형변환필요

String fullId = ob.getId(); // 아이디 전체 문자열

String showingId = fullId.substring(0,3);// 앞 세자리 3자리(뒤에 '3'은 범위에 포함안됨)

//substring: 문자열에서 해당범위에있는 문자열을 반환

int markId = fullId.length()-3; // 3자리 아이디표시 이후 4번째 자리부터의 문자열길이

char[] ch = new char[markId]; //* 표시를 저장하기위한 공간(배열)을 생성

for(int i =0; i<markId; i++){

ch[i]='*';

}

String star = String.valueOf(ch);

//valueOf() 메소드는 ()괄호 안의 해당 객체를 String 객체로 변환시키는 역활을 합니다. 말그대로 String의 객체로 형변환입니다.

if(searchPw.equals(ob.getPw()) && searchEmail.equals(ob.getEmail())) { //논리연산자 and(&&)

System.out.println("회원님의 아이디:"+showingId+ star+" "+"입니다.");

break;

}

}catch(EOFException ee) {

System.out.println("일치하는 회원이 존재하지 않습니다...");

//java.io.EOFException; (IOExeption에 포함)파일의 끝에 도달했을 때 발생

break;

}

}

}

}

Task2.java
0.00MB
Task1.java
0.00MB

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package day17_io;
 
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
import java.io.IOException;
 
/*
 * 1. 학생번호,이름,전화번호를 키보드로 입력받아 student.data파일로 저장하세요.
   student.data파일의 학생정보를 모두 출력해 보세요.
   ==> DataOutputStream,DataInputStream사용
 */
 
public class Task1 {
    public static void main(String[] args) {
        try {
            int count = output();
            input(count);
        } catch (IOException ie) {
            System.out.println(ie.getMessage());
        }
    }
 
    public static int output() throws IOException {
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("student.data"));
        System.out.println("전체학생정보를 출력하기 위해 학생정보를 입력하세요.");
        Scanner scan = new Scanner(System.in);
        System.out.println("입력할 학생 수를 입력하세요.");
        int count = scan.nextInt();
        for(int i=1; i<=count; i++) {
            System.out.print(i+"번째 학생번호를 입력하세요:");
            dos.writeUTF(scan.next());
            System.out.print(i+"번째 학생이름을 입력하세요:");
            dos.writeUTF(scan.next());
            System.out.print(i+"번째 학생 전화번호를 입력하세요:");
            dos.writeUTF(scan.next());
        }
        dos.close();
        scan.close();
        return count;
    }
    public static void input(int count) throws IOException{
        DataInputStream dis = new DataInputStream(new FileInputStream("student.data"));
        System.out.println("<< 전체학생정보 >>");
            for(int i=1; i<=count; i++) {
                String readNum = dis.readUTF();
                String readName = dis.readUTF();
                String readTel = dis.readUTF();
                System.out.println(i+"번째 학생번호:"+readNum);
                System.out.println(i+"번째 학생이름:"+readName);
                System.out.println(i+"번째 전화번호:"+readTel);
                System.out.println("========================");
        }
            dis.close();
    }
}
 
cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package day15_io;
 
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
 
/*1. 키보드로 입력받은 문자열이 파일로 생성되게 하기
 ## test.txt
예)
 hello!
 my name is hong gil dong.
 */
 
/* 1)required method
 *         public FileWriter(String fileName) throws IOException
 */
 
public class Task1 {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        FileWriter fw = null;
        try {
            fw = new FileWriter("test.txt",true);
            System.out.println("Write any content that will be saved in the 'test.txt'.");
            while(true) {
                String str = scan.next();
                if(str.equals("exit")) {
                    break;
                }
                fw.write(str);                
            }
            System.out.println("A file is created.");
        }
        catch(IOException ie) {
            System.out.println(ie.getMessage());
        }finally {
            try {
                fw.close();
            }catch(IOException ie) {
                System.out.println(ie.getMessage());
            }
        }
    }
}
cs
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package day15_io;
 
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
 
/*
 * 2. 프로그램을 실행하면 test.txt을 읽어와서 모두 대문자로 
 변환해서 upper_test.txt파일이 생성되도록 만들어 보세요.
예)
 ## upper_test.txt
HELLO!
MY NAME ...
 */
//Pseucode; read test.txt->toUpperString->create a upper_test.txt file including the changed contents. 
public class Task2 {
    public static void main(String[] args) {
//public FileReader(String fileName) throws FileNotFoundException
//public static char toUpperCase(char ch)
//public FileWriter(String fileName) throws IOException
//public void write(String str) throws IOException        
        FileReader fr = null;
        FileWriter fw = null;
        int ch = 0;
        System.out.println("프로그램이 실행되었습니다.");
        try {
            fr = new FileReader("/Users/Home/eclipse-workspace/day15_io/test.txt");
            fw = new FileWriter("upper_test.txt");
            while(true) {
                    ch = fr.read();
                    if(ch==-1) {
                        break;
                    }
                    fw.write(Character.toUpperCase(ch));
                }
            }
        catch(FileNotFoundException fe) {
            System.out.println(fe.getMessage());
        }catch(IOException ie) {
            System.out.println(ie.getMessage());
        }finally {
            try{
                fr.close();
                fw.close();
            }catch(IOException ie) {
                System.out.println(ie.getMessage());
            }
        }
    }
}
 
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package day15_io;
 
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
 
/*
 * 3.읽어올 파일명을 입력받아 해당 파일의 내용을 화면에 출력해 보세요.
예)
읽어올 파일명 입력
c:\java\아리랑.txt
 
==> 아리랑.txt파일을 화면에 출력합니다.
아리랑 아리랑 아라리요
아리랑 고개로 넘어간다...
나를 버리고 가시는 님은...
 */
public class Task3 {
    public static void main(String[] args) {    
    //public FileReader(String fileName) throws FileNotFoundException
        FileReader fr = null;
        Scanner scan = new Scanner(System.in);
        System.out.println("읽어 올 파일명을 입력하세요.");
        try {
            String name = scan.next();
            fr = new FileReader("name");
            int n  = fr.read();
            while(true) {
                if(n==-1) {
                    break;
                }
                System.out.print((char)n);
            }
        }catch(IOException ie) {
            System.out.println(ie.getMessage());
        }finally {
            try {
                fr.close();
            }
            catch(IOException ie) {
                System.out.println(ie.getMessage());
            }
        }
    }
}
 
cs

질문사항

1.

문제 1번)

사용자로부터 문자열 입력받을 때

공백 또는 엔터버튼 까지만 저장되고 끝난다.

->띄어쓰기를 포함한 문자열을 파일에 저장하는 방법.

 

*1-Solution

(next()와 nextLine()차이)

 

2.

문제 3번)

FileReader 생성 시, 매개변수 값으로 읽어올 파일의 경로? 파일명? 구분 어떻게 하는지 

송다슬_task1.txt
0.00MB

 

/*
  사원클래스 
                   [ 사원이름,부서 ]
             |                            |
             |                            |
        정규사원                        임시사원
  [사원번호,직책,급여(본봉+수당)]    [주민번호,급여(근무시간*시급)]

부모클래스(직장)

필드->이름,부서
정규사원(자식1)클래스super(사원이름/부서)+사원번호,직책,급여(본봉+수당)
임시사원(자식2)클래스super(사원이름/부서)+주민번호,급여(근무시간*시급)
멤버변수(필드)->이름,부서,번호,직책,급여(본봉,수당,근무시간,시급)
정규사원클래스메소드(급여계산(본봉+수당))
임시사원클래스메소드(급여계산(근무시간*시급))
*/
class Office{
protected String name;
protected String department;

public Office(String name, String department){
this.name = name;
this.department = department;
}
public String getName(String name){
return name;
}
public String getDepartment(String department){
return department;
}
}
class Employee extends Office{
protected String position;
protected int number;
protected double salary;
protected double regularSalary;
protected double extraPay;

public Employee(String name, String department, String position, int number, double regularSalary, double extraPay){
super(name, department);
this.position = position;
this.number = number;
this.salary = salary;
}
public String getPosition(String position){
return position;
}
public int getNumber(int number){
return number;
}
public double getSalary(double regularSalary, double extraPay){
salary = regularSalary + extraPay;
return salary;
}
}
class Employee2 extends Office{
protected long residentNumber;
protected double salary;
protected int hour;
protected double hourlyWage;

public Employee2(String name, String department, long residentNumber, int hour, double hourlyWage){
super(name, department);
this.residentNumber = residentNumber;
this.hour = hour;
this.hourlyWage = hourlyWage;
}
public long getResidentNumber(long residentNumber){
return residentNumber;
}
public double getSalary(int hour, double hourlyWage){
salary = hour*hourlyWage;
return salary;
}
}
class Task12 {
public static void main(String[] args) {
Employee emp = new Employee("송다슬", "Backend", "Staff", 20201101, 2000000.0, 300000.0);
Employee2 emp2 = new Employee2("Alexandra", "Accounting", 199608142892422L, 8, 8350.0);

System.out.println("<<정규사원>>");
System.out.println("사원이름:" + emp.getName("송다슬"));
System.out.println("부서:" + emp.getDepartment("Backend"));
System.out.println("사원번호:" + emp.getNumber(20201101));
System.out.println("직책:" + emp.getPosition("Staff"));
System.out.println("급여:" + emp.getSalary(2000000.0, 300000.0)+  " " +"Won");
System.out.println(" ");
System.out.println("<<임시사원>>");
System.out.println("사원이름:" + emp2.getName("Alexandra"));
System.out.println("부서:" + emp2.getDepartment("Accounting"));
System.out.println("주민번호:" + emp2.getResidentNumber(199608142892422L));
System.out.println("급여:" + emp2.getSalary(8, 8350.0)+ " " +"Won");
}
}

9일차 문제풀이.txt
0.00MB

Task1 


1. 학생답안을 입력받아 학생의 점수를 출력해 보세요.  
   정답은 아래와 같다.
   int answer[]={1,2,3,4,3,2,4,3,1,4};
   예)
  학생답입력
  1,3,3,4,1,1,1,1,1,1

  점수:40점
  int submission[][]=new int[5][11]; // [10]자리에 맞은 갯수 별 +10점 합산
  ==> 학생수는 다섯명으로 만들어주세요.

Task1

 

Task2

 

2. 임의의 정수를 입력받아 사용자정의 메소드를 사용해서 절대값을 구해 보세요.

Task2

Task3

배열의 전체요소를 거꾸로 출력하는 사용자 정의 메소드를 만들고 사용해 보세요.(배열요소값을 거꾸로 변
경하는것이 아니라 뒤에서부터 출력만 하는것임)

예)
int[] a={1,2,3,4,5};
revers(a);
[출력결과]
5 4 3 2

Task3

 

 

 

10개의 입력데이터 배열 저장해서 총점.평균 및 특정조건 충족하는 수 출력

 

1. 10명학생의 점수를 입력받아 배열에 저장하고 전체 총점,평균을 구하고 점수가 80점이상인 학생수를 구해서 
출력해 보세요.

import java.util.Scanner;
class Task1{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

int[] ten = new int[10];
int tot = 0;
double avg = 0.0;
int count = 0;

System.out.println("10명의 학생 점수를 입력하시오.");

for(int i=0; i<ten.length; i++){
ten[i] = sc.nextInt();
tot += ten[i];
avg = tot/10;

if(ten[i]>=80){
count += 1;
}
}
System.out.println("전체 총점:" + tot);
System.out.println("평균:" + avg);
System.out.println("80점 이상 학생 수:" + count);
}
}

5일차_해답.zip
0.02MB
Task1.java
0.00MB

+ Recent posts