Java初学者如何用for循环和下标实现指定字符串输出?
How to Output "Jamaica amaica maica aica ica ca a" with For Loops and Indices in Java
Hey there! Let's break this down step by step since you're just starting out with Java—this is a great practice problem for getting comfortable with loops and string indices.
First, let's spot the pattern in your desired output: you're taking the original string "Jamaica" and repeatedly removing the first character, then printing each resulting substring separated by spaces. So:
- Start with the full string:
Jamaica - Remove first character:
amaica - Remove first character again:
maica - ... and so on until we're left with just
a
Here's a straightforward implementation using a for loop and string indices:
public class Main { public static void main(String[] args) { String original = "Jamaica"; // Loop from index 0 to the last index of the string for (int i = 0; i < original.length(); i++) { // Grab the substring starting at index i to the end of the string String currentSubstring = original.substring(i); // Print the substring followed by a space System.out.print(currentSubstring + " "); } } }
Let's break down what this code does:
- Original String: We start by defining the base string
"Jamaica". - For Loop: The loop variable
istarts at 0 (the first character's index in Java strings) and runs until it reaches the length of the string. Since"Jamaica"has 7 characters,iwill take values 0 through 6 (7 total iterations, one for each substring we need). - Substring Method:
original.substring(i)returns a new string that starts at indexiand includes all characters from that point to the end of the original string. For example:- When
i=0, it returns"Jamaica" - When
i=1, it returns"amaica" - ...
- When
i=6, it returns"a"
- When
- Printing: Using
System.out.print()instead ofprintln()ensures all substrings are printed on the same line, with spaces between them.
Optional: Fix the trailing space
If you want to avoid the extra space at the end of the output, you can adjust the loop to only print a space when it's not the last iteration:
public class Main { public static void main(String[] args) { String original = "Jamaica"; for (int i = 0; i < original.length(); i++) { System.out.print(original.substring(i)); // Only add a space if we're not on the last substring if (i != original.length() - 1) { System.out.print(" "); } } } }
Key concepts to remember:
- String Indices: Java strings are zero-indexed—meaning the first character is at index 0, the second at 1, and the last character is at
original.length() - 1. substring()Method: This is a built-in string method that lets you extract parts of a string. The version we used (substring(int beginIndex)) takes the starting index and returns everything from that point onward.- Loop Control: By incrementing
ieach iteration, we're effectively "chopping off" the first character of the original string each time, which gives us exactly the sequence you want.
内容的提问来源于stack exchange,提问作者coding anonymous




