我目前正在开发一个项目,我不明白为什么我的第二种方法不起作用。我正在尝试将用户输入的号码更改为另一个号码。每个数字应加 +7,然后除以 10。第一和第三位数字应该交换,第二和第四位也是如此。它应该接受四位数字,并单独处理每一位数字。我不确定如何获得教授要求的结果。他说1234的结果应该是0189,但是无论我如何交换它们,我总是得到13...我尝试修改方法来分隔数字,然后执行后面需要的数学运算,但现在结果是14 ... 我也不明白如何让编译器在数字开头返回零,或者防止它在返回时删除数字开头的零。 任何帮助将不胜感激,但请不要因为我不理解这项作业而讨厌我。
import java.util.*;
public class SeayJ_program2
{
static Scanner input = new Scanner (System.in);
public static void main (String [] args)
{
int num = getnum();
System.out.println(encrypt(num));
}
// methods are here
public static int getnum()
{
int num;
System.out.println("Please enter a four digit number");
num = input.nextInt();
return num;
}
public static int encrypt(int num)
{
int digit1, digit2, digit3, digit4;
digit4 = num % 10;
num = num / 10;
digit4 = (num + 7) / 10;
digit3 = num % 10;
num = num / 10;
digit3 = (num + 7) / 10;
digit2 = num % 10;
num = num / 10;
digit2 = (num + 7) / 10;
digit1 = num % 10;
num = num / 10;
digit1 = (num + 7) / 10;
return digit3 + digit4 + digit1 + digit2;
}
}
最佳答案
这应该适用于获取加密号码。 思考如何处理缺失的零
public static int encrypt(int number){
int temp = number;
int digit4 = (temp + 7) % 10;
temp = temp / 10;
int digit3 = (temp + 7) % 10;
temp = temp / 10;
int digit2 = (temp + 7) % 10;
temp = temp / 10;
int digit1 = (temp + 7) % 10;
return (digit3 * 1000 + digit4 * 100 + digit1 * 10 + digit2);
}
关于java - 使用方法加密java中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23206667/