繁体   English   中英

hasNextInt()对于已解析的String输入返回false

[英]hasNextInt() returns false for String input parsed

嗨,我在阅读文本文件时遇到问题:

我将一个名为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

现在,我想(最后......)说一遍,通过公寓的读取方法循环3次,因为3是公寓的数量。 但是当我尝试时: int NumberOfAppartmentsInList = scanner.nextInt(); ,这不起作用! 我得到错误的甚至scanner.hasNextInt()甚至当我尝试NumberOfAppartmentsInList = Integer.parseInt(list.get(0))当我创建的字符串行一个ArrayList ..

谁能帮我吗?

提前Tnx!

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;
}

我猜您没有按正确的顺序读取数据。 再加上huizen.toString()不会给您所有字符串的总和。

因此,解决它的一种方法可能是这样的:

公共静态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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM