조컴퓨터

200826 OOP 10 - Java 객체지향 프로그래밍(Ⅰ) 본문

자바 웹개발자 과정/JAVA

200826 OOP 10 - Java 객체지향 프로그래밍(Ⅰ)

챠오위 2020. 8. 27. 09:52

Java에서 Static은 보통 변수나 메소드 앞에 static 키워드를 붙여서 사용하는데, 이때 static을 사용한 변수를 클래스 변수라 한다. static 변수와 static 메소드는 static 메모리 영역에 존재하므로 객체가 생성되기 이전에 이미 할당되어 있다. 즉, 객체가 아닌 클래스 변수이기 때문에 객체를 생성(new)하지 않아도 사용가능하다.

 

static은 다음과 같은 특징이 있다.

 

클래스를 설계할 때, 멤버변수 중 모든 인스턴스에 공통적으로 같은 값을 유지해야 하는 것에 static을 붙인다.

   - 인스턴스를 생성하면, 각 인스턴스들은 서로 독립적이기 때문에 서로 다른 값을 유지한다.

 

static이 붙은 멤버변수는 인스턴스를 생성하지 않아도 사용할 수 있다.

   - static이 붙은 멤버변수(클래스 변수)는 클래스가 메모리에 올라갈 때 자동으로 생성되기 때문이다.

 

static이 붙은 메소드에서는 인스턴스 변수를 사용할 수 없다.

   - 인스턴스 변수가 존재하면 static이 붙은 변수가 이미 메모리에 존재한다는 뜻. 그러나 static이 붙은 메소드에서는 인스턴스 변수가 존재하지 않을 수 있다.

 

메소드 내에서 인스턴스 변수를 사용하지 않는다면 static을 사용하는 것을 고려한다.

   - 메소드의 작업 내용 중에서 인스턴스 변수를 필요로 하면, static을 붙일 수 없다. 반대로 인스턴스 변수를 필요로 하면, static을 붙이는 것이 좋다. 메소드 호출시간이 짧아지기 때문에 효율이 높아진다.

 

 

static 공간 → continue

stack 공간 → reset

 

클래스 변수는 JVM의 Method Area에 들어간다. 이때의 객체는 Heap Area에 들어간다.

 

 

 

Static 변수(정적 변수)

- 메모리에 한 번 생성되어 프로그램이 종료될 때 소멸하는 변수

- 객체를 만들기 전에 초기화가 되므로 멤버 메소드 안에 선언할 수 없다.

- 최초 사용 요청 시 한 번만 메모리 할당(#100번지)을 받고 모든 객체가 이 메모리를 공유한다. 그러나 인스턴스 변수(지역 변수)는 객체 생성 시마다 메모리를 새롭게 할당받는다.

- 기본적으로 모든 클래스는 new를 이용하여 메모리를 할당한 후 사용이 가능하지만, Static 변수와 메소드는 new를 이용하여 객체를 만들지 않고도 사용 가능하다.

- 프로그램 내에서 값이 변하지 않는 상수나 모든 객체가 공유하는 변수의 값을 유지할 때 사용한다.

- 자주 생성이 필요한 객체의 경우에는 Static 객체 형식으로 생성하면 객체가 하나만 메모리에 생성되므로 처리 속도를 향상시킬 수 있다.

- 특정 객체에서 값을 수정하게 되면 다른 모든 객체들이 수정된 값을 사용하게 된다.

- 같은 프로그램 내의 어디서나 접근할 수 있는 전역 변수의 성격을 갖는다.

 

System.out.println(Calendar.YEAR);	//1	
System.out.println(Calendar.MONTH);	//2
System.out.println(Calendar.DATE);	//5

System.out.println(Calendar.HOUR);	//10
System.out.println(Calendar.MINUTE);	//12
System.out.println(Calendar.SECOND);	//13

 

 

 

Static 메소드 : new연산자를 이용해서 별도의 객체 생성 없이 사용가능하다. 보통 Static 메소드는 유틸리티성 메소드를 작성할 때 많이 사용된다. 예를 들어, "날짜 구하기", "글자 사이에 콤마 추가하기" 등의 메소드를 작성할 때 클래스 메소드를 사용하는 것이 좋다. 

 

//static은 클래스명으로 직접 접근가능하다
//->클래스.변수
//->클래스.함수()

System.out.println(Math.PI);	//static변수는 대문자로 많이 준다
System.out.println(Math.abs(3));//static

//에러
Math math=new Math();
System.out.println(math.PI);
System.out.println(math.abs(3));

 

 

예제) 

 

package oop0826;

import java.util.Calendar;

class Sawon{
	//멤버 변수 field
	String sabun;//사원번호
	String name;//이름
	int pay;//급여
		
	//생성자 함수 constructor
	public Sawon() {}//Package도 가능 Sawon(){}

	//생성자 함수
	public Sawon(String sabun, String name, int pay) {
		this.sabun = sabun;
		this.name = name;
		this.pay = pay;
	}//Sawon() end	
	
	//static변수(오늘은 함수 method를 사용x)
	static String COMPANY="(주)솔데스크";	//RAM공간에 static변수가 입력됨
	static int SUDANG=10;
	static double TAX=0.03;
	
	//static함수
	static void line() {
		System.out.println("---------");
	}//end
	
}//class end


public class Test01_static {
	public static void main(String[] args) {
		//static
		//->함수, 변수(정적변수)
		//->메모리 생성 1번, 소멸도 1번 된다.
		//->new연산자를 이용해서 별도의 객체 생성 없이 사용가능하다

		//static변수와 함수는 클래스명으로 직접 접근한다
		
		System.out.println(Sawon.COMPANY);
		System.out.println(Sawon.SUDANG);
		System.out.println(Sawon.TAX);
		Sawon.line();

		/*
        	(주)솔데스크
		10
		0.03
        	*/
		
//--------------------------------------------------------------------	
		//1)static의 특징을 적용하지 않는 경우(비추)
		//new 생성자함수() -> 객체(Object)
		//one -> 참조변수
		
		Sawon one=new Sawon("1001", "개나리", 100);
		//나의 세금
		double myTax=one.pay*one.TAX;
		//나의 총지급액=급여-세금+수당
		int total=(int)(one.pay-myTax+one.SUDANG);
		
		System.out.println("회사:"+one.COMPANY);
		System.out.println("사번:"+one.sabun);
		System.out.println("이름:"+one.name);
		System.out.println("총지급액:"+total);
		one.line();

		/*
        	회사:(주)솔데스크
		사번:1001
		이름:개나리
		총지급액:107
		*/
        
//--------------------------------------------------------------------
		//2)static의 특징을 적용한 경우(강추)
		//->static변수와 함수는 이미 static 메모리에
		//->값이 상주해 있기 때문에 별도의 객체 생성을
		//->하지 않고도 바로 접근할 수 있다
		
		Sawon two=new Sawon("1002", "진달래", 200);
		myTax=two.pay*Sawon.TAX;
		total=(int)(two.pay-myTax+Sawon.SUDANG);
		System.out.println("회사:"+Sawon.COMPANY);
		System.out.println("사번:"+two.sabun);
		System.out.println("이름:"+two.name);
		System.out.println("총지급액:"+total);
		two.line();
		
		
//--------------------------------------------------------------------
		//static변수의 연산 (continue)
		//static변수는 생성도 1번, 소멸도 1번
		//주소를 공유한다
		Sawon kim=new Sawon("1003", "무궁화", 300);
		Sawon lee=new Sawon("1004", "봉선화", 400);
		
		System.out.println(kim.SUDANG);//10
		System.out.println(lee.SUDANG);//10
		
		//SUDANG=10+1=11
		kim.SUDANG=kim.SUDANG+1;
		System.out.println(kim.SUDANG);//11
		
		//static이라는 공간은 하나의 칸을 만들어 같이 사용 (SUDANG이라는 한 칸을 같이 사용)
		//heap에서는 new 생성연산자()를 입력하면 그에 해당하는 각각의 공간을 마련
		//SUDANG=11+1=12        
		lee.SUDANG=lee.SUDANG+1;
		System.out.println(lee.SUDANG);//12	
									   
		//(추천)페이지가 다량으로 많아질 때에도 같은 값을 공유해야 하는 일이 있기 때문에
		//static이라는 공간을 활용
		Sawon.SUDANG=Sawon.SUDANG+1;//12+1=13
		System.out.println(Sawon.SUDANG);//13
		System.out.println(kim.SUDANG);	 //13
		System.out.println(lee.SUDANG);	 //13	
		

	}//main() end
}//class end

 

 

 

final 예약어

- 마지막의, 변경될 수 없는

- 상수(constant)의 의미, 상수의 이름은 모두 대문자로 하는 것이 관례

- 적용 분야 : 변수, 메소드, 클래스

 

1) 변수에 final을 적용할 때

- final로 지정된 변수는 값을 변경할 수 없는 상수가 된다.

- 프로그램이 끝날 때까지 변수값을 변경하지 못하는 상수화

 

2) 메소드에 final을 적용할 때

- 상속 관계에 따른 오버라이딩 확장을 할 수 없음

- 리폼 불가능(재정의 할 수 없음)

 

3) 클래스에 final을 적용할 때

- 더 이상 상속을 허용하지 않는 종단 클래스

- 다른 클래스의 조상이 될 수 없다.

- 더 이상 물려주지 말고 너만 사용해라!

 

package oop0826;

import java.util.Calendar;

//1)final 클래스(종단클래스)
final class Animal{}//class end
/*	에러
	final클래스를 상속받을 수 없다
class Elephant extends Animal{}//Animal클래스가 종단클래스이므로 에러
*/

//2)final 메소드
class Fruit{
	void view() {}
	final void disp() {}
}//class end

class Apple extends Fruit{
		  //부모클래스 Fruit
	
	@Override //<-annotation
			  //<-재정의(리폼)
	void view() {}
	
	/*에러. final 메소드는 더이상 override할 수 없다
	@Override
	void disp() {}
	*/
	
}//class end


public class Test02_final {
	public static void main(String[] args) {
		//final 마지막
		//변수   : 변수의 상수화
		//함수   : 더이상 리폼(override재정의)할 수 없다
		//클래스 : 종단클래스. 부모클래스가 될 수 없다
		
		int a=3;
		a=5; //다른 값으로 대입 가능
		
		final int b=2; //변수의 상수화
		//b=4; //에러
		//final 변수는 다른 값으로 대입 불가능
		
		//static final int YEAR=1
		System.out.println(Calendar.YEAR); //SF
			
	}//main() end
}//class end

 

 

 

this( ), this

 

- 현재 객체의 생성자 함수를 의미한다.

- this( ); 생성자 함수를 가리키는 대명사

- this( ); 일반 메소드에서는 생성자 함수를 호출할 수 없다.

           단, 생성자 함수에서는 일반 메소드를 호출할 수 있다.

- 생성자 함수에서 다른 생성자 함수를 호출할 때 사용

- this( )는 생성자 함수끼리만 호출 가능

- 생성자의 이름으로 클래스 이름 대신 this를 사용

- 주의할 점 : 한 생성자에서 다른 생성자를 호출할 때는 반드시 첫 행에 정의해야 한다.

 

package oop0826;

class Sungjuk{//Sungjuk클래스가 package oop0825에 있으나 package 단위가 다르기 때문에 에러X
	private String name;
	private int kor, eng, mat;
	private int aver;
	
	public Sungjuk() {//기본생성자함수 default constructor    
		//생성자함수가 다른 생성자함수를 호출할 수 있다
		//Sungjuk("개나리"); //에러
		this("개나리");
	}//end
	
	public Sungjuk(String name) {
		this.name=name;
		//this.멤버변수field=매개변수parameter
	}//end
	
	public Sungjuk(int kor, int eng, int mat) {
		this("홍길동");
		this.kor=kor;
		this.eng=eng;
		this.mat=mat;
		//this("홍길동"); //에러
		//->생성자함수를 호출하는 경우에는 첫 줄에서 호출한다
	}//end

	public Sungjuk(int aver) {
		disp();//생성자함수에서는 일반 메소드 호출 가능하다
	}//end
	
	public void disp() {
		//this(85); //에러
		//->일반 메소드는 생성자함수 호출 불가능 
		//this는 자기들끼리 지칭하는 말이지 다른(제3의) 함수에서는 부를 수 없다
	}//disp() end

}//class end


public class Test03_this {
	public static void main(String[] args) {
		//this()
		//->자신의 생성자함수가 자신의 생성자함수를 호출할 때
		
		
	}//main() end
}//class end

 

 

 

Getter와 Setter 메소드

 

- private 속성의 멤버 변수는 각각 개별적으로 접근할 수 있도록 getter와 setter 메소드를 생성해 사용한다.

 

- 기본생성자 자동 생성

  Source → Generate Constructors from Superclass

 

- getter, setter 메소드 자동 생성

  Source → Generate Getters and Setters

 

- toString( ) 오버라이드 자동 생성

  Source → Generate toString( )

 

package oop0826;

class Bbs{
	private int bbsno;	//글번호
	private String writer;	//글작성자
	private String subject;	//글제목
	
	public Bbs() {}
	
	public int getBbsno() {
		return this.bbsno;
	}
	public void setBbsno(int bbsno) {
		this.bbsno=bbsno;
	}
	public String getWriter() {
		return this.writer;
	}
	public void setWriter(String writer) {
		this.writer=writer;
	}
	public String getSubject() {
		return this.subject;
	}
	public void setSubject(String subject) {
		this.subject=subject;
	}
}//class end 

class Member{
	private int memberno;	//일련번호
	private String id;	//아이디
	private String passwd;	//비밀번호
	private String email;	//이메일
	
	public Member() {}
	
	//getter과 setter함수 자동 코딩 추가
	//메뉴의 Source
	//->Generate Getters and Setters.
	public int getMemberno() {
		return memberno;
	}
	public void setMemberno(int memberno) {
		this.memberno = memberno;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPasswd() {
		return passwd;
	}
	public void setPasswd(String passwd) {
		this.passwd = passwd;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	
}//class end

public class Test04_getset {
	public static void main(String[] args) {
		//getter와 setter함수
		/*	
			함수명 작성 규칙
			is~~~() 대부분 boolean으로 반환 	//물어보는 형식. 답변: 맞아, 틀려
			to~~~() to뒤의 값으로 변환	 //(뒤에 있는 무언가를)주라. return형이 존재
			get~~() 대부분 리턴값이 존재	//가져와
			set~~() 값을 세팅할 때		//줄 때 사용. 일반적으로 void형이 존재
		*/
		
		//getter함수 작성 규칙
		//->get멤버변수의첫글자를대문자로바꾼후함수명()
		//setter함수 작성 규칙
		//->set멤버변수의첫글자를대문자로바꾼후함수명()
		
		Bbs bbs=new Bbs();
		bbs.setBbsno(1);;
		bbs.setWriter("무궁화");
		bbs.setSubject("오필승코리아");
		
		System.out.println(bbs.getBbsno());
		System.out.println(bbs.getWriter());
		System.out.println(bbs.getSubject());
		/*
			1
			무궁화
			오필승코리아
		*/
		
		
	}//main() end
}//class end

 

 

 

Wrapper(포장) 클래스

 

- 기본 자료형(byte, char, short, int, long, float, double, boolean)의 데이터 타입을 객체화한 클래스

 

- 포장 클래스는 java.lang 패키지에 포함되어 있다. 

- 포장 클래스는 첫 자를 대문자로 시작한다. 

 

기본 타입 포장 클래스
byte Byte
char Character
short Short
int Integer
long Long
float Float
double Double
boolean Boolean

 

* 포장 클래스 중에서 Integer 클래스와 Character 클래스가 기본 자료형과 이름이 다른 것을 주의하자.

 

 

- int는 하나의 정수값을 저장할 수 있다.

  Integer는 정수를 저장할 수 있을 뿐만 아니라 그 정수를 편집할 수 있는 메소드를 포함하고 있다.

- 객체지향의 속성 중 하나인 캡슐화를 지원한다.

- 단순한 값의 처리는 int를 사용한다.

 

- 참조 자료형 : new 연산자를 사용해서 객체를 선언한다.

- String 자료형은 대표적인 참조 자료형이다.

  자바의 기본 자료형은 아니다. 

  하지만 사용 빈도가 높기 때문에 기본 자료형처럼 쓰일 뿐이다.

  String의 기본 선언 형식 : String name = new String( );

 

 

예제1) Boolean형

 

boolean boo1=true;

//절판 Deprecated
Boolean boo2=new Boolean(false);//실선-절판표시
Boolean boo3=new Boolean("true");

System.out.println(boo1); //true
System.out.println(boo2); //false
System.out.println(boo3); //true

 

 

예제2) Integer형

 

int in1=3;
Integer in2=new Integer(5);
Integer in3=new Integer("7");

System.out.println(in1); //3
System.out.println(in2); //5
System.out.println(in3); //7


Integer in4=9;

System.out.println(in2.doubleValue()); 	//5.0 -> 5라는 정수를 double형 변환
System.out.println(in3.longValue());	//7L


//빨간색 s -> static의 약자
//static -> 클래스.멤버
System.out.println(Integer.toBinaryString(9));	//1001	10진수->2진수
System.out.println(Integer.toOctalString(10));	//12	10진수->8진수
System.out.println(Integer.toHexString(11));	//b	10진수->16진수
		
System.out.println(Integer.max(3, 5)); //5
System.out.println(Integer.min(3, 5)); //3
System.out.println(Integer.sum(3, 5)); //8


//★★★
//"123" -> 123
System.out.println(Integer.parseInt("123")); //123
System.out.println(Integer.parseInt("1"));   //1

 

 

예제3) Long형, Double형

 

long lo1=3L;
Long lo2=new Long(5);
Long lo3=new Long("7");
		
double dou1=1.2;
Double dou2=new Double(3.4);
Double dou3=new Double("5.6");
		

//문제)실수형 값들 중에서 정수의 합을 구하시오.
int hap=(int)dou1+dou2.intValue()+dou3.intValue();
System.out.println(hap); //9

 

 

예제4) Character형

 

char ch1='R';
Character ch2=new Character('r');
System.out.println(ch1);//R
System.out.println(ch2.toString());//r
		
//문자가 공백 문자인 경우, true를 반환하고 그렇지 않으면 false
System.out.println(Character.isWhitespace(' '));//true

System.out.println(Character.toUpperCase('n')); //N
System.out.println(Character.toLowerCase('M')); //m

 

 

 

문자열 관련 클래스

- String 클래스

- StringBuffer 클래스

- StringBuilder 클래스

- StringTokenizer 클래스 ← 과제

 

문자열 연산 속도

String < StringBuffer < StringBuilder

 

 

예제1) String형

 

String str="";
System.out.println(str.length());//0 

str=str+"ONE";
System.out.println(str); //ONE
str=str+"TWO";
System.out.println(str); //ONETWO
str=str+"THREE";
System.out.println(str); //ONETWOTHREE

str="";//모든 문자열 지우기(빈 문자열 대입)
System.out.println(str.length()); //0

 

 

예제2) StringBuilder형

 

StringBuilder sb=null;
//NullPointerException 발생
//System.out.println(sb.length());
		

sb=new StringBuilder();
sb.append("ONE");
System.out.println(sb.toString()); //ONE
sb.append("TWO");
System.out.println(sb.toString()); //ONETWO      
sb.append("THREE");
System.out.println(sb.toString()); //ONETWOTHREE
        
//모든 글자 지우기
sb.delete(0, sb.length());
System.out.println(sb.length());   //0

 

 

 

참고1) charAt( )

 

String str="Gone With The Wind";
//글자갯수
System.out.println(str.length());  //18
//0번째 문자 'G'
System.out.println(str.charAt(0)); //G
//17번째 문자 'd'
System.out.println(str.charAt(17));//d
//length() 이용해서 마지막 문자 출력
System.out.println(str.charAt(str.length()-1));//d

 

 

문제1) 대소문자를 서로 바꾸어 출력하시오. (단, Character 클래스를 활용)

 

내 답안

 

for(int i=0; i<str.length(); i++) {
	if(str.charAt(i)>='A' && str.charAt(i)<='Z') {
		System.out.print(Character.toLowerCase(str.charAt(i)));
	}else if(str.charAt(i)>='a' && str.charAt(i)<='z') {
		System.out.print(Character.toUpperCase(str.charAt(i)));
	}else {
		System.out.print(str.charAt(i));
	}//if end
}//for end
System.out.println(""); //gONE wITH tHE wIND

 

선생님 답안

 

for(int i=0; i<str.length(); i++) {
	char c=str.charAt(i);
	if(Character.isUpperCase(c)) {
		System.out.print(Character.toLowerCase(c));
	}else if(Character.isLowerCase(c)) {
		System.out.print(Character.toUpperCase(c));
	}else {
		System.out.print(c);
	}//if end
}//for end
System.out.println(""); //gONE wITH tHE wIND

 

 

 

참고2) indexOf( )

 

String str="Gone With The Wind";

//"G" 문자열의 순서 -> 0
System.out.println(str.indexOf("G"));

//중복되었다면 처음 찾은 문자열의 순서 -> 3
System.out.println(str.indexOf("e"));

//없는 문자열의 순서 -> -1
System.out.println(str.indexOf("k"));

//'n' -> 'N'으로 치환
System.out.println(str.replace('n', 'N')); //GoNe With The WiNd

 

 

참고3) isEmpty( )

 

String str="Gone With The Wind";

//문자열의 갯수가 0인지?
if(str.isEmpty()) {
	System.out.println("빈문자열이다");
}else {
	System.out.println("빈문자열이 아니다");
}//if end

//빈문자열이 아니다

 

 

참고4) startsWith( ), endsWith( ), equals( )

 

String str="Gone With The Wind";

//앞에서부터 문자열 비교
System.out.println(str.startsWith("Gone")); //true
//뒤에서부터 문자열 비교
System.out.println(str.endsWith("Wind"));   //true
		
//문자열 내용 비교
System.out.println("sky".equals("hi")); //false

 

 

참고5) substring( )

 

//문자열 일부분만 추출(★★★)

//6번째~끝까지
System.out.println(str.substring(6));    //ith The Wind
//6번째~11번째까지
System.out.println(str.substring(6, 12));//ith Th

 

문제) substring( )

 

String str="Gone With The Wind";
//문제)"The" 추출하기
System.out.println(str.substring(10, 13));
		
//문제)첫번째 문자 추출하기
System.out.println(str.substring(0, 1));
		
//문제)마지막 문자 추출하기
System.out.println(str.substring(17, 18));
System.out.println(str.substring(str.length()-1, str.length()));
System.out.println(str.substring(str.length()-1));

 

 

 

참고6) split( )

 

String str="Gone With The Wind";

//특정 문자를 기준으로 문자열 분리하기
String[] word=str.split("e");
for(int i=0; i<word.length; i++) {
	System.out.println(word[i]);
}//for end

/*
	Gon
	 With Th
	 Wind
*/

 

 

참고7) trim( )

 

//문자열 좌우 끝에 있는 공백 제거
System.out.println("#"+"   s ky    ".trim() +"#"); //#s ky#

 

 

 

연습문제1) 문자열 관련 문제

 

//오류

String name1="KOREA";
String name2=new String("KOREA");
		
if(name1==name2) {
	System.out.println("같다");
}else {
	System.out.println("다르다");
}//if end

//다르다

 

같은 "KOREA"인데 결과값은 다르다로 출력된다.

따라서 문자열의 경우에는 name1==name2이 사용되지 않는 것을 확인할 수 있다.

 

if(name1.equals(name2)) {
	System.out.println("같다");
}else {
	System.out.println("다르다");
}//if end

//같다

 

※ 문자열 내용을 비교하려면 equals( ) 메소드를 사용할 것!!

   equals( ) 메소드는 비교하고자 하는 대상의 내용 자체를 비교하지만, 

   == 연산자는 비교하고자 하는 대상의 주소값을 비교한다.

 

//wrapper 클래스도 문법 허용 (String 클래스도 한 예시)

Character ch1=new Character('r');
Character ch2='r';
		
System.out.println(ch2.toString()); //r
System.out.println(ch2); //r

 

 

 

문제1) 이메일 주소에 @ 문자가 있으면 @ 기준으로 문자열을 분리하여 출력하고

         @ 문자가 없다면 "이메일 주소 틀림" 메세지를 출력하시오.

 

/*
	출력결과
	webmaster
	soldesk.com
*/

 

내 답안

 

String email="webmaster@soldesk.com";

if(email.indexOf("@")==-1) {
	System.out.println("이메일 주소 틀림");
}else {
	String[] word=email.split("@");	//split이용
			
	for(int i=0; i<word.length; i++) {
		System.out.println(word[i]);
	}//for end
}//if end

/*
	webmaster
	soldesk.com
*/

 

 

선생님 답안 1) substring

 

String email="webmaster@soldesk.com";

System.out.println(email.substring(0, 9));
System.out.println(email.substring(10, 21));

/*
	webmaster
	soldesk.com
*/

 

선생님 답안 2) split

 

String email="webmaster@soldesk.com";

String[] word=email.split("@");
for(int i=0; i<word.length; i++) {
	System.out.println(word[i]);
}//for end

/*
 	webmaster
	soldesk.com
*/

 

선생님 답안 3) 

 

String email="webmaster@soldesk.com";

int pos=email.indexOf("@");
//System.out.println(pos); //9
System.out.println(email.substring(0, pos));
System.out.println(email.substring(pos+1, email.length()));
System.out.println(email.substring(pos+1));

/*
	webmaster
	soldesk.com
	soldesk.com
*/

 

선생님 답안 4)

 

String email="webmaster@soldesk.com";

int pos=email.indexOf("@");
//System.out.println(pos); //9

if(pos==-1) {
	System.out.println("이메일 주소 틀림");
}else {
	System.out.println("이메일 주소 맞음");
	System.out.println(email.substring(0, pos));
	System.out.println(email.substring(pos+1, email.length()));
	System.out.println(email.substring(pos+1));
}//if end

/*
	이메일 주소 맞음
	webmaster
	soldesk.com
	soldesk.com
*/

 

 

 

문제2) 주민번호 각 숫자의 전체 합을 구하시오.

 

//1+5+1+2+3+0+4+1+2+3+4+5+6=37
//substring()과 charAt()을 이용하여 결과값인 37을 구하여라

 

substring( ) 메소드를 이용하는 방법 1) 

 

내 답안

 

String jumin="1512304123456";

int hap=0;
String crop1;
int crop2;
		
for(int i=0; i<jumin.length(); i++){
	crop1=jumin.substring(i, i+1);
	crop2=Integer.parseInt(crop1);
	hap=hap+crop2;			
}//for end
System.out.println(hap); //37

 

선생님 답안

 

int hap=0;
for(int i=0; i<jumin.length(); i++) {
	//System.out.println(jumin.substring(i, i+1));
	hap=hap+Integer.parseInt(jumin.substring(i, i+1));
}//for end
System.out.println(hap);//37

 

charAt( ) 메소드를 이용하는 방법 2)

 

내 답안

 

int hap=0;
char crop1;
int crop2;
		 
for(int i=0; i<jumin.length(); i++){
	crop1=jumin.charAt(i);
			
	//crop2=Integer.parseInt(crop1);
	//System.out.println(crop2);
			
	crop2=crop1-48;	//48차이 char 1~9 -48 =0
	hap=hap+crop2;	
}//for end
System.out.println(hap); //37

 

선생님 답안

 

int hap=0;
for(int i=0; i<jumin.length(); i++) {

	//char->int : getNumericValue
	hap=hap+Character.getNumericValue(jumin.charAt(i));
    
}//for end
System.out.println(hap); //37

 

 

 

문제3-1) 파일명, 확장명을 분리해서 출력하시오.

 

/*
	출력결과
	파일명: 2020.03.10.sky
	확장명: png
*/

 

내 답안

 

String path="d:/java0812/workspace/2020.03.10.sky.png";

String a;
String b;
int c=path.lastIndexOf("/");
int d=path.lastIndexOf(".");
		
a=path.substring(c+1, d);
b=path.substring(d+1, path.length());
System.out.println("파일명: "+a);
System.out.println("확장명: "+b);

/*
	파일명: 2020.03.10.sky
	확장명: png
*/

 

선생님 답안

 

String path="d:/java0812/workspace/2020.03.10.sky.png";

//마지막 "/"기호의 위치
int last_s=path.lastIndexOf("/");
//마지막 "."기호의 위치
int last_d=path.lastIndexOf(".");

//System.out.println(last_s); //21
//System.out.println(last_d); //36

//1) path.substring()
//System.out.println(path.substring(22, 36)); //2020.03.10.sky
//System.out.println(path.substring(37));		//png

//2) path.substring()
//System.out.println(path.substring(last_s+1, last_d)); //2020.03.10.sky
//System.out.println(path.substring(last_d+1));		  //png
		
String filename=path.substring(last_s+1, last_d);
String ext=path.substring(last_d+1);
System.out.println("파일명:"+filename);
System.out.println("확장명:"+ext);

/*
	파일명:2020.03.10.sky
	확장명:png
*/

 

 

문제3-2) 확장명이 이미지 파일(png, jpg, gif)인지 확인하고, 

            이미지 파일이 맞다면 "파일이 전송되었습니다."

            아니라면 "파일을 다시 선택해 주세요."를 출력하시오.

 

내 답안

 

String path="d:/java0812/workspace/2020.03.10.sky.png";

String ext=path.substring(last_d+1);
//System.out.println(ext); //png

if(path.equals("png") || path.equals("jpg") || path.equals("gif")) {
	System.out.println("파일이 전송되었습니다.");
}else {
	System.out.println("파일을 다시 선택해 주세요.");
}//if end

//파일이 전송되었습니다.

 

선생님 답안

 

//소문자로 전부 치환해서 문자열 비교
		
String ext=path.substring(last_d+1);
ext=ext.toLowerCase();

if(ext.equals("png") || ext.equals("jpg") || ext.equals("gif")) {
	System.out.println("파일이 전송되었습니다.");
}else {
	System.out.println("이미지 파일이 아닙니다.");
}//if end

//파일이 전송되었습니다.