第二次读取一个数字

Reading a number the second time

如果用户通过 cmd 输入以下数字:2 -13 4 12 -1 113 19,输出应该是:

(2,-13) has signs (+,-) and is in Q4
(4,12) has signs (+,+) and is in Q1
(-1,113) has signs (-,+) and is in Q2

但我得到的是:

(2,-13) has signs (+,-) and is in Q4
(-13,4) has signs (-.+) and is in Q2
(4,12) has signs (+,+) and is in Q1
(12,-1) has signs (+,-) and is in Q4
(-1,113) has signs (-.+) and is in Q2
(113,19) has signs (+,+) and is in Q1

即对中的第二个数字再次重复自己作为下一对中的第一个数字。代码有什么问题?

public static void main(String [] args) 
    {

         int[] numbers = new int[args.length];
           try
            {
                for (int i = 1; i < args.length; i++) 
                {

                    numbers[i-1] = Integer.parseInt(args[i-1]);
                    numbers[i] = Integer.parseInt(args[i]);
                    System.out.println("("+numbers[i-1]+","+numbers[i]+")" + " has signs " + checkSigns(numbers[i-1], numbers[i]) + " and is in " + fromInts(numbers[i-1], numbers[i]));
                }
            }
            catch (NumberFormatException e)
            {
                System.out.println(e.getMessage());
            }
    }

将变量 i 增加 2,因为您在循环的每次迭代中使用数组中的两个条目:

public static void main(String [] args) 
{

     int[] numbers = new int[args.length];
       try
        {
            for (int i = 1; i < args.length; i += 2) 
            {

                numbers[i-1] = Integer.parseInt(args[i-1]);
                numbers[i] = Integer.parseInt(args[i]);
                System.out.println("("+numbers[i-1]+","+numbers[i]+")" + "    has signs " + checkSigns(numbers[i-1], numbers[i]) + " and is in " + fromInts(numbers[i-1], numbers[i]));
            }
        }
        catch (NumberFormatException e)
        {
            System.out.println(e.getMessage());
        }
}

你的 for 循环应该递增 2。 因为在你的情况下这就是正在发生的事情 数字[i-1] = 2 其中 i=1 数字[i] = -13 其中 i=1 数字[i-1] = -13 其中 i=2 numbers[i] = 4 其中 i=2 依此类推