You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 world method is declared to return a String, but you're trying to return an int value. Here's why:
    • The charAt() method returns a char (the character at the specified index). When you assign this to an int variable x, 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 an int when the method expects a String will throw a compile error.
  • Missing Output: You call the world(test) method in main, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:47:06