0
我想使用Java中的文件和掃描儀打開CSV文件,但無法使用掃描儀打開它。下面是代碼,任何想法? 相關的代碼是在parseFile功能使用掃描儀在Java中打開CSV文件
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class CIS350HW1 {
/**
* @param args
*/
public static void main(String[] args) {
boolean quit = false;
int year = 0;
while(quit == false){
printMenu();
Scanner sc = new Scanner(System.in);
String str = sc.next().toUpperCase();
System.out.println(str);
if (str.equals("Q")) {
System.out.println("Good bye");
quit = true;
}
else if (str.equals("3")) {
parseFile(args[0], Integer.parseInt(str), year);
}
else if (str.equals("2") || str.equals("1")) {
System.out.println("Please enter the year: "); //remember might not be println
try {
year = Integer.parseInt(sc.next());
} catch(NumberFormatException e) {
System.out.print("Invalid formatted input. ");
}
if (year < 1920 || year > 2010){
System.out.println("Not a valid year.");
System.out.println();
}
parseFile(args[0], Integer.parseInt(str), year);
}
else {
System.out.println("That is not a valid selection.");
}
}
}
/**
* prints the menu options to the consul.
*/
public static void printMenu() {
System.out.println("Welcome to the Oscars database!");
System.out.println();
System.out.println("Please make your selection:");
System.out.println("1: Search for best picture award winner by year");
System.out.println("2: Search for best picture award nominees by year");
System.out.println("3: Search for actor/actress nominations by name");
System.out.println("Q: Quit");
}
public static void parseFile(String args, int n, int year) {
File file = new File(args);
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Could not open the file for some reason.");
}
while(input.hasNext()) {
String nextLine = input.nextLine();
String token[] = nextLine.split(",");
if (n == 1) {
String tempYear[] = token[0].split(" ");
if (Integer.parseInt(tempYear[0]) == year
&& token[1].equals("Best Picture")
&& token[3].equals("YES")) {
System.out.println(token[2]);
}
}
}
input.close();
}
}
注意,代碼沒有做任何事情,試圖找出爲什麼try/catch語句永遠不會奏效。 謝謝!
你是什麼意思的'從來沒有工作'? – kmera
我寫的「出於某種原因無法打開文件」的錯誤消息。總是打印並導致主 –
中的異常線程,然後它沒有找到該文件。你如何將文件名傳遞給你的程序? – kmera