Strings and nested loops · 文字列とネストループ
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.
Stringとネストループ
Stringは文字の羅列であり、各文字には位置(インデックス)があります。- 最初のインデックスは
0、最後のインデックスはlength() - 1です。 - このレッスンでは、Stringを1文字ずつ順にたどり、ループをループの中に組み込みます。
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の走査
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));
}
}
}
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から始めるcounterを使用します。- 単一文字はシングルクォートを使用します(例:
'o')。==(Stringではなくchar)と比較してください。
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
}
}
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
}
}
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.
エンハンスドfor (プレビュー)
- Stringをたどる際は通常インデックスが必要なので、通常の
forが最適です。 - しかしJavaには、項目を直接訪問する エンハンスドfor ループもあります。
- レッスン8では配列で頻繁に使うことになります。ここではテキストを用いた小さなプレビューを紹介します。
public class Main {
public static void main(String[] args) {
String[] words = {"hi", "there", "!"};
for (String word : words) {
System.out.println(word);
}
}
}
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);
}
}
}
Common mistakes
- Strings are immutable — store the result of
s.substring(...)etc. s.length()is a method (with()), unlike an array's.length.
よくあるミス
- Stringは不変です —
s.substring(...)などの結果を保存してください。 s.length()はメソッド(()を持つ)であり、配列の.lengthとは異なります。
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 内にコードを書くか、表示されたメソッドを完成させてください。
- 実行 を押してコンパイル・実行し、その後 回答を確認 を押してください。
- コードはサーバー上でコンパイル・実行されるため、初回実行でも高速です。
Indexing a String · 文字列のインデックス付け
Each char has an index from 0; substring takes a range. · 各文字には0からのインデックスがあり、サブストリングは範囲を取得する。
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. · countChar(String s, char c) を完成させて、c が s 内に何回出現するかを返します。charAt と == を使用してください。例えば countChar("balloon", 'o') は 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 +. · reverse(String s) を完成させて、文字の順序を逆にした s を返します。例えば reverse("code") は "edoc" です。+ を使って新しい文字列を作成してください。
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. · ネストループを使って星の三角を印刷する:1行目に*が1つ、2行目に2つ、3行目に3つ、4行目に4つ。各行をSystem.out.printlnで印刷する。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。