0

この学校向けの小さなプロジェクトでは、シーザー暗号を使用しています。実行されるのは、ユーザーが単語をパンチインし、それが文字配列に変換されてから、それぞれのASCII番号に変換されることです。次に、この方程式は各数値に対して実行されます。

new_code =(Ascii_Code + shift [ユーザーが選択する数値])%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ループで「精度が低下する可能性がある」と述べています。他にやるべきことはありますか?ありがとうございました!

4

2 に答える 2

2

の場合、。の場合A a; B b;、割り当てのa = (A) b精度が失われ((B) ((A) b)) != bます。つまり、宛先タイプにキャストして戻ると、異なる値が得られます。たとえば、aをに(float) ((int) 1.5f) != 1.5fキャストするfloatと、が失わintれるため、精度.5が失われます。

charsはJavaでは16ビットの符号なし整数であり、intsは32ビットの符号付き2の補数です。すべての32ビット値を16ビットに適合させることはできないため、コンパイラは、16ビットが失われることによる精度の低下について警告しintますchar。最上位16ビット。

検討

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

あなたは17ビットにしか収まらない整数を持っています、そしてそうcです(char) 0

修正するにcharは、プログラムのロジックが原因でこれが発生しないと思われる場合に、明示的なキャストを追加します。 asciiArray[count]((char) asciiArray[count])

于 2012-10-23T17:55:13.433 に答える
0

char以下のようにキャストと入力するだけです。

  charArray[count] = (char)asciiArray[count];
于 2012-10-23T17:55:10.423 に答える