我有一个程序,我需要从一个方法返回,问题是他总是返回第一个位置而已。这是我想要接收输入的方法。
public void getCountByArea() {
//always receive the same string
String inputToValidate = getInputsTxtFromConsole();
String inputToCompare = getInputsTxtFromConsole();
}
这是我的另一种方法
public String getInputsTxtFromConsole() {
//read inputs file
try {
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
return line; //this always returns the same number
}
} catch (FileNotFoundException e) {
}
return "";
}
答案 0 :(得分:3)
您不能使用return语句来获取更多的值,因为它结束了函数调用。最好的方法是堆叠值然后返回。这是使用arraylist的一个例子。
public List getInputsTxtFromConsole() {
//read inputs file
try {
List<String> lines = new ArrayList(); //list instance
Scanner scanner = new Scanner(inputFile);
//read the file line by line
int lineNum = 0;
while (scanner.hasNextLine()) {
lines.add(scanner.nextLine()); //adding elements
lineNum++;
}
return lines; //then return
} catch (FileNotFoundException e) {
}
return null;
}
第二次编辑
如果你想获得循环返回列表所需的每个值;
public void getCountByArea() {
//always receive the same string
List<String> inputToValidate = getInputsTxtFromConsole();
List<String> inputToCompare = getInputsTxtFromConsole();
for(String input1 : inputToValidate){ //input1 is a temp variable
// your custom implementation
...
}
//another for each
...
}