반응형
덧셈식 출력하기
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
System.out.printf("%d + %d = %d"
, a, b, a + b);
}
}
문자열 붙여서 출력하기
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
String b = sc.next();
System.out.print(a+b);
}
}
기억할 점
문자열 덧셈이 가능하다
문자열 돌리기
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.next();
for(char c : a.toCharArray()){
System.out.println(c);
}
}
}
홀짝 구분하기
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String answer = "even";
if (n%2 > 0) {
answer = "odd";
}
System.out.printf("%d is %s", n, answer);
}
}
//다른사람의 풀이
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(n + " is "+(n % 2 == 0 ? "even" : "odd"));
}
}
기억할 점
삼항연산자
(조건식) ? (True일 때의 결과) : (False일 때의 결과)
문자열 겹쳐쓰기
class Solution {
public String solution(String my_string, String overwrite_string, int s) {
String answer = "";
int idx = 0;
for(int i = idx; i<s; i++){
answer += my_string.charAt(i);
}
answer += overwrite_string;
idx = answer.length();
for(int i = idx; i<my_string.length(); i++){
answer += my_string.charAt(i);
}
return answer;
}
}
//다른사람의 풀이
class Solution {
public String solution(String my_string, String overwrite_string, int s) {
String before = my_string.substring(0, s);
String after = my_string.substring(s + overwrite_string.length());
return before + overwrite_string + after;
}
}
기억할 점
문자열 자르기 함수 : substring
String substring(int startIdx);
String substring(int startIdx, int endIdx);
☑️ 만약 인덱스가 문자열의 길이를 넘어선다면?
-> 빈 문자열을 출력한다.
재풀이
class Solution {
public String solution(String my_string, String overwrite_string, int s) {
String answer = my_string.substring(0,s) + overwrite_string;
answer += my_string.substring(answer.length());
return answer;
}
}
반응형
'Programming > Java' 카테고리의 다른 글
Logback의 보안 취약점 알아보기 - DBAppender는 왜 제거되었을까? (0) | 2024.02.21 |
---|---|
final 키워드 (0) | 2023.05.31 |
[코딩 기초 트레이닝] java - Day 3 (0) | 2023.05.18 |
자바 주피터 노트북으로 실행하기! (0) | 2023.05.17 |
[코딩기초트레이닝] java - Day 1 (0) | 2023.05.17 |