import java.util.Random;
class OddException extends Exception {
}
public class Sample {
static void execute(int n) throws OddException {
System.out.printf("입력 숫자: %d\n", n);
if (n % 2 == 1) { // 홀수이면 OddException이 발생한다.
throw new OddException();
}
System.out.println("짝수입니다.");
}
public static void main(String[] args) {
Random r = new Random();
try {
for (int i = 0; i < 10; i++) {
execute(r.nextInt(10));
}
} catch (OddException e) {
e.printStackTrace();
}
}
}
0-10 중 한 숫자를 random 함수로 가져와 짝수이면 짝수라고 출력하고, 홀수이면 OddException 에러를 내도록 짠 코드이다. executive 함수를 10번 반복해야 하는데 도중에 홀수가 나오면 프로그램이 종료된다. 이를 해결하려면 두가지 방법이 있는데 첫번째 방법은 main 메소드에서 try-catch 구문을 for문 안으로 집어 넣어 홀수가 나와 OddException이 나더라도 10번을 계속 반복하도록 하는 방법이다.
import java.util.Random;
class OddException extends Exception {
}
public class Sample {
static void execute(int n) throws OddException {
System.out.printf("입력 숫자: %d\n", n);
if (n % 2 == 1) { // 홀수이면 OddException이 발생한다.
throw new OddException();
}
System.out.println("짝수입니다.");
}
public static void main(String[] args) {
Random r = new Random();
for (int i = 0; i < 10; i++) {
try {
execute(r.nextInt(10));
} catch (OddException e) {
e.printStackTrace();
}
}
}
}
여기서 printStackTrace 함수는 에러 메세지의 발생 근원지를 찾아서 단계별로 에러를 출력해주는 함수이다.
두번째 방법은 예외처리를 main 메소드에서 하는 것이 아닌 execute 함수 내에서 하는 방법이다. execute 함수에서 OddException을 main메소드로 던지지 말고, try-catch구문을 사용해서 함수 내에서 에러를 처리한다. 이렇게 하면 에러가 나도 for문으로 execute 함수가 10번이 정상적으로 실행될 것이다.
import java.util.Random;
class OddException extends Exception {
}
public class Sample {
static void execute(int n) {
System.out.printf("입력 숫자: %d\n", n);
try {
if (n % 2 == 1) { // 홀수이면 OddException이 발생한다.
throw new OddException();
}
System.out.println("짝수입니다.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Random r = new Random();
for (int i = 0; i < 10; i++) {
execute(r.nextInt(10));
}
}
}
import java.util.ArrayList;
import java.util.Arrays;
public class Sample {
static String dashInsert(String data) {
int[] numbers = Arrays.stream(data.split(""))
.mapToInt(Integer::parseInt)
.toArray();
ArrayList<String> result = new ArrayList<>();
for (int i=0; i< numbers.length; i++) {
result.add("" + numbers[i]);
if (i < numbers.length-1) {
boolean isOdd = numbers[i] %2 ==1;
boolean isNextOdd = numbers[i+1] %2 ==1;
if (isOdd && isNextOdd) result.add("-");
else if (!isOdd && !isNextOdd) result.add("*");
}
}
return String.join("",result);
}
public static void main(String[] args) {
String data = "4546793";
String result = dashInsert(data);
System.out.println(result); // 454*67-9-3 출력
}
}
public class Sample {
static String compressNum(String data) {
String[] c = data.split("");
String result = "";
int count = 0;
for (int i=0; i<data.length()-1; i++) {
if (c[i].equals(c[i+1])) {
count++;
} else {
result += c[i];
result += count + 1;
count = 0;
}
}
return result;
}
public static void main(String[] args) {
String data = "aaabbcccccca";
System.out.println(compressNum(data)); // a3b2c6 출력
}
}
public class Sample {
static String compressNum(String data) {
String result = "";
String temp = "";
int count = 0;
for (String c : data.split("")) {
if (!c.equals(temp)) {
temp = c;
if (count > 0) {
result += "" + count;
}
result += c;
count = 1;
} else {
count++;
}
}
if (count > 0) {
result += "" + count;
}
return result;
}
public static void main(String[] args) {
String result = compressNum("aaabbcccccca");
System.out.println(result); // a3b2c6a1 출력
}
}
import java.util.HashSet;
public class Sample {
static boolean chkDupNum(String data) {
HashSet<String> chk = new HashSet<>();
for (String c : data.split("")) {
chk.add(c);
}
if (chk.size() < data.length()) return false;
else return data.length() == 10;
}
public static void main(String[] args) {
System.out.println(chkDupNum("0123456789")); // true
System.out.println(chkDupNum("01234")); // false
System.out.println(chkDupNum("01234567890")); // false
System.out.println(chkDupNum("6789012345")); // true
System.out.println(chkDupNum("012322456789")); // false
}
}
import java.util.ArrayList;
public class Sample {
static boolean chkDupNum(String data) {
ArrayList<String> result = new ArrayList<>();
for (String c : data.split("")) {
if (result.contains(c)) {
return false; // 중복된 숫자가 있으면 false
} else {
result.add(c);
}
}
return result.size() == 10; // 0~9 모두 10개의 숫자인지 확인
}
public static void main(String[] args) {
System.out.println(chkDupNum("0123456789")); // true
System.out.println(chkDupNum("01234")); // false
System.out.println(chkDupNum("01234567890")); // false
System.out.println(chkDupNum("6789012345")); // true
System.out.println(chkDupNum("012322456789")); // false
}
}
import java.util.ArrayList;
import java.util.HashMap;
public class Sample {
static String morse(String data) {
HashMap<String, String> info = new HashMap<String, String>() {{
put(".-", "A");
put("-...", "B");
put("-.-.", "C");
put("-..", "D");
put(".", "E");
put("..-.", "F");
put("--.", "G");
put("....", "H");
put("..", "I");
put(".---", "J");
put("-.-", "K");
put(".-..", "L");
put("--", "M");
put("-.", "N");
put("---", "O");
put(".--.", "P");
put("--.-", "Q");
put(".-.", "R");
put("...", "S");
put("-", "T");
put("..-", "U");
put("...-", "V");
put(".--", "W");
put("-..-", "X");
put("-.--", "Y");
put("--..", "Z");
}};
ArrayList<String> result = new ArrayList<>();
for (String word : data.split(" ")) {
for (String c : word.split(" ")) {
result.add(info.get(c));
}
result.add(" ");
}
return String.join("", result);
}
public static void main(String[] args) {
System.out.println(morse(".... . ... .-.. . . .--. ... . .- .-. .-.. -.--")); // HE SLEEPS EARLY
}
}
import java.util.ArrayList;
public class Sample {
static String caesar(String data, int n) {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
ArrayList<String> result = new ArrayList<>();
for (String c : data.split("")) {
int position = alphabet.indexOf(c);
int newPosition = position + n;
newPosition = newPosition % alphabet.length();
result.add(alphabet.substring(newPosition, newPosition+1));
}
return String.join("",result);
}
public static void main(String[] args) {
System.out.println(caesar("CAT", 5)); // HFY
System.out.println(caesar("XYZ", 3)); // ABC
}
}