【发布时间】:2019-03-15 02:30:42
【问题描述】:
对于我正在制作的这个程序,我有几个问题要找出列表中连续数字的最大总和。请注意,这与在数组中找到最大的连续整数之和不同。基本上,给定一个 ex 列表。 2, -1, 3,4,9 .... 等高达 100 万,我需要找到最大的连续数字总和(在上面给出的列表中,3,4 是连续的,因此总和将为 7)。所以我能理解的是我需要一个循环来遍历列表并检查数字是否连续。我的循环基于这样一个事实,即减去连续数字后将等于 -1,但我的 if 语句似乎总是出现 ArrayINdexOutOfBounds 错误。举个例子,假设列表是
1 2 3 4
3 -1 4 5
这是我的代码;
public class ProgramCRedo {
//This method reads each line and checks for the largest sum of consecutive numbers in a list
//This method does not have a return value, information is outputted once it exists
//This method has one parameter, it is string list taken from the input file
public static void checkLine (String line){
String[] numbers = line.split(" ");
int sum = 0;
int largestSum = 0;
int [] savedNums = new int [numbers.length];
for(int i = 0; i<savedNums.length; i++) { //loops through the list
savedNums [i] = Integer.parseInt(numbers[i]);
if((savedNums[i] - (savedNums[i+1])) == -1) { //checks if numbers are consecutive
sum += (savedNums[i] + (savedNums[i+1])); //if true, adds them up to a sum
}
System.out.println(sum);
// System.out.println(savedNums[i]);
}
}
}
public static void main(String[] args) {
try{
BufferedReader bf = new BufferedReader (new FileReader("input.txt"));
String line;
line = bf.readLine(); //reads line
//String line1= null; //skips first line
while(line != null){ //keeps looping until no more lines
checkLine(line); // uses list to check each line in file
line = bf.readLine();
}
bf.close();
}catch(FileNotFoundException e){ // catches exceptions
System.out.println("FILE NOT FOUND!");
}catch(IOException e){
System.out.println("Reading Error!");
}catch(NumberFormatException e) {
System.out.println("Invalid Input Entered");
}
System.out.println("Program is complete");
}
这是我的一些问题
- 为什么我的方法中的 if 语句给我一个 ArrayIndexOutOfBounds 异常?
- 作业规定每个测试用例的整数列表将在单行文本中给出,列表中的每个整数用一个空格分隔。您可以假设每个案例的最大列表大小为 1,000,000 - 我在哪里以及如何输入此检查以获取最多 100 万个整数的列表?
谢谢,这是用 JAVA 写的。
更新:我发现数组越界问题。现在发生的情况是,当我打印出此处给出的列表示例的总和时,我得到 0 和 -1。这是不正确的。我将尝试追踪这一点,但如果有人有任何想法,请告诉我。
【问题讨论】:
-
当
i处于最大值时,savedNums[i+1]将超过数组的长度 -
读行时使用"line = bf.readLine().substring(0,1000000);"这会将您的字符长度限制为 100 万,并且在创建 saveNums 数组时,您已经创建了与输入行中的数字长度相等的数组,但您没有在数组中添加这些数字。
标签: java arrays string loops integer