不允许使用ARRAYLIST
嘿,伙计们!感谢您花时间阅读!我有一个阵列,目前有15个数字,我需要添加点1-5中的数字,然后从2-6,然后从3,7等添加到15。然后总和这些必须放入一个新阵列。
任何提示?
代码在
之下import java.io.*;
import java.util.Scanner;
public class Asgn7
{
public static void main(String[] args) throws FileNotFoundException
{
Scanner file = new Scanner(new File("asgn7data.txt"));
int[] array = new int[file.nextInt()];
for (int i = 0; i < array.length; i++)
{
array[i] = file.nextInt();
System.out.println(array[i]);
}
file.close();
}
}
这是输入文件。
1
1
4
6
4
7
11
8
10
6
10
13
6
10
15
答案 0 :(得分:1)
你需要的是第二个数组为空,只是一个正确的算法来使这个工作。这里我们只循环下五个整数并将它们添加到第二个数组的相同索引中。
includes(:loan_balance)
String ints = "15 1 1 4 6 4 7 11 8 10 6 10 13 6 10 15";
Scanner file = new Scanner(ints);
int[] array = new int[file.nextInt()];
int[] newArray = new int[array.length-4];
int counter = 0;
while (file.hasNextInt()) array[counter++] = file.nextInt();
for (int i = 0 ; i < array.length - 4 ; i++){
for (int j = 0 ; j < 5 ; j++){
newArray[i] += array[i+j];
}
}
System.out.println(Arrays.toString(newArray));
答案 1 :(得分:1)
Scanner scanner = new Scanner(new File("input.txt"));
int[] inputarray = new int[10]; // You take a fixed size because you don't necessarily know the actual amount of input, we will expand this like an arraylist would
// First we will collect the input data
int current_index = 0;
while (scanner.hasNextInt()) {
if (inputarray.length == current_index) {
// Expand the array by creating a new one
final int[] expanded = new int[inputarray.length * 2];
System.arraycopy(inputarray, 0, expanded, 0, inputarray.length);
inputarray = expanded;
}
inputarray[current_index++] = scanner.nextInt();
}
// now we can calculate
final int[] answers = new int[current_index + 1 - 5];
for (int i = 0; i < answers.length; i++) {
for (int j = 0; j < 5; j++)
answers[i] += inputarray[i + j];
}
System.out.println(Arrays.toString(answers));