TXT 文件搜索不起作用
好的,我已将一些记录输入到一个文本文件中,并且我可以写入和读取该文件,但我现在尝试搜索该文本文件并遇到了问题。
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
无论我输入什么值,我都会被告知文件中不存在门牌号,但显然是这样,有什么想法吗?
附录:
文本文件中的文件结构。
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
Ok so i have inputted a number of records to a text file and i can both write to and read from this file, but i am now attempting to search through this textfile and have encountered a problem.
package assignmentnew;
// Import io so we can use file objects
import java.io.*;
import java.util.Scanner;
public class SearchProp {
public void Search() throws FileNotFoundException {
try {
String details, input, id, line;
int count;
Scanner user = new Scanner(System.in);
System.out.println();
System.out.println();
System.out.println("Please enter your housenumber: ");
input = user.next();
Scanner housenumber = new Scanner(new File("writeto.txt"));
while (housenumber.hasNext())
{
id = housenumber.next();
line = housenumber.nextLine();
if (input.equals(id))
{
System.out.println("House number is: " + id + "and" + line);
break;
}
if(!housenumber.hasNext()) {
System.out.println("no house with this number");
}
}
}
catch(IOException e)
{
System.out.print("File failure");
}
}
}
No matter what value i enter i am told that the house number is not present in the file, but obviously it is, any ideas?
Addendum:
File Structure in textfile.
27,Abbey View,Hexham,NE46 1EQ,4,150000,Terraced
34,Peth Head,Hexham,NE46 1DB,3,146000,Semi Detached
10,Downing Street,London,sw19,9,1000000,Terraced
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
扫描仪的默认分隔符是空格,而不是
,
。The default delimiter for a scanner is white-space, and not
,
.您必须使用
housenumber.useDelimiter(",");
并且代码将起作用。编辑:
在此之前设置它。
这就是我得到的 27 的例子。
You have to use
housenumber.useDelimiter(",");
and the code will work.EDIT:
Set it before the while.
And that is what I get for example for 27.