0

In this little project for school, I am doing a Caesar cipher. What will be done is that the user will punch in a word, and it will be converted to an character array, then into its respective ascii numbers. Then this equation will be performed upon each number:

new_code = (Ascii_Code + shift[A number that the user picks out]) % 26

So far, here is the code I've written out:

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

It is mentioning a "possible loss of precision" in the last for loop. Is there something else I'm supposed to do? Thank you!

4

2 回答 2

2

因为A a; B b;,当 时,赋值a = (A) b会丢失精度((B) ((A) b)) != b。换句话说,转换为目标类型并返回会给出不同的值。例如(float) ((int) 1.5f) != 1.5f,将 a 转换为 afloatint因为丢失而丢失精度.5

chars 是 Java 中的 16 位无符号整数,而ints 是 32 位有符号 2-s 补码。您不能将所有 32 位值都放入 16 位,因此编译器会警告由于 16 位会丢失的精度损失,隐式转换只会将 16 个最低有效位intchar16 个最高有效位。

考虑

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

只需键入 castchar如下:

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