[英]hasNextInt() returns false for String input parsed
Hi I have a problem with reading a text-file: 嗨,我在阅读文本文件时遇到问题:
I load into Java a file called huizen.txt, which is the following: (I put it in workspace, C:\\, src, bin, in Files in the project itself and on the desktop, still dont know where to put it correctly) 我将一个名为huizen.txt的文件加载到Java中,该文件如下:(我将其放在工作区,C:\\,src,bin,项目本身和桌面中的Files中,但仍然不知道将其正确放置在何处)
3
Emmalaan 23
3051JC Rotterdam
7 kamers
prijs 300000
Javastraat 88
4078KB Eindhoven
3 kamers
prijs 50000
Javastraat 93
4078KB Eindhoven
4 kamers
prijs 55000
Now I want (in the end......) to say loop for 3 times through a read-method for appartments since 3 is the number of appartments. 现在,我想(最后......)说一遍,通过公寓的读取方法循环3次,因为3是公寓的数量。 But when I try:
int NumberOfAppartmentsInList = scanner.nextInt();
但是当我尝试时:
int NumberOfAppartmentsInList = scanner.nextInt();
, this does not work! ,这不起作用! I get false even for
scanner.hasNextInt()
, even when I try NumberOfAppartmentsInList = Integer.parseInt(list.get(0))
when I create an arraylist for the string lines.. 我得到错误的甚至
scanner.hasNextInt()
甚至当我尝试NumberOfAppartmentsInList = Integer.parseInt(list.get(0))
当我创建的字符串行一个ArrayList ..
Can anyone help me out? 谁能帮我吗?
Tnx in advance! 提前Tnx!
Grtz (code below) Grtz(下面的代码)
public static Portefeuille read(String infile) throws Exception
{
Portefeuille protonX = new Portefeuille();
ArrayList<String> huizen = new ArrayList<String>();
Scanner sc = new Scanner("huizen.txt");
while (sc.hasNext())
{
huizen.add(sc.nextLine());
}
String infil3 = huizen.toString();
Scanner scan = new Scanner(infil3);
if (scan.hasNextInt())
{
int aantal = scan.nextInt();
System.out.println(aantal);
}
else{
System.out.println("ERROR");
}
ArrayList<Woning> list = new ArrayList<Woning>();
for (int i = 0; i < 4; i++)
{
list.add(Woning.read(scan));
}
scan.close();
sc.close();
return protonX;
}
You did not read the data in the right order, I guess. 我猜您没有按正确的顺序读取数据。 Plus huizen.toString() will not give you the sum of all strings.
再加上huizen.toString()不会给您所有字符串的总和。
So the one way to fix it might be like this: 因此,解决它的一种方法可能是这样的:
public static Portefeuille read(String infile) throws Exception { 公共静态Portefeuille read(String infile)引发异常{
Portefeuille protonX = new Portefeuille();
ArrayList<String> huizen = new ArrayList<String>();
Scanner sc = new Scanner("huizen.txt");
while (sc.hasNext())
{
huizen.add(sc.nextLine());
}
String infil3 = "";
for (String h : huizen)
{
infil3 += h + "\n";
}
Scanner scan = new Scanner(infil3);
if (scan.hasNextInt())
{
int aantal = scan.nextInt();
System.out.println(aantal);
}
else{
System.out.println("ERROR");
}
ArrayList<Woning> list = new ArrayList<Woning>();
for (int i = 0; i < aantal; i++)
{
list.add(Woning.read(scan));
}
scan.close();
sc.close();
return protonX;
} }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.