我正在研究方法。如果我没有使用Methods,我可以弄明白,但我试图通过使用Java中的方法将char转换为十六进制ASCII字符串。
我收到错误hexText
var尚未初始化。
你能指出问题出在哪里吗?
谢谢你的帮助。
这是我的代码:
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)
答案 0 :(得分:-4)
您需要在main中将hexText声明为String。您需要在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);