gpt4 book ai didi

java - 第二次读取一个数字

转载 作者:行者123 更新时间:2023-12-01 18:16:32 24 4
gpt4 key购买 nike

如果用户通过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());
}
}

关于java - 第二次读取一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29185174/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com