给定一个字符串,我必须找到字符串中每个字符的 ASCII。如果任何 ASCII 不是质数,则必须将其转换为最接近的质数 ASCII。如果两个素数 ASCII 与原始 ASCII 等距,则取较小者。 完成上述操作后,我需要将生成的 ASCII 转换为字符串。
但是我的代码的问题是它无法打印 y 形式的 ASCII 121
请帮我找出错误; 提前致谢
int T = s.nextInt();
int len;
byte lowerPrime, greaterPrime, temp;
String word;
byte[] b;
for (int i = 0; i < T; i++) {
len = s.nextInt();
s.nextLine();
word = s.nextLine();
b = word.getBytes(StandardCharsets.US_ASCII);
for (int k = 0; k < b.length; k++) {
temp = b[k];
if (!checkPrime(temp)) {
lowerPrime = findPrimeSmaller(temp);
greaterPrime = findPrimeGreater(temp);
if ((temp - lowerPrime) == (greaterPrime - temp)) {
b[k] = lowerPrime;
} else if ((temp - lowerPrime) < (greaterPrime - temp)) {
b[k] = lowerPrime;
} else if ((temp - lowerPrime) > (greaterPrime - temp)) {
b[k] = greaterPrime;
}
}
}
System.out.println(new String(b, "UTF-8"));
}
}
private static boolean checkPrime(byte n) {
if (n == 1) {
return false;
}
byte i = 2;
while (i < (n / 2)) {
if (n % i == 0) {
return false;
}
i++;
}
return true;
}
private static byte findPrimeGreater(byte n) {
while (!checkPrime(n)) {
n++;
}
return n;
}
private static byte findPrimeSmaller(byte n) {
while (!checkPrime(n)) {
n--;
}
return n;
}
最佳答案
您的代码正在按预期工作。 Here an online compiler with a few added debug-lines.
如您所见,它将在输入中找到字符 y
(121
) 的 127
,这是第一个更大的质数。 The ASCII character with code-point 127 is an unprintable character however ,这使得输出中看起来好像没有字符。
您可能希望通过向 findPrimeSmaller
和 findPrimeGreater
添加一些检查,将代码限制在可打印的 ASCII 范围 [32,126]
方法,这样它们就不会超出此限制(当然,不要返回该限制,因为它不是素数,而是返回 Integer.MIN_VALUE
和 Integer.MAX_VALUE
code> 或类似的东西,而不是当它到达边界时,所以你知道它会在你的 if 检查中选择另一个质数)。
或者,如果您想在程序中使用非 ASCII unicode 字符,您可能需要跳过不可打印的字符。
此外,一般注意事项:使用 IDE 调试器或像我在上面的在线版本中所做的那样添加打印行有助于检查代码出错的位置及其作用。在这种情况下,您的代码工作完全正常,但生成的字符只是一个不可打印的字符(unicode 值 127
)。
PS:这部分代码可以简化:
if ((temp - lowerPrime) == (greaterPrime - temp)) {
b[k] = lowerPrime;
} else if ((temp - lowerPrime) < (greaterPrime - temp)) {
b[k] = lowerPrime;
} else if ((temp - lowerPrime) > (greaterPrime - temp)) {
b[k] = greaterPrime;
}
致:
if ((temp - lowerPrime) <= (greaterPrime - temp)) { // Single <=, instead of loose == and <
b[k] = lowerPrime;
} else if ((temp - lowerPrime) > (greaterPrime - temp)) {
b[k] = greaterPrime;
}
关于java - 无法将 ascii 121 打印到字符 y,而是打印特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392730/