我正在嘗試使用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()'有什麼問題? –