Java
자바의신 ch14 & ch15
langsamUndStetig
2022. 6. 19. 15:47
package c.exception.practice;
public class Calculator {
public static void main(String[] args) {
Calculator calc = new Calculator();
try {
calc.printDivide(1, 2);
calc.printDivide(1, 0);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
// throws를 사용해서 호출시 try-catch 안에 넣도록 했음
public void printDivide(double d1, double d2) throws Exception {
if(d2==0){
// d2가 0인데 나누기가 실행되면 Infinity가 출력되기 때문에 아래의 메시지를 갖는 예외를 발생시켰다.
throw new Exception("Second value can't be Zero");
}
double result = d1/d2;
System.out.println(result);
}
}

package d.string.practice;
import java.util.Locale;
public class UseStringMethod {
public static void main(String[] args) {
UseStringMethod a = new UseStringMethod();
a.printWords("The String class represents character strings.");
a.findString("The String class represents character strings.", "string");
a.findAnyCaseString("The String class represents character strings.", "string");
a.countChar("The String class represents character strings.", 's');
a.printContainWords("The String class represents character strings.", "ss");
}
public void printWords(String str) {
String[] a = str.split(" ");
for(String as : a) {
System.out.println(as);
}
}
public void findString(String str, String findStr) {
int a = str.indexOf(findStr);
System.out.println(String.format("%s is appeared at %d", findStr, a));
}
public void findAnyCaseString(String str, String findStr) {
String a = str.toLowerCase();
int b = a.indexOf(findStr);
System.out.println(String.format("%s is appeared at %d", findStr, b));
}
public void countChar(String str, char c) {
char[] a = str.toCharArray();
int count = 0;
for(char as : a) {
if(c == as) {
count++;
}
}
System.out.println("char " + "'"+c+ "' count is " + count);
}
public void printContainWords(String str, String findStr) {
String [] a = str.split(" ");
for(String as : a ) {
if(as.contains(findStr)) {
System.out.println(as + " contains " + findStr);
}
}
}
}

