【发布时间】:2016-06-01 19:17:41
【问题描述】:
在我进入这个问题之前,让我描述一下代码应该解决的问题。
代码应该采用以下语法从文件中获取输入:
1,2,3,4;5
代码应该采用分号后面的整数并将其分配给一个变量,它确实如此。然后代码应该获取分号之前的值并找到并返回所有两对整数,它们加起来等于分号之后的值。
示例:如果输入是
1,2,3,4;5
那么输出应该是
1,4;3,2
我的问题是我的String result 没有被代码中嵌套的for 循环编辑。我没有编译时或运行时错误。它只是不编辑String result,我不知道为什么。可以看看吗?
import java.util.*;
import java.io.*;
public class NumberPairs2 {
public static void main (String[] args) throws IOException {
File file = new File("C:/Users/James/Desktop/txt.txt"); // Takes in a file as input
BufferedReader buffer = new BufferedReader(new FileReader(file));
String line;
while ((line = buffer.readLine()) != null) {
String result = ""; // creates an empty string
line = line.trim(); // set the file contents equal to null
if (line.length() != 0){
int sumTest = Integer.parseInt(line.substring(line.indexOf(";") + 1));
String[] intArray = line.split(";");
String[] intArray2 = intArray[0].split(",");
for (int i = 0; i < intArray2.length - 1; i++){
for(int j = i + 1; i < intArray2.length; i++){
if (intArray2[i] != "," && intArray2[j] != "," && Integer.parseInt(intArray2[i]) + Integer.parseInt(intArray2[j]) == sumTest){
result += intArray[i] + ", " + intArray[j] + ";";
System.out.println(result);
}
}
}
//int compare = ()
}
else {
result = null;
System.out.println(result);
}
}
}
}
【问题讨论】:
-
我已经编辑了你的问题。我试图用正确的代码格式将大段分成更小的块;我已经删除了很多“so”并修复了代码缩进。
标签: java arrays split nested-loops