2015-03-30 86 views
0

當我運行下面的方法時,請記住ADFGVX將顯示在左側和陣列頂部,就像傳統的ADFGVX密碼一樣。如何將字符串輸入與二維數組中的字符配對?

static char [][] poly = new char[][]{ 
     {'p','h','0','q','g','6'}, 
     {'4','m','e','a','1','y'}, 
     {'l','2','n','o','f','d'}, 
     {'x','k','r','3','c','v'}, 
     {'s','5','z','w','7','b'}, 
     {'j','9','u','t','i','8'}}; 

我寫了使用2D陣列(陣列從上面可以看出),我想要做什麼顯示波利比奧斯正方形的方法是對什麼都用戶與正方形進入,因此,如果用戶鍵入對象我希望它返回FG VX XA DF GV XG。

Scanner console = new Scanner (System.in); 

String phrase; 

displayGrid(); 
System.out.println(""); 

System.out.print("Please enter a phrase you want to use\n"); 
phrase = console.nextLine(); 

console.close(); 

有人在這裏知道我會怎麼做呢?我打算做一個switch語句或者其他的東西,但是我認爲這不會起作用,即使這樣做會很長,效率也很低。

回答

0

你可以迭代你的數組來獲得你正在尋找的字符的位置,並將該位置解碼爲該字母。

public static String[] cypherADFGVX(String phrase){ 

    String[] output=new String[phrase.length()]; 

    for (int i = 0; i < phrase.length(); i++) { 
     //optional for breaking 
     //squareIteration: 
     for (int j = 0; j < 6; j++) { 
      for (int k = 0; k < 6; k++) { 
       if(poly[j][k]==phrase.charAt(i)){ 
        output[i]=new String(new char[]{switchChar(j),switchChar(k)}); 
        //To stop the iteration over poly and take care of the next char 
        //break squareIteration;      
       } 
      } 
     } 
    } 

    return output; 
} 

public static char switchChar(int integer){ 
    switch (integer) { 
    case 0:  
     return 'A'; 
    case 1: 
     return 'D'; 
    //and so on 
    } 
} 

如果我留下任何問題就問。

回答您的問題

哦。我懂了。我對java初學者來說太複雜了。 只有一個字符串更簡單的解決辦法是:

public static String cypherADFGVX(String phrase){ 

    String output=new String[phrase.length()]; 

    for (int i = 0; i < phrase.length(); i++) { 
     //optional for breaking 
     //squareIteration: 
     for (int j = 0; j < 6; j++) { 
      for (int k = 0; k < 6; k++) { 
       if(poly[j][k]==phrase.charAt(i)){ 
        output=output+switchChar(j)+switchChar(k)+" "; 
        //To stop the iteration over poly and take care of the next char 
        //break squareIteration;      
       } 
      } 
     } 
    } 

    return output; 
} 

現在讓我來解釋一下我的臺詞做。

String[] output=new String[phrase.length()]; 

創建一個新的字符串數組,其中每個字符串都是兩個大寫字母。 它看起來像[「FG」,「VX」,...]。在我看來,進一步處理更容易。

if(poly[j][k]==phrase.charAt(i)) 

比較您的方塊中位置jk處的字符與輸入字符串的第i個字符。

output[i]=new String(new char[]{switchChar(j),switchChar(k)}); 

我使用String構造函數,它將char數組作爲參數。

new char[]{'a','b'} 

創建數組並使用括號中列出的元素填充數組。

當然,您可以使用開關設置變量的值並返回該變量。

+0

感謝您的回覆!只想澄清一些事情。
String [] output = new String [phrase.length()];
這是製作一個新字符串並將其設置爲該短語的大小?
poly [j] [k] == phrase.charAt(i)
這意味着如果當前位於索引處的char等於字符串中的char?
output [i] = new String(new char [] {switchChar(j),switchChar(k)});
這是什麼意思?我從來沒有見過這個,我現在要去看看switchChars
也應該不通過交換機傳遞輸出嗎?爲什麼int? – 2015-03-31 09:52:46

+0

編輯回答所有問題? – meneken17 2015-03-31 16:20:28

相關問題