如何解决当 int 答案应该是 0123 (Java) 时,IntelliJ 输出不显示 0
我是一名 CS 学位的新生,正在学习 Java。当我尝试解释我的问题时,您是否介意忍受我,因为我仍然是 Java/IDE 的新手,并且仍然不太熟悉一切如何协同工作?
首先,我的教授给了我们一个简单的任务,当用户被问到时加密/解密四位数的值。 (例如,“输入要加密的四位数整数”- 9835)
然后代码将使用一些公式(不完全正确的加密),但它会将四位数字转换为新的四位数字。所以对于这个例子,9835 加密将是 0265。
所以当我的课程使用 Netbeans 作为首选 IDE 时,代码运行良好,9835 的答案是 0265。
但是今天,当我决定尝试 IntelliJ Idea Community Edition 并复制完全相同的代码时,答案应该是 0265,但输出仅显示 265。不知何故,它没有将 0 显示为第一个数字。
请注意,我已经考虑将加密变量从整数转换为字符串 - 因此将显示 0,但我的教授说它可以在不进行任何转换的情况下完成(使用 Netbeans 时)。
我该怎么做才能在 IntelliJ 中运行代码时将准确输出显示为 Netbeans? (答案是 0265)
非常感谢,非常感谢任何帮助/建议。
以下是我的代码供您参考。 (这可能令人困惑,但确实有效。)
import java.util.Scanner;
class Encryption_Decryption
{
public static void main(String[] args)
{
Scanner input = new Scanner(system.in);
//Variables to store the inputs
int encrypted_value_input,decrypted_value_input;
//Variables for storing the individual digits.
int digit1_E,digit2_E,digit3_E,digit4_E; //Where digit1_E is the extreme left position and _E stands for Encrypted.
//Variables for storing the digits with the formula applied.
int a1_e,a2_e,a3_e,a4_e;
//Variables for storing the encrypted and decrypted values.
int encrypted_value,decrypted_value;
//Welcome Message
System.out.println("This is an Encryption and Decryption Application.");
System.out.println();
//Start of Encryption
System.out.print("Enter 4 digits to be Encrypted: ");
encrypted_value_input = input.nextInt();
digit1_E = (encrypted_value_input / 1000); //takes the first digit
digit2_E = ((encrypted_value_input / 100) % 10);
digit3_E = ((encrypted_value_input / 10) % 10);
digit4_E = (encrypted_value_input % 10);
//Encryption Formula
a1_e = (digit1_E + 7) % 10;
a2_e = (digit2_E + 7) % 10;
a3_e = (digit3_E + 7) % 10;
a4_e = (digit4_E + 7) % 10;
//Swapping the digits. For eg. 1234 is abcd. abcd needs to be swapped to become cdab.
int temp1 = a1_e;
a1_e = a3_e;
a3_e = temp1;
temp1 = a2_e;
a2_e = a4_e;
a4_e = temp1;
encrypted_value = a1_e * 1000 + a2_e * 100 + a3_e * 10 + a4_e;
System.out.println("The encrypted value is " + encrypted_value);
}
}
解决方法
以 9835 作为输入,
在行中:
encrypted_value = a1_e * 1000 + a2_e * 100 + a3_e * 10 + a4_e;
您会看到 a1e * 1000
为 0,a2e * 100
为 2,a3e * 10
为 6,a4e
为 5。
在数学中,这将等于 0 + 200 + 60 + 5。因此,程序返回值 265。由于您需要在加密值的开头为“0”,因此解决此问题的最佳方法是将这些值放入成一个字符串。
您还会在以下几行中发现:
int temp1 = a1e;
a1e = a3e;
a3e = temp1;
temp1 = a2e;
a2e = a4e;
a4e = temp1;
a1e = 0
、a2e = 2
、a3e = 6
、a4e = 5
- 所以你已经在这里得到了答案。
现在剩下要做的就是将这些值打印在一个字符串中 - 这样你就可以拥有原始整数(用于稍后解密),但也可以打印出正确的答案。
您可以这样做:
int concA1E = a1e;
int concA2E = a2e;
int concA3E = a3e;
int concA4E = a4e;
System.out.println("The encrypted value is " + concA1E+concA2E+concA3E+concA4E);
通过不在“+”符号和整数变量之间添加任何空格,您可以将它们连接起来,这将导致答案 0265。
您也可以使用原始的 a1e
、a2e
、a3e
和 a4e
整数进行连接,但我更愿意将它们存储在单独的变量中,就在案件。
我建议您学习如何在您选择的 IDE 中进行调试,因为您将能够看到存储在变量中的内容以及 Java 正在执行的操作。这就是我找到这个问题的解决方案的方式。
如下图所示,该程序有效。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。