9일차 : ArrayList, Character, String클래스, String Builder, Wrapper 클래스

ArrayList - 요소를 저장하고 저장된 데이터 꺼내와 출력

import java.util.ArrayList;//스캐너 클래스를 포함하는 java.util클래스 라이브러리의 선언 class ArrayList01{ public static void main(String[] args) { String str1=new String("진달래"); String str2=new String("개나리"); String str3=new String("봉선화꽃"); ArrayList list=new ArrayList(); //ArrayList생성 //ArrayList에 요소 저장하기 list.add(str1);//모든 요소들을 add로 다 추가할 수 있다 list.add(str2); list.add(str3); list.add(new Integer(100)); //저장된 데이터 꺼내와서 출력하기 for(int i=0; i<list.size(); i++){ Object str=list.get(i);//요소를 Object로 꺼내온 것 i번 째 요소 얻어오기 //String클래스의 메소드를 사용하기 위해 String으로 형변환 //자식클래스가 부모클래스를 참조할 때는 형변환하기! String ss=(String)str; System.out.println(str.toString() + ", 꽃이름 글자 수: "+ ss.length()); } } }

 

 

 

 

 

ArrayList - 아이디와 패스워드를 저장하고 저장된 데이터를 꺼내와 출력

import java.util.ArrayList; class Member{ private String id; private String pwd; public Member(String id, String pwd){ this.id=id; this.pwd=pwd; } public void print(){ System.out.println("id: "+id); System.out.println("pwd: "+pwd); } public String toString(){//오버라이딩 return "id: "+id+", pwd: "+pwd; } } class ArrayList02{ public static void main(String[] args) { ArrayList list=new ArrayList(); //list에 Member 객체 저장하기 list.add(new Member("kim", "1234")); list.add(new Member("hong", "0007")); list.add(new Member("happy", "8383")); //public E remove(int index) list.remove(1);//인덱스가 1인 요소 삭제(인덱스는 0부터 시작) //public E set(int index, E element) list.set(1, new Member ("song", "yyyy"));//1번 째 요소를 song, yyyy로 바꿈(song위치에 yyyy를 넣겠다) //list에 저장된 객체를 꺼내와 출력해 보세요! //public object get(int index) ==> 요소를 꺼내옴 for(int i=0; i<list.size(); i++){ Object aa=list.get(i); //Member mem=(Member)aa; //mem.print(); System.out.println(aa);//Member@해시코드로 나온다 --aa.toString이 생략되어있다(오버라이딩 하지 않은 경우) //id:kim, pwd:1234로 나오게 해주고 싶을 경우 자식 오버라이딩 해주면 된다 } } } /* id: kim, pwd: 1234 id: hong, pwd: 0007 id: happy, pwd: 8383 */

 

Character


class Character01 {
	public static void main(String[] args) {
		//public static boolean isLetter(char ch)
		//public static boolean isLowerCase(char ch)
		//public static boolean isWhitespace(char ch)
		//public static boolean isDigit(char ch)

		String str="Hello World 123";
		for(int i=0; i<str.length(); i++){
			char ch=str.charAt(i);
			if(Character.isLetter(ch)){	//문자인지 판별
				System.out.println(ch+"는 문자입니다.");
			}
			if(Character.isLowerCase(ch)){
				System.out.println(ch+"는 소문자 입니다.");
			}
							if(Character.isWhitespace(ch)){
				System.out.println(ch+"는 공백문자 입니다.");
			}
							if(Character.isDigit(ch)){
				System.out.println(ch+"는 숫자 입니다.");
							}
		}
	}
}

 

 

 

String - 문자열이 일치하는지, 다른지 판별

class String01{ public static void main(String[] args) { String str1="hello"; //상수 String str2="hello"; if(str1==str2){ System.out.println("문자열 일치"); }else{ System.out.println("문자열 다름"); } String str3=new String("hello"); String str4=new String("hello"); if(str3.equals(str4)){//두 객체의 주소값을 비교 --> 주소값은 다름. (문자열을 비교할 때는 반드시equals로 비교) System.out.println("equals메소드로 비교==>문자열 일치"); }else{ System.out.println("문자열 다름"); } } }

 

 

 

 

 

String - 문자열 길이 출력, 문자열 위치 리턴,  문자를 대문자로 변환, 문자열 얻어오기, 문자를 쪼개어 배열에 저장 등

class String02 { public static void main(String[] args) { //public String(String original) String str=new String("Hello World"); //public String(char[] value) char[] ch={'a', 'b', 'c', 'd'}; String str1=new String(ch); System.out.println("str: "+str); System.out.println("str1: "+str1); //public String(char[] value, int offset, int count) String str2=new String(ch, 1,2); //첫번째 위치에서 두 개. 배열은 0부터 시작하므로 bc의 값으로 출력됨. System.out.println("str2: "+str2); String str3="Java"; //public char charAt(int index) : index위치의 문자를 리턴 char a=str3.charAt(2); //나는 Java의 두 번째 위치의 문자를 알고싶다!(0,1,2 이므로 v가 출력) System.out.println("2번 째 위치의 문자"+a); //public int length() : 문자열의 길이 리턴 //length()메소드를 호출해서 str3의 문자열 길이를 출력해보세요. int b=str3.length(); System.out.println(str3+"의 문자열 길이: "+b); //public int indexOf(String str) : str문자열의 위치를 리턴 int c=str3.indexOf("a"); //해당 문자에 없는 문자열 입력시 -1이 출력(해당문자를 포함하고 있나없나 검사하는데도 사용) System.out.println("c: "+c); String email="aaa@daum.net"; if(email.indexOf("@")==-1){ //indexOf("")==>@가 없으면 -1리턴 System.out.println("이메일형식이 올바르지 않습니다."); }else{ System.out.println("이메일: "+email); } String id="song"; //public String toUpperCase() ==> 문자열을 대문자로 변환 String uid=id.toUpperCase(); //uid에 변환된 값이 들어가는 것 System.out.println(id + "대문자로 변환 후: "+uid); //public String substring(int beginIndex, int endIndex) String str4=email.substring(4,8); //4번 째 인덱스에서 (8-1)번째까지 문자열 얻어옴 System.out.println("str4: "+str4); //daum //public String[] split(String regex) String str5="홍길동, 김철수, 유관순"; String ss[]=str5.split(", "); //,(구분자)를 기준으로 문자열을 쪼개서 배열로 저장 for(int i=0; i<ss.length; i++){ System.out.println(ss[i]); } int n=12345; //n을 String타입으로 변환해서 출력해보세요. //public static String valueOf(int i) String sn=String.valueOf(n); //n을 문자열로 변환 System.out.println(sn); } } /* str: Hello World str1: abcd str2: bc 2번 째 위치의 문자v Java의 문자열 길이: 4 c: 1 이메일: aaa@daum.net song대문자로 변환 후: SONG str4: daum 홍길동 김철수 유관순 12345 */

 

 

 

 

String과 String Builder의 차이


class StringBuilder01 {
	public static void main(String[] args) {
		StringBuilder sb=new StringBuilder("Hello");
		//public StringBuilder append(String str)
		//StringBuilder는 원본문자열이 변경됨
		StringBuilder sb1=sb.append("안녕");	//sb1에는 변경된 값이 저장
		System.out.println(sb +"," +sb1);

		String st=new String("Hello");
		//String은 원본문자열은 절대 변경되지 않고 복사본이 생성됨
		String aa=st.concat("안녕");	
		System.out.println("st: "+st+", aa: "+aa);
		
	}
}

 

 

Wrapper 클래스

class Wrapper01{ public static void main(String[] args) { //public Integer(String s) Integer in=new Integer("100"); //멤버변수값이 출력되도록 자식 오버라이딩? System.out.println(in); //public int intValue() //Integer in1=new Integer(100); //int n=in1.intValue(); //정수로 바꾸기 Integer in2=100; //가능! (오토박싱 jdk5.0이상 지원) in2=new Integer(100); int n=in2; //가능! (언박싱) System.out.println(in2+","+n); //public static int parseInt(String s) ==>문자열을 int형으로 변환해서 리턴 String ss="100"; //ss를 int형으로 바꾸세요~ int a= Integer.parseInt(ss); System.out.println(a+2);//100+2 //public static String toBinaryString(int i) String ss1=Integer.toBinaryString(100); System.out.println(100+": 의 2진수: "+ss1); //public static double parseDouble(String s) double d=Double.parseDouble("12.2345"); System.out.println(d); } }

 

 

 

 

 

 

[ 과 제 ]