将ascii数字数组转换为各自的字符

时间:2012-10-23 17:53:00

标签: java arrays char int ascii

在这个学校的小项目中,我正在做一个凯撒密码。将要做的是用户将打入一个单词,它将被转换为字符数组,然后转换为其各自的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循环中提到了“可能的精度损失”。还有别的我应该做的吗?谢谢!

2 个答案:

答案 0 :(得分:2)

对于A a; B b;,分配a = (A) b((B) ((A) b)) != b时失去精确度。换句话说,转换为目标类型并返回给出不同的值。例如(float) ((int) 1.5f) != 1.5f因此,floatint投射会失去精确度,因为.5会丢失。

char是Java中的16位无符号整数,而int是32位带符号的2-s补码。您不能将所有32位值都装入16位,因此编译器会警告精度损失,因为隐式转换会丢失16位,而这只会隐藏{{1}中的16个最低有效位。进入int失去16个最重要的位。

考虑

char

你有一个只能容纳17位的整数,所以int i = 0x10000; char c = (char) i; // equivalent to c = (char) (i & 0xffff) System.out.println(c); c

要修复此问题,如果您认为由于您的计划逻辑不会发生这种情况,请向(char) 0添加一个明确的广告:charasciiArray[count]

答案 1 :(得分:0)

只需输入广告为char,例如下面:

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