제어문 연습문제를 풀어보았는데 파이썬 공부할 때와 비슷한 유형의 문제들이 있었는데 똑같이 적용이 안되는 경우가 있었다. 문제를 풀면서 왜 사람들이 파이썬이 입문하기에 좋은 언어라고 하는지 알게 되었다. 문제 풀이를 시작해 보겠다.
public class Sample {
public static void main(String[] args) {
String a = "write once, run anywhere";
if (a.contains("wife")) {
System.out.println("wife");
} else if (a.contains("once") && !a.contains("run")) {
System.out.println("once");
} else if (!a.contains("everywhere")) {
System.out.println("everywhere");
} else if (a.contains("anywhere")) {
System.out.println("anywhere");
} else {
System.out.println("none");
}
}
}
// everywhere 출력
조건문이 부합하는 if문은 세번째와 네번째 if문이다. 두 개 이상의 조건문이 참인 상황을 이 문제를 통해 처음봐서 당황했다. 근데 보통 프로그래밍 언어는 위에서 부터 아래로 처리가 되니까 두 if문 중 앞에 있는 문장이 수행될거라고 추측했는데 추측이 맞았다.
public class Sample {
public static void main(String[] args) {
int n = 0;
int sum = 0;
while(n<1000) {
n++;
if (n % 3 != 0) {
continue;
}
sum += n;
}
System.out.println(sum);
}
}
while 문 안의 if 문에서 3의 배수가 아닌 것은 continue 구문을 통해 while문을 다시 실행하게끔 해서 3의 배수만 sum에 더해지도록 했다.
String sentence = "I love you";
System.out.println(sentence);
String reverse = "";
int i = 0;
while (i < sentence.length()) {
reverse += sentence.charAt(sentence.length() - i);
i++;
}
reverse.replace(" ", "_");
System.out.println(reverse);
// StringIndexOutOfBoundsException 에러 뜸
뭐가 문제인지 잘 모르겠다.. reverse를 빈 문자로 선언해두고 while 문으로 0~sentence.length까지 조건을 걸어둔다. 그리고 reverse에 sentence의 끝 문자부터 차례로 저장한다. 여기서 에러가 났다. charAt에서 StringIndexOutOfBoundsException 에러가 떴는데 무슨 말인지 잘 모르겠다.. 더 공부하고 나중에 수정하러 다시 와야겠다.
*
**
***
****
*****
public class Sample {
public static void main(String[] args) {
int n = 0;
while(n < 5) {
n++;
for (int i=0; i<n; i++) {
System.out.print("*");
}
System.out.println();
}
}
}
while문을 0~4까지로 조건을 정해놓고 반복할 때마다 n이 1씩 증가하게 한다. for 문으로 n만큼 *을 출력하고 그 후에 다음 칸으로 내려간다.
*****
****
***
**
*
public class Sample {
public static void main(String[] args) {
int n = 0;
while (n<5) {
n++;
for (int i=0; i<6-n; i++) {
System.out.println("*");
}
Sytem.out.println();
}
}
}
public class Sample {
public static void main(String[] args) {
for (int i=1; i<101; i++) {
System.out.println(i + " ");
if (i % 10 == 0) {
System.out.println();
}
}
}
}
for 문으로 1~100까지 한 칸 띄면서 나란히 출력하게끔 했고, for문 안에 if문으로 10마다 \n 하게 했다.
public class Sample {
public static void main(String[] args) {
int[] marks = {70, 60, 55, 75, 95, 90, 80, 80, 85, 100};
int sum = 0;
for (int mark : marks) {
sum += mark;
}
int average = sum / marks.length;
System.out.println(average);
}
}
배열이나 리스트 등의 묶여있는 값에 관한 것은 for each문 문제이다. 정수형 배열이므로 for 문의 타입은 int이고 변수이름은 mark로 정했고, 객체 이름인 marks를 적어준다.