【问题标题】:Java: Methods; Where am i doing it wrong? [closed]Java:方法;我在哪里做错了? [关闭]
【发布时间】:2015-05-10 00:20:56
【问题描述】:

我正在学习方法。如果我没有使用方法,我可以弄清楚,但我正在尝试使用 Java 中的方法将 char 转换为十六进制 ASCII 字符串。

我收到hexText var is not been initialized 的错误。 你能指出问题出在哪里吗? 感谢您的所有帮助。

这是我的代码:

    package charToHex;
    import java.util.Scanner;

    public class charToHex {
    public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    String text, hexStr;

    System.out.print("Enter some text: ");
    text = input.nextLine();
    System.out.println();
    System.out.println("Hex value");
    hexText = hexStr(text);
    System.out.println(hexText);
    }

    public static String hexStr(String text)
            {
                // You need to implement this function
                char chr;
                int ASCII;
                String hexText;
                for (int i = 0; i < text.length(); i++){
                   character = text.charAt(i);
                   ASCII = (int)chr;
                   hexText = Integer.toHexString(ASCII);

                 }

    return hexText;
    }

    RUN:
    Enter some text: hi

        Exception in thread "main" hextStr message
java.lang.Error: Unresolved compilation problem: 
    The local variable hexText may not have been initialized

    at charToHex.charToHex.hexStr(charToHex.java:80)
    at charToHex.charToHex.main(charToHex.java:30)

【问题讨论】:

  • 显示编译错误?您使用的是哪个 IDE?只需将结束的 } 放在末尾即可。
  • 我 - 作为初学者 - 也曾经认为例外中的文字只是为了吓唬你。
  • @lacraig2 是的,我错过了副本,但这不是我遇到的问题。我编辑了我的问题。谢谢
  • @MouseEvent 你是对的 :) 但我只是错过了复制我的代码并错过了一个 } 但这不是我得到的错误。谢谢
  • @hichris123 我收到 hexText var has not been initialized 的错误。

标签: java


【解决方案1】:

您需要在 main.xml 中将 hexText 声明为字符串。您需要在 hexStr(String) 中将字符声明为 char。

import java.util.Scanner;

public class charToText {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String text, hexStr;

        System.out.print("Enter some text: ");
        text = input.nextLine();
        System.out.println();
        System.out.println("Hex value");
        String hexText = hexStr(text);
        System.out.println(hexText);
    }

    public static String hexStr(String text) {
        // You need to implement this function
        char chr;
        int ASCII;
        String hexText = "";
        for (int i = 0; i < text.length(); i++) {
            chr = text.charAt(i);
            ASCII = (int) chr;
            hexText += Integer.toHexString(ASCII);

        }

        return hexText;
    }
}

希望这会有所帮助。 TLDR:

hexText+= Integer.toHexString(ASCII);

【讨论】:

  • 感谢您的指出。我意识到我错过了复制代码。我编辑了我的代码。
  • 抱歉造成误会。我在我的问题上编辑了我的代码并写了我得到的正确错误。再次抱歉。谢谢
  • 错过复制代码和回答问题是两个不同的问题
  • @MadProgrammer 谢谢你的意见。我更正了我的代码并写了我得到的正确错误。你能看看和帮助吗?谢谢
  • @user257427 试试我发布的代码。这个对我有用。您将需要导入 java.util.Scanner;