我想从用户输入搜索arraylist但我的if条件似乎不起作用。使用boolean和.contains()对我的程序也不起作用。这是编码:
String phone;
phone=this.text1.getText();
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("C:\\Users\\Laura Sutardja\\Documents\\IB DP\\Computer Science HL\\cs\\data.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<String[]>();
while ((indata = line.readLine()) != null) {
String[] club = new String[2];
String[] value = indata.split(",", 2);
//for (int i = 0; i < 2; i++) {
int n = Math.min(value.length, club.length);
for (int i = 0; i < n; i++) {
club[i] = value[i];
}
boolean aa = dataArr.contains(this.text1.getText());
if(aa==true)
text2.setText("The data is found.");
else
text2.setText("The data is not found.");
dataArr.add(club);
}
for (int i = 0; i < dataArr.size(); i++) {
for (int x = 0; x < dataArr.get(i).length; x++) {
System.out.printf("dataArr[%d][%d]: ", i, x);
System.out.println(dataArr.get(i)[x]);
}
}
}
catch ( IOException iox )
{
System.out.println("Error");
}
答案 0 :(得分:2)
您的dataArr
是String[]
的列表,您正在搜索String
。这两种是不同类型的物体。
我真的不知道club
数组的内容是什么样的,但是您应该更改dataArr
以保持普通String
,或者编写一个方法在dataArr
中迭代地查找包含String[]
输出的this.text1.getText()
。
答案 1 :(得分:0)
该计划存在很多问题。我假设您要读取文本文件并将每行存储在arraylist中。为此,您必须拆分文本文件的每一行并将该数组存储在arrayList中。
String[] value;
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
现在您拥有arrayList中文件的内容。 接下来,您要将userinput与arraylist的每个元素进行比较。
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) { // i am assuming here that the phone number is the 2nd element of the String[] array, since i dont know how the textfile looks.
System.out.println("Found number.");
club[j++] = phoneData[1];
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
编辑: 根据要求:
String phone;
phone = "38495";
System.out.println("this is the phone: " + phone);
BufferedReader line = new BufferedReader(new FileReader(new File("list.txt")));
String indata;
ArrayList<String[]> dataArr = new ArrayList<>();
String[] club = new String[2];
String[] value;// = indata.split(",", 2);
while ((indata = line.readLine()) != null) {
value = indata.split(",");
dataArr.add(value);
}
int j = 0;
for (int i = 0; i < dataArr.size(); i++) {
String[] phoneData = dataArr.get(i);
if (phoneData[1].equals(phone)) {
System.out.println("Found number.");
club[j++] = phoneData[1];
break;
} else if (i == dataArr.size()-1) {
System.out.println("Didn't find number.");
}
}
我希望现在有道理。