如果用户输入以下数字,请通过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());
}
}
答案 0 :(得分:4)
将变量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());
}
}
答案 1 :(得分:0)
你的for循环应该增加2。 因为在你的情况下,这就是正在发生的事情 数字[i-1] = 2,其中i = 1 numbers [i] = -13其中i = 1 数字[i-1] = -13其中i = 2 numbers [i] = 4,其中i = 2,依此类推