Python到Java代码的转换

Kyl*_*e93 6 python java

有人能帮我把这个Python脚本转换成Java吗?

这是代码

theHex = input("Hex: ").split() 
theShift = int(input("Shift: ")) 
result = "" 
for i in range (len(theHex)): 
    result += (hex((int(theHex[i],16) + theShift))).split('x')[1] + " " 
    print(result)
Run Code Online (Sandbox Code Playgroud)

这就是我所拥有的

System.out.print("Please enter the hex: ");
String theHex = BIO.getString();
String[] theHexArray = theHex.split(" ");

System.out.print("Please enter the value to shift by: ");
int theShift = BIO.getInt();

String result[] = null;

for( int i = 0 ; i < theHex.length() ; i++ ){
     //result += (hex((int(theHex[i],16) + theShift))).split('x')[1] + " "
}

toText(result[]);
Run Code Online (Sandbox Code Playgroud)

BIO是我必须收集字符串和Ints的课程.可以把它想象成一个扫描仪.

谁能帮我翻译最后一行?

编辑这是toText方法

public static void toText(String theHexArray[]){
    String theHex = "";

    for(int i = 0 ; i < theHexArray.length ; i++ ){
        theHex += theHexArray[i];
    }

    StringBuilder output = new StringBuilder();
    try{
        for (int i = 0; i < theHex.length(); i+=2){
            String str = theHex.substring(i, i+2);
            output.append((char)Integer.parseInt(str, 16));
        }
    }catch(Exception e){
        System.out.println("ERROR");
    }
    System.out.println(output);
}
Run Code Online (Sandbox Code Playgroud)

Ian*_*ird 4

我怀疑你为自己做了比你真正需要的更多的工作,但就这样吧。

如果您打算进行逐行端口,那么就这样做

  1. 不要将结果声明为字符串数组。那只会让你头疼。像我在这里所做的那样,将其设置为 aStringBuilder或 plain (诚然,这会更有效,但这可能更容易理解)。这也更类似于您已有的 python 代码。StringStringBuilder

  2. 了解你的 python 代码在做什么。它采用十六进制格式的字符串,将其解析为整数,添加值 ( theShift),转换十六进制,然后仅获取字符串的数字部分(不带前导0x)。所以在 Java 中,循环是这样的。(注意:在 Java 中Integer.toString(x, 16)不会打印前导,因此0x我们不需要将其截断)。

    String result = "";
    for (String thisHex : theHexArray) {
        result += Integer.toString(Integer.parseInt(thisHex, 16) + theShift, 16) + " ";
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. 失去toText方法。此时,您已经获得了所需的字符串,因此该方法实际上不再执行任何操作。