Python到Java代码的转换

时间:2013-11-26 16:20:04

标签: java python

有人能帮我把这个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)

这就是我所拥有的

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[]);

BIO是我必须收集字符串和Ints的课程。把它想象成基本上是扫描仪。

有人可以帮我翻译最后一行吗?

EDIT 这是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);
}

2 个答案:

答案 0 :(得分:4)

我怀疑你为自己做的工作比你真正需要的更多,但是这里有。

如果您打算使用逐行端口,那么执行

  1. 不要将结果声明为字符串数组。这只会让你头疼。像我这样做StringBuilder或普通StringStringBuilder会更有效率,但这可能更容易理解)。这也与你已经拥有的python代码更相似。

  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) + " ";
    }
    
  3. 丢失toText方法。此时你有你想要的字符串,所以这个方法不再做任何事了。

答案 1 :(得分:3)

无论您是决定逐行翻译,还是致力于理解代码,然后为问题编写基于Java的解决方案,您都需要细分最后一行来理解它。试着这样看:

result += (hex((int(theHex[i],16) + theShift))).split('x')[1] + " " 

与 -

相同
val1 = int(theHex[i],16)
val2 = (val1 + theShift)
val3 = hex(val2)
val4 = (val3).split('x')
result += val4[1] + " " 

现在,您可以更清楚地看到所谓的内容。下一步是查找int,hex和split调用正在执行的操作。