我需要实现输出,但是代码逻辑似乎不正确

时间:2018-07-05 06:25:29

标签: java

我是初学者级程序员,我正在尝试实现以下提到的输出,并且我在java中编写了相同的代码,但是看来我的代码没有达到我的期望。

预期输出

input output
1        1
2        2 
3        3
4        1
5        2
6        3  

班级

public class Testing {

    public static void main(String[] args) {

        for (int i = 1; i < 7; i++) {
          //  System.out.println("the value of i is " + i);
            expectedOutput(i);

        }

    }

    private static void expectedOutput(int i) {

        int localVar = i;
        System.out.println("Input is " + i + " Output is " + localVar);

        if (localVar >= 3) {
            for (int j = 0; j < localVar; j++) {
                localVar = localVar / 2;
                System.out.println("Input is " + i + " Output is " + localVar);
            }
        }
    }
}

请指导我,并帮助我确定我犯错的地方,在此先谢谢您

输出应为

The input is 1 and output is 1
The input is 2 and output is 2
The input is 3 and output is 3
The input is 4 and output is 1
The input is 5 and output is 2
The input is 6 and output is 3

1 个答案:

答案 0 :(得分:5)

输出几乎是 input%3,但实际可被3整除的数字将返回3。您可以通过在执行模运算符之前减去1来获得此结果,并且然后重新添加:

System.out.printf("Input is %d Output is %d%n", i, (i -1) % 3 + 1);