编写.txt flie时遇到问题

时间:2015-09-30 02:19:23

标签: java

所以我无法让我的程序不向我抛出NoSuchElement异常。当我输入所有者信息时,无论我输入哪个所有者,它都会在第二个所有者之后抛出异常:

Jones; 221 Smith St; Arlington; Texas; 76019

Smith; 7345 Lane Rd; Dallas; Texas; 75000

Willis; 596 Dale Lane; Fort Worth; Texas; 76123

这是我的代码:

import java.util.Formatter;
import java.util.Scanner;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;

public class WriteFile
{

public static void main(String[] args)
{

    Formatter output;
    try
    {
        output = new Formatter("owners.txt");
        System.out.println("file accessed");

        System.out.println("Please enter owner information. Separate     information with semicolons please:");
        Scanner input = new Scanner(System.in);

        while(input.hasNext())
        {
            try
            {

                String owner = input.nextLine();
                String[] tokens = owner.split(";");

                output.format("%s %s %s %s %d%n",input.next(), input.next(), input.next(), input.next(),input.nextInt());
            }

            catch(NoSuchElementException ee)
            {
                System.out.println("Error on input. Please try again.");
                input.nextLine();
            }
        }

        output.close();
    }
    catch(Exception e)
    {
        System.out.println("Error working with file");
    }
}
}

谢谢大家的帮助!

1 个答案:

答案 0 :(得分:0)

问题在于:

output.format("%s %s %s %s %d%n",input.next(), input.next(), input.next(), input.next(),input.nextInt());

读取下一个令牌的调用没有读取任何内容,因为您之前的input.readLine()已经吞噬了整行。您应该在格式化程序中使用tokens[]对象。

相关问题