on
java 수업 DAY 16 // 라이브러리, static
java 수업 DAY 16 // 라이브러리, static
public class TestString { public static void main(String[] args) { // 라이브러리 String s = "Hello"; String s2 = new String("Hello"); System.out.println(s); System.out.println(s2); System.out.println(s == s2); // 참조하고 있는 방향이 같은지 char c = s.charAt(0); System.out.println(c); System.out.println("길이값: " + s.length()); String concat = s.concat("World"); System.out.println(concat); // 합연산과 비슷함 int index = s.indexOf('o'); // ()안의 문자 순서를 알고 싶다 -1한 값 System.out.println(index); String upper = s.toUpperCase(); System.out.println(upper); // 전부 대문자로 만들어 준다 String lower = upper.toLowerCase(); System.out.println(lower); // 소문자 String empty = ""; boolean isEmpty = empty.isEmpty(); // 비어있냐 System.out.println(isEmpty); String hasSpace = " asdf "; // 공백제거 String trim = hasSpace.trim(); System.out.println(trim); // asdf asdf 사이 공백은 안됨 양 옆으로 있는 공백만 String before = "before"; String after = before.replace('e', 'A'); //왼쪽에 있는 것을 찾아 오른쪽으로 바꿔줌 System.out.println(after); String sub = "Power Java"; // 공백의 기준으로 짜르고 싶을대 int indexOfSpace = sub.indexOf(' '); System.out.println(indexOfSpace); sub.substring(0, 5) // 인텍스를 알려주면 문자열을 잘라줌 // 0 ~ 5까지 필요하다 String abcd = "ABCDEFGHUHJDF"; String efg = abcd.substring(abcd.indexOf('E'), abcd.indexOf('G') + 1); System.out.println(efg); String lol = "League of Legends"; String wow = lol.replaceAll("Le", "WOW"); System.out.println(wow); } }
public class TestString2 { public static void main(String[] args) { String number = " 5647 - 3923 "; number = number.trim(); // 반환 받아야 잘린다 System.out.println(number); int index = number.indexOf('-'); String front = number.substring(0, index); System.out.println(front); String end = number.substring(index + 1, number.length()); // length or 생략 System.out.println(end); } }
class Person {} public class Main { public static void main(String[] args) { Person p = new Person(); // 버려진 인스턴스를 쓰레기라고 함 p = new Person(); // 기존에 있는 끈이 끊긴다 첫줄 인스턴스를 불러올 수 없음 // 연결 없는 인스턴스를 찾아낼 수 있고 jvm에게 치워라고 가능함 // G C 가비지 콜렉트 - 알아서 함 - 단점 인스턴스는 고정된 자리에 있지 않음 // 인스턴스의 이동을 막아야함 - GC를 사용할때 멈쳐야함 - world stop String s = "asdf"; // 공간차지 (바꾸지 못함 연산을 통해 바꾸는 것) // 문자열이 특히 쓰레기가 많이 쌓인다 s = s.toUpperCase(); // asdf와 끈이 끊기고 ASDF와 끈이 이어짐 } }
import java.util.StringJoiner; public class TestStringBuilder { public static void main(String[] args) { String a = "Hello"; a += "World"; StringBuilder sb = new StringBuilder("A"); // 문자열을 좀더 이쁘게 쓰는 것 // 빈생성자로 만드는건 첨에 빈문자로 시작 // 값을 주면 그 값으로 시작 sb.append("=에이"); //sb 반환 자기 자신을 반환 sb.append("
"); sb.append("One=1
"); sb.append("Red=빨간색"); String str = sb.toString(); System.out.println(str); String apple = "사과"; String banana = "바나나"; String carrot = "당근"; StringJoiner sj = new StringJoiner(", ", "(",")"); // 문자열 형태를 정해줄수있음. // 3개를 전달 받음 첫번째 " "는 문자 사이에 들어갈 것 문자구분 // 두번째 는 제일 앞에 붙이는것 // 마지막은 마지막에 붙이는 것 sj.add(apple); sj.add(banana); sj.add(carrot); System.out.println(sj); } }
String str 없이 바로 도 가능
String hello = "Hello";
String newHello = "Hello"; - 위에 있는 것을 참조 하더라 만들어진 것을 쓴다
System.out.println(hello == newHello); - true
String s2 = new String("Hello");
는 hello != s2
문자 합연산을 많이 하면 append를 쓰면 좋다
String a = "A";
a += "=에이"; 랑 위에 값이랑 같음
append 와 concat 과 같다고 생각하면 됨
append 주체를 적어줘야함
한번하면 자기자신을 반환
sp.append("dfd").append("qwer").append("dfdf") - 이게 가능함
스트링 빌드업은 자기 박스에서 계속 변화
ctrl space 사용해서 찾기 - 이름보고 설명보고
StringJoiner 는 하나의 문장 사이사이 전달받은 걸 넣어준다
// 콘솔 입출력 // 생년? 1960 // 월? 6 // 일? 25 // 성별 (남/여)? 여 (남 1 / 여 2, 2000년 이후는 3 /4) // 60625-2****** 본인 맞나요(Y/N)? Y -> 종료 // N -> 다시 입력해주세요 import java.util.Scanner; public class KoreanIden { public static void main(String[] args) { Scanner scan = new Scanner(System.in); boolean go = true; while (go) { System.out.print("생년? "); int year = scan.nextInt(); System.out.print("월? "); int month = scan.nextInt(); System.out.print("일? "); int day = scan.nextInt(); scan.nextLine(); System.out.print("성별(남/여)? "); String gender = scan.nextLine(); StringBuilder birth = new StringBuilder(); birth.append(year % 100); // String strYear = " " + year; // 2000년대생이 안나올경우 // birth.append(strYear.substring(2, 4)) // 위에 birth.append(year~ 삭제 if (month < 10) { birth.append("0"); birth.append(month); } else { birth.append(month); } if (day < 10) { birth.append("0"); birth.append(day); } else { birth.append(day); } birth.append("-"); if (gender.equals("남")) { if (year < 2000) { birth.append(1); } else { birth.append(3); } } else { if (year < 2000) { birth.append(2); } else { birth.append(4); } } birth.append("******"); System.out.println(birth + "본인 맞나요(Y/N)?"); String ans = scan.nextLine(); go = ans.equals("N"); if(go == true) { System.out.println("다시 입력하세요"); } } System.out.println("---종료---"); } } // 고칠려면 상당히 복잡함 그래서 객체의 형태로 하면 고치기 편함
String ddd = " " + 123; = 문자형 + 인트형 더해서 문자형으로 변환시키는 방법
반대로 문자열인 숫자를 인트형으로 바꾸는 방법
String abs = "12345";
int number = Interger.parseInt(abc) - Integer이라는 클래스가 있음 parseInt 메소드 인데 사용가능한경우 있음 interger 객체는 아닌 메소드
System.out.println(number +10); 하면 10이 더해짐
String str = String.valueof(1); 숫자형을 문자형으로 바꿔준다
lang이라는 패키지는 import를 쓰지 않아도 됨 = String, StringBuilder등등
월 입력 할때 문자열로 입력받아서 두글자인지 아니진 확인 0이 있는지 없는지 확인
// static = 정적 public class MyClass { private int a; // 필드 - 인스턴스 필요 public static int c; // 변수 앞에도 붙을 수 있음 static // 정적 변수 class 변수, 인스턴스와 관련이 없음 // class와 관련이 있음 사용할 때 대부분 클래스 이름 사용 // static 변수 한개 , 초기화 해야함 이경우는 0으로 초기화 static { // 프로그램 시작전에 선언해놓은 static를 찾고 만들어논다 System.out.println("메롱메롱"); } public MyClass(int a) { this.a = a; } public int getA() { return a; } public void setA(int a) { this.a = a; } public static void main(String[] args) { System.out.println("프로그램 시작점"); // MyClass m = new MyClass(3); // MyClass m2 = new MyClass(5); // // System.out.println(m.getA()); // System.out.println(m2.getA()); MyClass.c++; // m2도 같이 오름 // 인스턴스 사용 하지 않아도 static 변수는 사용가능 // 클래스 이름으로 바로 System.out.println(MyClass.c); // System.out.println(m2.c); } }
출력
메롱메롱
프로그램 시작점
1
public class MyClass { public static int s = 0; public void nonStaticHello() { System.out.println("Hello"); } public static void printHello() { System.out.println("Hello"); } public static void main(String[] args) { MyClass.printHello(); //가능 } }
public class MyClass2 { public int myNumber; public static int sum = 0; // 같이 공유할 수 있는 하나의 변수 // 프로그램 시작부터 존재해서 끝까지 존재 public MyClass2(int myNumber) { this.myNumber = myNumber; sum += myNumber; } public static int getSum() { return sum; } }
public class TestMyClass { public static void main(String[] args) { MyClass2 m3 = new MyClass2(10); MyClass2 m4 = new MyClass2(12); new MyClass2(10); new MyClass2(14); new MyClass2(12); new MyClass2(10); System.out.println(MyClass2.sum); } }
출력
68
인스턴스를 만드는 이유 필드 값을 주고 정보값을 담아놓고 그정보로 상태변화 시키고...
복잡한 필드 필요 없고 단순한 연산 이면 static 으로 많이 쓴다 - 간단한 메소드가 필요할때 많이 쓴다
Math.abs(-5) - 수학계산을 해주는 클래스 전부 static 하게 되어 있음
프로그램에 큰 영향을 주는 변수는 public 쓰면 안됨
만약 public 쓸경우 final을 붙여주자
static 한개 - 이름은 클래스 이름 빌려쓴다
public class Circle { private int radius; public static final double PI = 3.14; // 인스턴스 만들 필요 no public Circle(int radius) { this.radius = radius; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public double getArea() { return PI * radius * radius; } }
public class TestCircle { public static void main(String[] args) { Circle c = new Circle(5); double area = c.getArea(); System.out.println(area); // System.out.println(c.PI); System.out.println(Circle.PI); System.out.println(Math.PI); // 3.141592653589793 } }
출력
78.5
3.14
3.141592653589793
// static는 필드에 접촉하는 것이 말이 안됨
public static int getRedius() -> 안됨
Redius 가 필드면
public class Car { private String color; private int speed; private int gear; // 자동차의 시리얼 번호 private int id; private static int numberOfCars = 0; // 정적변수 public Car(String color, int speed, int gear) { this.color = color; this.speed = speed; this.gear = gear; // 자동차의 개수를 증가시키고 id번호를 할당한다. numberOfCars++; this.id = numberOfCars; } public String toString() { return "Car [color=" + color + ", speed=" + speed + ", gear=" + gear + ", id=" + id + "]"; } public static void main(String[] args) { Car c1 = new Car("Red", 100, 3); System.out.println(c1); } }
출력
Car [color=Red, speed=100, gear=3, id=1]
// static 정적변수를 get만들고 싶으면
public static int getNumberOfCars() {
return numberOfCars
정적인 것만 가능
간단하게 생각하면 다른 메소드나 클래스에서 쉽게 쓰기 위해서 static을 쓴다
빨간색 s - 정적인 메소드
class Beverage { public static final int COLA = 1; public static final int COFFEE = 2; public static final int MILK = 3; } public class StaticMethods { public static void main(String[] args) { String num = String.valueOf(3.4343); // 숫자를 문자형로 int i = Integer.valueOf("12345"); // 문자형을 숫자로 int userInput = 3; if (userInput == Beverage.MILK) { System.out.println("우유를 선택"); } } }
class Single { private static Single s_instance; // 하나의 인스터스, Single이라는 (즉 자기꺼) public static Single getInstance() { if (s_instance == null) { // 처음 만들땐 null이니 만든다 두번째는 null이 아니니 만들지 않는다 s_instance = new Single(); // 자기 자신을 생성 클래스 안에서 자기 인스턴스 만드는게 가능 } return s_instance; } } public class SingleTest { public static void main(String[] args) { Single obj1 = Single.getInstance(); Single obj2 = Single.getInstance(); System.out.println(obj1 == obj2); } }
출력
true
한개의 인스턴스만 만들어놓고 필요할때 연결 시켜서 쓰자 ↑
from http://hiapprendre.tistory.com/30 by ccl(A) rewrite - 2021-12-18 22:27:30