package pkgPeople;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public class CreateWithoutSerialization {
public static void main(String[] args) throws Exception
{
BankAccount bankAccount = new BankAccount(0, 0);
Person person = new Person();
String nm;
int ht;
int wt;
long ba;
double bal;
File inFile = new File("G:/CS9.27/inperson.txt");
File outFile = new File("G:/CS9.27/outperson.txt");
PrintWriter writer = new PrintWriter(outFile);
Scanner reader = new Scanner(inFile);
nm = reader.nextLine();
ht = reader.nextInt();
wt = reader.nextInt();
ba = reader.nextLong();
bal = reader.nextDouble();
person.setName(nm);
person.setHeight(ht);
person.setWeight(wt);
bankAccount.setAcctID(ba);
bankAccount.setBalance(bal);
System.out.println(person.toString());
//Write the attributes in ASCII to a file
writer.printf("%s is the name of the person.\r\n",nm);
writer.printf("%d inches is the height of %s.\r\n",ht, nm);
writer.printf("%d pounds is the weight of %s\r\n",wt,nm);
writer.printf("%d dollars is the balance of %s\r\n", bal, nm);
writer.printf("%l is the ID of the bank account.\r\n", ba);
}
}
运行后,我得到了这个例外..
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at pkgPeople.CreateWithoutSerialization.main(CreateWithoutSerialization.java:23)
这是文件错误吗?尝试过多次修复,但仍然卡住了。
答案 0 :(得分:5)
对reader.nextLine()
的调用引发了异常根据the javadoc,这意味着nextLine()
无法找到下一行。
基于仔细阅读javadoc,我认为这意味着您的输入文件为空。您可以在致电hasNextLine()
之前致电nextLine()
进行测试。
答案 1 :(得分:4)
作为编程语言的初学者,您需要学习如何使用为该语言提供的文档和资源。
如果您查看使用here方法的javadoc,您很快就会发现问题是Scanner
没有换行的新行字符。检查输入文件并确保其符合规格。如果您确定输入文件是正确的,可以使用文件API进行一些调试,以确保输入文件存在,然后再尝试将其用作扫描程序的输入。
您需要的所有信息都可以在javadoc中找到。
答案 2 :(得分:2)
现在NoSuchElementException
在输入用尽时出现。它不必与nextLine()
相关。因此,请检查是否有以下读取次数
nm = reader.nextLine();
ht = reader.nextInt();
wt = reader.nextInt();
ba = reader.nextLong();
bal = reader.nextDouble();
你的inperson.txt中有相同数量的行
同时强> 写完后......也这样做..
writer.flush();
writer.close();
否则你将看不到任何输出文件......:)
祝你好运