2013-11-26 128 views
5

任何人都可以给我一个手把这个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) 

这里是我有

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是一类我有收集字符串和整数的。把它看作基本上是一台扫描仪。

任何人都可以帮我翻译最后一行吗?

编辑 这里是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); 
} 
+3

我真的质疑这些所谓的“助手”类,它们实际上只是您和扫描仪之间的一个额外的层。要点:不要尝试一对一翻译代码。分解它,看看它正在尝试做什么,然后逐步实施它。 –

+0

你的意思是打印数组? 'java.util.Arrays中。toString(result)' – PeterMmm

+0

@JeroenVannevel我只是为了简单而使用它,因为这是我已经习惯了。至于评论,我试过。然而,由于我对python不熟悉,我一直无法找到它在做什么。我看过文档,但没有找到它。如果你可以用面向Java的方式解释它,这可能会有所帮助。 – Kyle93

回答

4

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

如果你打算去一个逐行的端口,那么这样做

  1. 不要将结果声明为字符串数组。这只会让你头疼。或者像StringBuilder或者简单的String这样做(我承认StringBuilder会更高效,但这可能更容易理解)。这也更类似于你已经拥有的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方法。在这一点上,你有你想要的字符串,所以这种方法不再做任何事情。

+0

完美答案,非常感谢。很好的解释 – Kyle93

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调用正在做什么。