Reputation: 1047
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!
Upvotes: 0
Views: 4219
Reputation: 120526
For A a; B b;
, the assignment a = (A) b
loses precision when ((B) ((A) b)) != b
. In other words, casting to the destination type and back gives a different value. For example (float) ((int) 1.5f) != 1.5f
so casting a float
to an int
loses precision because the .5
is lost.
char
s are 16-bit unsigned integers in Java, while int
s are 32-bit signed 2-s complement. You can't fit all 32-bit values into 16-bits, so the compiler warns about loss of precision due to the 16 bits that would be lost by an implicit cast that just shoehorns the 16 least-significant bits from the int
into the char
losing the 16 most-significant bits.
Consider
int i = 0x10000;
char c = (char) i; // equivalent to c = (char) (i & 0xffff)
System.out.println(c);
you have an integer that can only fit in 17-bits, and so c
is (char) 0
.
To fix, add an explicit cast to char
if you believe that this will not happen because of the logic of your program: asciiArray[count]
→ ((char) asciiArray[count])
.
Upvotes: 2
Reputation: 34367
Just type cast as char
e.g. below:
charArray[count] = (char)asciiArray[count];
Upvotes: 0