java中关于readLine()的一个问题
我想用readLine().trim().split(" "); 这个代码去实现输入一行数值,并将这一行数值存储到数组中。
但我用这个去划分的时候,最后编译总会出现Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at Solution.main(Solution.java:12)
这种问题。
以如下题目为例:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那 两个 整数,并返回它们的数组下标。
我的代码如下:
import java.io.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
int target = Integer.parseInt(br.readLine());
int nums[] = new int[n];
for(int i = 0; i < n; i++){
String[] temp = br.readLine().trim().split(" ");
nums[i] = Integer.parseInt(temp[i]);
}
int[] result = new int[2];
for(int i = 0; i < result.length; i++){
result[i] = twoSum(nums,target)[i];
}
System.out.println("[" + result[0] + "," + result[1] +"]");
}
public static int[] twoSum(int[] nums, int target) {
int tot[] = new int[2];
//int sum = 0;
for(int i = 0 ; i < nums.length; i++){
for(int j = i+1; j < nums.length; j++){
if((nums[i] + nums[j]) == target) {
tot[0] = i;
tot[1] = j;
}
}
}
return tot;
}
} 在编译的时候会出现刚刚说的那个错误。但是把它复制到力扣上编译就会通过。有大佬可以帮忙解决一下么
查看1道真题和解析