제곱 구하기
Scanner scanner = new Scanner(System.in);
double CircleVolumn; // 원부피 Pascal 표기법
// 1. 반지름을 입력받는다.
double radius = scanner.nextDouble(); // 반지름
// 구체(구의부피) = 4/3 * 파이 * 반지름(3제곱)
CircleVolumn = 4/3. * Math.PI * (Math.pow(radius, 3)); // 4 자동 형변환
// 4.0 / 3.0 으로 나눠주는게 자동 형변환이 이뤄나지 않아서 연산이 매끄러워진다.
내가 원하는 소숫점 단위로 출력하기
System.out.printf("원둘레 : [%10.2f](cm)\n", circle_length);
// 결과값 62.83(cm)
// %10은 총 10자리수를 표현하겠다 (공백, dot 포함)
타입의 형변환
/*
형변환(Type Conversion)
1. 자동형변환(암시적)
1) 연산시 : 자료형이 큰쪽으로 변환
(byte < short < int < long < float < double)
1(int) + 1.0(double)
1.0 + 1.0 => 2.0
2) 대입시 : 좌변항측으로 변환(단 좌변항 > 우변항)
float f = 10;
f = 10f; (float 상수선언 : 값 F)
int n = 10.5;(X)
2. 강제형변환(명시적)
int i = (int)10.5;
// i의 값은 double로 형변환이 되어도 10으로 저장이 된다.
*/
// byte + byte -> int
// short + short -> int
// int + long -> long
// int + float -> float
byte b1 = 1;
byte b2 = 2;
// byte b3 = b1 + b2;
// int 보다 작은 자료형끼리 연산한 결과는 int가 나온다.
byte b3 = (byte)(b1 + b2);
short s1 = 1;
short s2 = 2;
// short s3 = s1 + s2;
// int 보다 작은 자료형끼리 연산한 결과는 int가 나온다.
short s3 = (short)(s1 + s2);
char to String (문자를 문자열로 변경하는 방법)
char ch = 'K';
String str = ch + "";
char ch = 'A';
char[] arrChar = new char[] {'a', 'b', 'c' };
String str = String.valueOf(ch);
String str2 = String.valueOf(arrChar);
char ch = 'A';
String str = Character.toString(ch);
String str2 = new Character(ch).toString();
2차원 배열
String [][] ganji_array = {
{"경","신","임","계","갑","을","병","정","무","기"},{"신","유","술","해","자","축","인","묘","진","사","오","미"}
};
return String.format("%s%s년", ganji_array[0][ganji_index1], ganji_array[1][ganji_index2]);
// 배열 : 동일한 자료형이 연속할당되는 자료구조(인접리스트)
public static void main(String[] args) {
// 고정길이배열
// 행 열
int [][] mm = new int[3][4];
MyArray2.display(mm);
// 가변길이배열(행마다 열의 갯수가 틀린배열)
int [][] mm2 = new int[3][];
mm2[0] = new int[2];
mm2[1] = new int[3];
mm2[2] = new int[4];
System.out.println("---[가변길이배열]---");
MyArray2.display(mm2);
// 2차원배열 초기화
int [][] mm3 = new int[][] {
{1,2},{3,4,5},{6,7,8,9}
// 0 1 2
};
MyArray2.display(mm3);
public static void display(int[][]mm) {
for(int i =0; i < mm.length; i++) { // 행첨자
for(int k = 0; k < mm[i].length; k++) { // 열첨자
System.out.printf("[%4d]", mm[i][k]);
}
System.out.println();
}
}// display-end
System.out.println("---[가변길이배열2]---");
// 테트리스
int [][] box = {
{1,1,1},
{1,1,1},
{1,1,1},
};
int [][] block_l = {
{1,0,0},
{1,0,0},
{1,1,1},
};
int [][] block_t = {
{1,1,1},
{0,1,0},
{0,1,0},
};
MyArray2.display_block(box);
MyArray2.display_block(block_l);
MyArray2.display_block(block_t);
public static void display_block(int[][]mm) {
for(int i =0; i < mm.length; i++) { // 행첨자
for(int k = 0; k < mm[i].length; k++) { // 열첨자
if(mm[i][k] == 1) {
System.out.print("■");
} else {
System.out.print("□");
}
}
System.out.println();
}
}// display-end
- 객체를 오름차순, 내림차순 배열로 나타내기
@Override
public int compare(Grade o1, Grade o2) {
int result = 0;
if(sort_field == SORT_FIELD_NAME) {
if(o1.getName().compareTo(o2.getName()) > 0) result = 1;
else if(o1.getName().compareTo(o2.getName()) < 0) result = -1;
}else if(sort_field == SORT_FIELD_KOR) {
if(o1.getKor() > o2.getKor()) result = 1;
else if(o1.getKor() < o2.getKor()) result = -1;
}else if(sort_field == SORT_FIELD_ENG) {
if(o1.getEng() > o2.getEng()) result = 1;
else if(o1.getEng() < o2.getEng()) result = -1;
}else if(sort_field == SORT_FIELD_MATH) {
if(o1.getMath() > o2.getMath()) result = 1;
else if(o1.getMath() < o2.getMath()) result = -1;
} else if(sort_field == SORT_FIELD_ALL) {
if(o1.getTotal() > o2.getTotal()) result = 1;
else if(o1.getTotal() < o2.getTotal()) result = -1;
}
if(sort_method == SORT_METHOD_DESC)
result = -result;
return result;
}
-enum
public static void main(String[] args) {
FRUIT pear = FRUIT.APPLE;
FRUIT pear2 = FRUIT.MANGO;
System.out.println(pear); // APPLE
System.out.println(pear.name()); // APPLE
System.out.println(pear.ordinal()); // 0
System.out.println(pear2.ordinal()); // 2
FRUIT [] fruits = FRUIT.values();
System.out.println(fruits[0]); // APPLE
}
public enum FRUIT {
APPLE, BANANA, MANGO
}
- 이중 for문으로 tree구조 만들기, 피라미드 만들기
https://daily-nalong.tistory.com/27
이중 for문을 이용한 피라미드 출력
누구나 한 번쯤은 마주쳤을 듯한 문제 피라미드 출력에 대한 글이다. 해당 글은 C언어를 기준으로 해서 작성했다. 우선 출력하고자 하는 피라미드의 구조가 어떻게 되어있는지 파악할 필요가 있
daily-nalong.tistory.com
hashset
public static void main(String[] args) {
Set<String> set1 = new HashSet<String>();
boolean flag1 = set1.add("kang");
boolean flag2 = set1.add("kim");
boolean flag3 = set1.add("kang");
System.out.println(set1.size());
System.out.println(flag1); // true
System.out.println(flag2); // true
System.out.println(flag3); // false
Iterator<String> iter = set1.iterator();
while(iter.hasNext()) {
String str = iter.next();
// 넥스트안에 있는 값을 꺼내줘
System.out.println(str); // kang kim
}
}
list
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("kim");
list.add("kang");
list.add("kim");
System.out.println(list.size());
for(int i = 0; i < list.size(); i++) {
String str = list.get(i);
System.out.println(str);
}
}
map
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("001", "kim");
map.put("002", "lee");
map.put("003", "choi");
map.put("001", "kang");
System.out.println(map.size());
System.out.println(map.get("001")); // 기존값을 새로운값으로 바꾼다 kang
System.out.println(map.get("002")); // lee
System.out.println(map.get("003")); // choi
Set<String> keys = map.keySet(); // key값을 set으로 받아온다.
Iterator<String> iter = keys.iterator();
while(iter.hasNext()) {
String key = iter.next();
String value = map.get(key); // key안에 있는 value값을 get으로 가져온다.
System.out.println(key + ":" + value);
}
}
date
public static void main(String[] args) {
Date date = new Date();
System.out.println(date.toString());
// Thu May 23 06:50:04 KST 2024
SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss a zzz");
System.out.println(ft.format(date)); // 형식을 커스텀하여 사용하기
// 2024.05.23 at 06:50:04 오전 KST
System.out.println(date.getTime()); // 현재 시간 가져오기
long today = System.currentTimeMillis(); // 현재 시간 가져오기
System.out.println(today);
System.out.println(today-date.getTime());
}
calendar
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
// Calendar는 추상클래스라서 생성자로 생성할 수 없다.
System.out.println(cal.get(Calendar.YEAR)); // 년
System.out.println(cal.get(Calendar.MONTH)+1); // 월
System.out.println(cal.get(Calendar.DATE)); // 일
cal.add(Calendar.HOUR, 5); // 현재 시간에 + 5
System.out.println(cal.get(Calendar.HOUR_OF_DAY)); // 12시가 최대로 표현됨
System.out.println(cal.get(Calendar.MINUTE));
}
- Calendar에서 100일을 추가한 날짜를 구하기
int yyyy = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH)+1;
int date = cal.get(Calendar.DATE);
cal.add(Calendar.DATE, 100);
String str = cal.get(Calendar.YEAR)+ "년" + cal.get(Calendar.MONTH) + "월" + cal.get(Calendar.DATE) + "일";
System.out.println(str);
time
public static void main(String[] args) {
LocalDateTime timePoint = LocalDateTime.now(); // 현재시간
System.out.println(timePoint); // 2024-05-23T07:37:49.159708200
LocalDate ld1 = LocalDate.of(2012, Month.DECEMBER, 12); // 내가 원하는 시간 넣기
System.out.println(ld1); // 2012-12-12
LocalTime lt1 = LocalTime.of(17, 18); // 17:18
System.out.println(lt1);
LocalTime lt2 = LocalTime.parse("10:15:30"); // 10:15:30
System.out.println(lt2);
LocalDate theDate = timePoint.toLocalDate();
System.out.println(theDate); // 2024-05-23
System.out.println(timePoint.getMonth()); // MAY
Month month = timePoint.getMonth();
System.out.println(timePoint.getMonthValue()); // 5
System.out.println(month.getValue()); // 5
System.out.println(timePoint.getHour()); // 7
}
io package
- byte를 하나씩 읽어오기
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("src/util/ByteExam1.java");
fos = new FileOutputStream("byte.txt");
int readData = -1;
while((readData = fis.read()) != -1) {
fos.write(readData);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
}
- byte[512]를 배열로 가져와서 한 번에 읽어오기
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("src/util/ByteExam1.java");
fos = new FileOutputStream("byte.txt");
int readCount = -1;
byte[] buffer = new byte[512];
while((readCount = fis.read(buffer)) != -1) {
fos.write(buffer,0,readCount);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
System.out.println(endTime-startTime);
- 파일을 바깥으로 출력하기
public static void main(String[] args) {
try(
DataOutputStream out = new DataOutputStream(new FileOutputStream("data.text"));
){
out.writeInt(100);
out.writeBoolean(true);
out.writeDouble(50.5);
}catch (Exception e) {
e.printStackTrace();
}
}
- 파일을 안으로 가져오기
public static void main(String[] args) {
try(
DataInputStream in = new DataInputStream(new FileInputStream("data.text"));
){
int i = in.readInt();
boolean b = in.readBoolean();
double d = in.readDouble();
System.out.println(i);
System.out.println(b);
System.out.println(d);
}catch (Exception e) {
e.printStackTrace();
}
}
- BufferedReader로 키보드로 입력받아 문자형으로 출력하는 방법
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(line);
}
- BufferedReader로 file을 새로 만들어 파일안으로 코드를 그대로 가져와 복사하기
public static void main(String[] args) {
BufferedReader br = null;
PrintWriter pw = null;
try {
br = new BufferedReader(new FileReader("src/util/CharIOExam02.java"));
pw = new PrintWriter(new FileWriter("test.txt"));
String line = null;
while((line = br.readLine()) != null) {
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
pw.close();
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
어노테이션(Annotation)
@Retention(RetentionPolicy.RUNTIME)
public @interface Count100 {
}
public class MyHello {
@Count100
public void hello() {
System.out.println("hello");
}
}
public static void main(String[] args) {
MyHello hello = new MyHello();
try {
// getClass : 해당 클래스의 인스턴스에 대한 정보를 받는다.
// 메서드의 정보를 받고, 그 정보로 부터 hello라는 메서드를 구해라.
Method method = hello.getClass().getDeclaredMethod("hello");
// count100이라는 옵션을 적용하고 있나?? -> true
if(method.isAnnotationPresent(Count100.class)) {
// annotation이 적용되었다면 100번 반복문으로 출력
for(int i = 0; i < 100; i++) {
hello.hello();
}
}else {
hello.hello();
}
} catch (Exception e) {
e.printStackTrace();
}
}
Thread 쓰레드
- Thread를 상속받아서 사용
public class MyThread1 extends Thread {
String str;
public MyThread1(String str) {
this.str = str;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(str);
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyThread1 t1 = new MyThread1("*");
MyThread1 t2 = new MyThread1("-");
t1.start();
t2.start();
System.out.println("main end!!!");
}
- Runnable를 사용해서 쓰레드 사용
Thread 클래스를 상속받지 않고, Runnable를 쓰는 이유
자바 클래스는 단일 상속밖에 되지 않는데, 그럴때에는 Thread 클래스를 상속받을 수 없기 때문에 인터페이스인 Runnable를 구현해서 사용한다.
public class MyThread2 implements Runnable {
String str;
public MyThread2(String str) {
this.str = str;
}
@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println(str);
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyThread2 t1 = new MyThread2("*");
MyThread2 t2 = new MyThread2("-");
// 쓰레드를 상속받은게 아니기 때문에, start 메서드를 사용할 수 없다.
Thread thread1 = new Thread(t1);
Thread thread2 = new Thread(t2);
thread1.start();
thread2.start();
System.out.println("main end!!!");
}
- 쓰레드의 공유객체
public class MusicBox {
public void playMusicA() {
for(int i = 0; i < 10; i++) {
System.out.println("신나는 음악!!!");
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void playMusicB() {
for(int i = 0; i < 10; i++) {
System.out.println("찬양 음악!!!");
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void playMusicC() {
for(int i = 0; i < 10; i++) {
System.out.println("카페 음악!!!");
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MusicPlayer extends Thread {
// 쓰레드를 상속받고 있다.
int type;
MusicBox musicBox;
public MusicPlayer(int type, MusicBox musicBox) {
this.type = type;
this.musicBox = musicBox;
}
@Override
public void run() {
switch (type) {
case 1:
musicBox.playMusicA();
break;
case 2:
musicBox.playMusicB();
break;
case 3:
musicBox.playMusicC();
break;
}
}
}
public static void main(String[] args) {
MusicBox box = new MusicBox();
MusicPlayer kang = new MusicPlayer(1, box);
MusicPlayer kim = new MusicPlayer(2, box);
MusicPlayer cha = new MusicPlayer(3, box);
kang.start();
kim.start();
cha.start();
}
- 쓰레드 동기화와 동기화 블럭
public class MusicBox {
// synchronized를 사용했기에, 이 메서드가 실행되면 다른 synchronized 메서드는 사용불가
public synchronized void playMusicA() {
for(int i = 0; i < 10; i++) {
System.out.println("신나는 음악!!!");
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// synchronized를 사용했기에, 이 메서드가 실행되면 다른 synchronized 메서드는 사용불가
public synchronized void playMusicB() {
for(int i = 0; i < 10; i++) {
System.out.println("찬양 음악!!!");
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
// synchronized 사용하지 않았기에 동시에 쓰레드가 실행시킨다.
public void playMusicC() {
for(int i = 0; i < 10; i++) {
// 전체 메서드를 synchronized 해주는 것이 아닌 블록을 사용해서 특정부분만 동시실행이 안되게 설정이 가능하다.
synchronized (this) {
System.out.println("카페 음악!!!");
}
try {
Thread.sleep((int)(Math.random()*1000));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public class MyThread5 extends Thread {
public void run() {
for(int i = 0; i < 5; i++) {
System.out.println("MyThread5 : " + 1);
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
MyThread5 thread = new MyThread5();
thread.start();
System.out.println("시작");
try {
thread.join();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("종료");
}
- 메서드를 wait 시키고 notify로 다시 깨우기
public class ThreadB extends Thread {
int total;
public void run() {
synchronized (this) {
for(int i = 0; i < 5; i++) {
System.out.println(i + "를 더합니다.");
total += i;
try {
Thread.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
notify();
}
}
}
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
synchronized (b) {
try {
System.out.println("b가 완료될때까지 기다립니다.");
b.wait();
}catch(Exception e) {
e.printStackTrace();
}
}
System.out.println("일어났어요 나");
System.out.println("Total is : " + b.total);
}
charAt(),대문자,소문자 변환,대문자확인으로 소문자를 대문자로, 대문자를 소문자로 바꾸는 예제
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String answer = "";
for(int i = 0; i < a.length(); i++){
char result = a.charAt(i);
if(Character.isUpperCase(result)){
answer += Character.toLowerCase(result);
} else {
answer += Character.toUpperCase(result);
}
}
System.out.println(answer);
}
}
배열을 ArrayList로 ArrayList를 배열로
[Java] 배열에서 ArrayList로, ArrayList에서 배열로 변환하기
자바에는 Collection 인터페이스를 구현하는 List, Set, Queue 계열의 자료 구조가 있다. 이 객체들을 배열로 만들거나, 배열의 데이터를 Collection 자료구조로 변환해야될 상황이 있다. 그 방법에 대해서
rachel0115.tistory.com
System.out.println("이 안에 \와 '와 "를 넣는방법") : 이걸 넣기전에 \를 넣어준다.
public class Solution {
public static void main(String[] args) {
System.out.println("!@#$%^&*(\\\'\"<>?:;");
}
}
가변인자(자바 ... 파라미터) (varargs)
자바에서는 파라미터 개수가 다르면 다른 메소드로 인식을 합니다.
동일한 기능을 하지만 파라미터가 가변적으로 변경되는 경우 오버로딩을 사용한다.
그런데 오버로딩은 파라미터 개수에 맞춰 메소드가 계속 늘어나는 구조이다.
// 파라미터가 한 개인 경우
public void search(String one) {}
// 파라미터가 두 개인 경우
public void search(String one, String two) {}
// 파라미터가 세 개인 경우
public void search(String one, String two, String three) {}
가변인자를 사용하면 동적으로 파라미터를 받을 수 있다.
사용법은 변수 타입 뒤에 기호(...)를 붙여주면 된다.
아래는 메소드를 오버로딩한 상태에서 파라미터에 가변인자를 넣어서 메소드로 생성했다.
그 결과, 메소드에서 타입을 두 개 이상 호출했을시, 가변인자를 넣은 메소드가 호출된다.
package practice;
public class BillboardMainObject {
public static void main(String[] args) {
// TODO Auto-generated method stub
// 빌보드(DTO) 객체를 생성한다.
Billboard b1 = new Billboard
(1,"Despacito",1,"https://www.billboard.com/images/pref_images/q61808osztw.jpg","luis fonsi");
Billboard b2 = new Billboard
(2,"That's What I Like",2,"https://www.billboard.com/images/pref_images/q59725qvpol.jpg","bruno mars");
Billboard b3 = new Billboard
(3,"I'm The One",3,"https://www.billboard.com/images/pref_images/q64532pl64x.jpg","dj khaled");
showAbout(b1); // 1개 객체
showAbout(b2); // 1개 객체
showAbout(b1,b2); // 2개 객체
showAbout(b1,b2,b3); // 3개 객체
// 빌보드(DTO)의 배열을 생성한다.
Billboard [] b = new Billboard[3];
// 배열안에 객체를 넣어준다.
b[0] = new Billboard
(1,"Despacito",1,"https://www.billboard.com/images/pref_images/q61808osztw.jpg","luis fonsi");
b[1] = b2; // 생성해도 좋고, 생성된 객체를 받아도 된다.
b[2] = b3;
showAbout(b[0],b[1]);
showAbout(b);
}
public static void showAbout(Billboard bb) {
System.out.println("1---------------------");
String sf = String.format("%d, %s, %d, %s, %s", bb.getRank(),bb.getSong(),bb.getLastweek(),bb.getImagesrc(),bb.getArtist());
System.out.println(sf);
}
public static void showAbout(Billboard ... b) {
System.out.println("2=====================>");
for(Billboard bill : b) {
showAbout(bill); //1
System.out.println("<======================2");
}
}
}
'java(2)↗' 카테고리의 다른 글
java Stream (0) | 2024.05.29 |
---|---|
java 2차원배열 및 알고리즘 (0) | 2024.05.14 |
VO와 DTO와 DAO (0) | 2024.05.12 |
java 네트워크 (0) | 2024.05.10 |
java IO패키지 (0) | 2024.05.09 |