【发布时间】:2015-04-16 23:33:36
【问题描述】:
我的任务是创建一个程序,它从文本文件中读取数据,然后将数据存储在ArrayList 中。然后用户可以输入一个整数,程序会检查该数字是否在数据库中。程序返回一条语句,说明该号码是否在数据库中。文本文件由整数组成,每个整数在各自的行中,第一个数字表示文件中的整数数。
当我运行我的程序时,即使我在数据库中输入了一个我知道是 IS 的数字,我也会不断收到“x 不是数据库”。我做错了什么?
import java.io.*;
import java.util.*;
public class DirectoryLookupApplication {
public static void main(String[] args) throws IOException {
File read = new File("Data3.txt");
Scanner dataFile = new Scanner(read);
ArrayList<String> temporary = new ArrayList<String>();
while (dataFile.hasNextLine()) {
temporary.add(dataFile.nextLine());
}
temporary.remove(0); //removes the first element of the list since that element represents how many numbers are in the file
Scanner userInput = new Scanner(System.in);
System.out.println("Database Server is Ready for Number Lookups!");
int searchingFor = userInput.nextInt();
while (userInput.hasNext()) {
searchingFor = userInput.nextInt();
for (int i = 0; i < temporary.size(); i++) {
if (temporary.contains(searchingFor)) {
System.out.println("It exists in the database");
break;
}
else {
System.out.println("It is not in the database");
}
}
}
}
}
【问题讨论】:
-
尝试打印出您的变量,以检查它们是否符合您的想法。
-
你能发布一个文件内容的例子吗?它可以提供帮助。
-
我不是 Java 专家,但您的意思是
temporary[i].contains(searchingFor)? -
不要破坏自己的问题。如果您删除代码,那么问题和答案对其他人来说就是零意义。
标签: java arrays for-loop while-loop