【发布时间】:2012-10-13 17:35:11
【问题描述】:
在这个学校的小项目中,我正在做一个凯撒密码。将要做的是,用户将输入一个单词,并将其转换为字符数组,然后转换为相应的 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 循环中提到了“可能的精度损失”。还有什么我应该做的吗?谢谢!
【问题讨论】:
标签: java arrays char int ascii