2012-10-23 40 views
0

在這個學校的小項目中,我正在做一個凱撒密碼。將要做的是,用戶將打出一個單詞,它將被轉換爲一個字符數組,然後轉換爲相應的ASCII數字。然後這個方程將在每個號碼來執行:將ascii數字數組轉換爲它們各自的字符

new_code =(Ascii_Code +移用戶挑選出一個數])%26

到目前爲止,這裏是我已經寫出的代碼:

import javax.swing.*; 
import java.text.*; 
import java.util.*; 
import java.lang.*; 

public class Encrypt { 


public static void main(String[] args) { 

String phrase = JOptionPane.showInputDialog(null, "Enter phrase to be messed with "); 
String shift = JOptionPane.showInputDialog(null, "How many spots should the characters be shifted by?"); 
int shiftNum = Integer.parseInt(shift); //converts the shift string into an integer 
char[] charArray = phrase.toCharArray(); // array to store the characters from the string 
int[] asciiArray = new int[charArray.length]; //array to store the ascii codes 

//for loop that converts the charArray into an integer array 
for (int count = 0; count < charArray.length; count++) { 

asciiArray[count] = charArray[count]; 

System.out.println(asciiArray[count]); 

} //end of For Loop 

//loop that performs the encryption 
for (int count = 0; count < asciiArray.length; count++) { 

    asciiArray[count] = (asciiArray[count]+ shiftNum) % 26; 

} // end of for loop 

//loop that converts the int array back into a character array 
for (int count = 0; count < asciiArray.length; count++) { 

    charArray[count] = asciiArray[count]; //error is right here =(

} 




}//end of main function 




}// end of Encrypt class 

它提到了最後一個for循環中的「可能的精度損失」。還有什麼我應該做的嗎?謝謝!

回答

2

A a; B b;,分配a = (A) b失去精度((B) ((A) b)) != b時。換句話說,鑄造到目標類型並返回給出不同的值。例如(float) ((int) 1.5f) != 1.5f,因此將float轉換爲int會丟失精度,因爲.5丟失。

char s是Java中的16位無符號整數,而int是32位有符號的2-s補碼。您無法將所有32位值都放入16位,所以編譯器會警告由於16位會導致精度損失,而隱式轉換將會丟失從int的16位最低有效位進入char失去了16個最重要的位。

考慮

int i = 0x10000; 
char c = (char) i; // equivalent to c = (char) (i & 0xffff) 
System.out.println(c); 

你有一個整數,僅能以17位,所以c(char) 0

要解決,如果你相信,這不會因爲你的程序的邏輯的發生增加一個顯式的charasciiArray[count]((char) asciiArray[count])

+0

因此,就像翻譯多次從英語翻譯成日語一樣,將原來的短語完全改變爲其他語言,因爲它們是兩種不同的語言? – user1768884

+0

@ user1768884,是的。如果你循環翻譯「我吃**蘋果」。在英語和沒有確定(「the」)和不確定(「a」)條款的語言之間,你可能會得到「我吃了**蘋果」。背部。這是精確度的損失。 –

0

只需鍵入char如下:

charArray[count] = (char)asciiArray[count];