我正在尝试使用Date(int,int,int)构造函数(每个教师需求),并且我遇到了一些困难。试图使用Date(int,int,int)构造函数
最初我收到警告,因为显然这个构造函数已被弃用,另外由于我使用了代码,我得到了错误。
我会在下面附上我的代码。我尝试使用fileRead.nextInt()作为文件扫描程序,并且我也尝试了使用Integer.parseInt(fileRead.next())在下面看到的方法。
这是从具有文本格式文件阅读:
firstName lastName, 4, 24, 2016, aStringOfTextPossiblyMultipleWords...
其中4月24日是2016年是。
我得到的错误是...
Exception in thread "main" java.lang.NumberFormatException: For input string: " 4"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:569)
at java.lang.Integer.parseInt(Integer.java:615)
at BlogEntryTester.main(BlogEntryTester.java:59)
/NetBeans/8.1/executor-snippets/run.xml:53: Java returned: 1
BUILD FAILED (total time: 6 seconds)
这里是代码。错误是在运行时接近代码结束的地方。
import java.util.Date;
import java.util.Scanner;
import java.io.*;
public class BlogEntryTester {
/**
* @param args the command line arguments
*/
public static void main(String[] args){
Date newDate = new Date();
BlogEntry BE1 = new BlogEntry();
BlogEntry BE2 = new BlogEntry("firstName", newDate, "This is the body of "
+ "blog entry number two. This is the last sentence.");
BlogEntry BE3 = new BlogEntry(BE2);
BE1.setUsername("randFirstName");
BE1.setDateOfBlog(newDate);
BE1.setBlog("This is less than 10 words...");
System.out.println(BE1.toString());
System.out.println(BE2.toString());
System.out.println(BE3.toString());
Scanner keyboard = new Scanner(System.in);
Scanner fileRead = null;
String fileName;
System.out.print("Enter the name of the file you wish to read from: ");
fileName = keyboard.next();
try{
fileRead = new Scanner(new FileInputStream(fileName));
System.out.println("> File opened successfully.");
fileRead.useDelimiter(",|\\n");
}
catch(FileNotFoundException e){
System.out.println("> File not found.");
System.exit(0);
}
BlogEntry newBlog = new BlogEntry();
newBlog.setUsername(fileRead.next()); // Reads username from file.
if(newBlog.getUsername().length() > 20){
System.out.println("> Error: Username read from file exceeds 20 "
+ "characters.");
}
newBlog.setDateOfBlog(new Date(Integer.parseInt(fileRead.next()),
Integer.parseInt(fileRead.next()),
Integer.parseInt(fileRead.next())));
newBlog.setBlog(fileRead.next()); // Reads the text of the blog.
System.out.println(newBlog.toString()); // Prints the data gathered from file.
}
}
您在'“4”'前面输入了一个空格。在解析它之前需要修剪它。 – Thilo
您将面临的下一个问题:那个不赞成使用的构造函数接受1900年和1月为0的年份。 – Thilo
'nextInt()'有什么问题? –