Strings and nested loops
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 이 페이지는 최신 브라우저(SharedArrayBuffer 지원)가 필요합니다. Chrome, Edge, Firefox 또는 Safari를 최신 버전으로 업데이트해 주세요.
English
Strings and nested loops
- A
Stringis a row of characters, each with a position (an index). - The first index is
0, and the last islength() - 1. - In this lesson you walk through a String one character at a time, and put loops inside loops.
한국어
Strings와 중첩 루프
String는 각 위치(인덱스)를 가진 문자들의 줄입니다.- 첫 번째 인덱스는
0이며, 마지막은length() - 1입니다. - 이번 수업에서는 String을 한 문자씩 순서대로.walk through하며 루프를 중첩합니다.
English
Traversing a String
s.length()gives the number of characters.s.charAt(i)gives the character at indexi.- Loop
ifrom0up tolength() - 1to visit every character.
한국어
String Traverse
s.length()는 문자 수를 반환합니다.s.charAt(i)는 인덱스i에 있는 문자를 반환합니다.- 모든 문자를 방문하기 위해
i를0부터length() - 1까지 반복하세요.
public class Main {
public static void main(String[] args) {
String s = "code";
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
}
}
English
Counting characters
- You can count how many times a character appears.
- Use a counter that starts at
0. - A single character uses single quotes, like
'o'. Compare with==(chars, not Strings).
한국어
문자 세기
- 특정 문자가 나타나는 횟수를 세어볼 수 있습니다.
0에서 시작하는 카운터를 사용하세요.- 단일 문자는 단일-quote를 사용하며, 예시는
'o'입니다. (문자列, 즉 Strings가 아님)==과 비교하세요.
public class Main {
public static void main(String[] args) {
String s = "balloon";
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == 'o') {
count++;
}
}
System.out.println(count); // 2
}
}
English
Building a new String
- Start with an empty String
""and add characters with+. - Reading from the end to the start reverses the String.
- Each
+makes a longer String.
한국어
새로운 String 만들기
- 빈 String
""로 시작하여+으로 문자를 추가하세요. - 끝에서 시작으로 읽으면 String이 역순이 됩니다.
- 각
+는 더 긴 String을 만듭니다.
public class Main {
public static void main(String[] args) {
String s = "code";
String result = "";
for (int i = s.length() - 1; i >= 0; i--) {
result = result + s.charAt(i);
}
System.out.println(result); // edoc
}
}
English
Enhanced for (preview)
- For walking a String you usually need the index, so a normal
foris best. - But Java also has an enhanced for loop that visits items directly.
- You will use it a lot with arrays in lesson 8. Here is a small preview with text.
한국어
Enhanced for (미리보기)
- String을 순회할 때는 보통 인덱스가 필요하므로 일반
for가 가장 좋습니다. - 하지만 Java에는 항목을 직접 방문하는 enhanced for 루프도 있습니다.
- 수업 8에서 배열과 함께 자주 사용할 것입니다. 텍스트를 사용한 작은 미리보기를 보여줍니다.
public class Main {
public static void main(String[] args) {
String[] words = {"hi", "there", "!"};
for (String word : words) {
System.out.println(word);
}
}
}
English
Nested loops
- A nested loop is a loop inside another loop.
- The inner loop runs all the way for each step of the outer loop.
- Below, the outer loop picks a row, and the inner loop prints stars in that row.
한국어
중첩 루프
- 중첩 루프는 다른 루프 안에 있는 루프입니다.
- 안쪽 루프는 바깥쪽 루프의 각 단계마다 완전히 실행됩니다.
- 아래 예시에서 바깥쪽 루프는 행을 선택하고, 안쪽 루프는 그 행에 별을 출력합니다.
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 3; row++) {
String line = "";
for (int col = 1; col <= row; col++) {
line = line + "*";
}
System.out.println(line);
}
}
}
English
Common mistakes
- Strings are immutable — store the result of
s.substring(...)etc. s.length()is a method (with()), unlike an array's.length.
한국어
흔한 실수
- Strings는 불변성(immutable)이므로,
s.substring(...)등의 결과를 저장해야 합니다. s.length()는 메소드(()포함)입니다. 배열의.length과 다릅니다.
English
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
한국어
이제 직접 해보기
- 각 과제는 클래스 골격을 미리 채워 놓으므로, 코드를 main 내부에 작성하거나 제시된 메서드를 완성하십시오.
- Run 버튼을 눌러 컴파일하고 실행한 후, Answer 확인 버튼을 누르세요.
- 코드는 서버에서 컴파일되고 실행되므로 첫 실행에서도 빠릅니다.
Explore · 탐색하기
Indexing a String
Each char has an index from 0; substring takes a range.
Complete countChar(String s, char c) so it returns how many times c appears in s. Use charAt and ==. For example countChar("balloon", 'o') is 2.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Complete reverse(String s) so it returns s with the letters in the opposite order. For example reverse("code") is "edoc". Build a new String with +.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.
Use nested loops to print a triangle of stars: line 1 has one *, line 2 has two, line 3 has three, line 4 has four. Print each line with System.out.println.
Click Run to see the output here. · 출력을 보려면 '실행'을 클릭하세요.