通过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=1numbers[i]=-13,其中i=1数字[i-1]=-13,其中i=2numbers[i]=4,其中i=2,依此类推