【问题标题】:Convert array of ascii numbers into their respective chracters将ASCII数字数组转换为各自的字符
【发布时间】: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


    【解决方案1】:

    只需键入 cast as char 例如下面:

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

    【讨论】:

      【解决方案2】:

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

      chars 在 Java 中是 16 位无符号整数,而 ints 是 32 位有符号 2 秒补码。您不能将所有 32 位值都放入 16 位,因此编译器会警告精度损失,因为 16 位会因隐式转换而丢失,该隐式转换只是从int 中提取 16 个最低有效位进入 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])

      【讨论】:

      • 那么就像从英语到日语多次来回翻译会完全改变原始短语一样,因为它们是两种不同的语言?
      • @user1768884,是的。如果你循环翻译“我吃了the苹果”。在英语和没有定冠词(“the”)和不定冠词(“a”)的语言之间,你可能会得到“I ate an apple”。背部。这是精度的损失。
      猜你喜欢
      • 2015-03-29
      • 2011-09-19
      • 2016-03-02
      • 1970-01-01
      • 2022-01-09
      • 2022-01-09
      • 1970-01-01
      • 2011-10-03
      • 1970-01-01
      相关资源
      最近更新 更多