Java 在编写.txt文件时遇到问题

Java 在编写.txt文件时遇到问题,java,Java,所以我很难让我的程序不向我抛出NoTouchElement异常。当我输入所有者信息时,无论我输入哪个所有者,它都会在第二个所有者之后抛出异常: 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; impo

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

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");
    }
}
}
谢谢大家的帮助

问题是:

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

读取下一个标记的调用没有读取任何内容,因为您先前的input.readLine已经占用了整行内容。您应该在格式化程序中使用tokens[]对象。

您可能应该在format调用中使用tokens变量,而不要在catch中调用nextLine。还可以考虑循环如何结束。你能准确地更新你的问题吗?您是想将输入写入文件,还是只是将其格式化以显示到控制台?就目前而言,您的代码几乎有太多问题无法回答。