我正在尝试操作4位整数的入门级java课程。我需要为每个数字加7,然后模数,10,并切换第一个和第三个,第二个和第四个数字。
我很确定我能够操纵原始数据,但是如何切换数字呢?我似乎无法得到它。有没有办法返回这个,所以我可以在循环之外重组它而不是立即打印?
public static void main(String[] args) throws IOException
{
String input = JOptionPane.showInputDialog("Enter the data");
for (int i = 0; i < input.length(); i++)
{
char x = input.charAt(i);
int y = Character.getNumericValue(x);
int seven = addSeven(y);
int mod = modulusTen(seven);
System.out.print(mod);
}
System.out.println();
}
private static int addSeven(int data)
{
int add7 = data + 7;
return(add7);
}
private static int modulusTen(int mod)
{
int modulusTen = mod % 10;
return(modulusTen);
}
答案 0 :(得分:0)
如果您使用数组来保存数据会更容易
int arr [] = new int [4];
// check input is 4 in length then
for (int i = 0; i < input.length(); i++)
{
char x = input.charAt(i);
int y = Character.getNumericValue(x);
int seven = addSeven(y);
int mod = modulusTen(seven);
arr[i] = mod;
}
// then perform your swap logic
int tmp = arr [0];
arr[0] = arr[2];
arr [2] = tmp;
tmp = arr[1];
arr[1] = arr[3];
arr[3] = tmp;
答案 1 :(得分:-1)
这是算术方式:
public static void main(String[] args) throws IOException
{
String input = JOptionPane.showInputDialog("Enter the data");
int number = Integer.parseInt(input);
System.out.println(solve(number));
}
private static int solve(int num)
{
return (((num % 1000)/100 + 7) % 10) * 1000 +
(((num % 10000)/1000 + 7) % 10) * 100 +
(((num % 10) + 7) % 10) * 10 +
(((num % 100)/10 + 7) % 10);
}
这是字符串方式:
public static void main(String[] args) throws IOException
{
String input = JOptionPane.showInputDialog("Enter the data");
System.out.println(solve(input));
}
private static String solve(String num)
{
int first = (Integer.parseInt(num.charAt(0) + "") + 7) % 10;
int second = (Integer.parseInt(num.charAt(1) + "") + 7) % 10;
int third = (Integer.parseInt(num.charAt(2) + "") + 7) % 10;
int fourth = (Integer.parseInt(num.charAt(3) + "") + 7) % 10;
return "" + third + fourth + first + second;
}