Java字符串与char方法问题:代码无法返回Hello World的'd'求排查
Fixing Your Code to Return the 'd' from "Hello World"
Let's walk through what's going wrong with your code, and fix it so you can grab that 'd' from "Hello World" properly:
Key Issues in Your Original Code
- Type Mismatch Error: Your
worldmethod is declared to return aString, but you're trying to return anintvalue. Here's why:- The
charAt()method returns achar(the character at the specified index). When you assign this to anintvariablex, Java automatically converts the character to its ASCII code value (for 'd', that's 100). Not only is this not the actual character you want, but returning anintwhen the method expects aStringwill throw a compile error.
- The
- Missing Output: You call the
world(test)method inmain, but you don't print the result—so even if the code worked, you wouldn't see the 'd' in your console.
Corrected Code Options
Option 1: Return the Character as a String
If you want the method to return a String (matching your original method declaration), convert the char to a String before returning:
public class StringTest{ public static void main(String [] args){ String test= "Hello World"; System.out.println(world(test)); // Print the result to see it } public static String world(String original){ // Get the last character (index is length-1 since Java uses 0-based indexing) char targetChar = original.charAt(original.length() - 1); // Convert char to String and return return String.valueOf(targetChar); } }
Option 2: Return a char Directly
If you don't need a String and just want the character itself, change the method's return type to char:
public class StringTest{ public static void main(String [] args){ String test= "Hello World"; System.out.println(world(test)); // Print the result } public static char world(String original){ // Directly return the last character return original.charAt(original.length() - 1); } }
Quick Note on Indexing
You were actually right about using original.length()-1—since Java strings use 0-based indexing, the last character of "Hello World" (which has a length of 11) is at index 10, which is indeed the 'd' you want. Great call there!
内容的提问来源于stack exchange,提问作者Lotun Kanji
相关产品推荐
相关产品推荐

