【发布时间】:2015-12-05 01:24:45
【问题描述】:
我正在制作一个概率结果模拟器 Java 程序。该程序从 FileChooser 中的用户那里获取一个 CSV 文件(或任何文档文件)。然后用户将点击“运行”按钮,程序将开始读取 CSV(我们的首选文件)文件。到目前为止,这是我的代码:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.layout.*;
import javafx.scene.control.*;
import javafx.stage.FileChooser;
import javafx.geometry.*;
import java.util.*;
import java.io.*;
public class POS extends Application
{
private Button runBtn = new Button("Run");
@Override
public void start(Stage stage)
{
GridPane pane = new GridPane();
VBox vBox = new VBox(20);
vBox.setPadding(new Insets(15));
Button selectBtn = new Button("Select File");
selectBtn.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
vBox.getChildren().add(selectBtn);
selectBtn.setOnAction(e->
{
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open Resource File");
File file = fileChooser.showOpenDialog(stage);
String regEx = "([^\\s]+(\\.(?i)(txt|doc|csv|pdf|xlsx))$)";
if (file.getName().matches(regEx))
{
run(file);
}
else
{
System.out.println("Please enter a valid CSV file");
}
});
RadioButton weekBtn = new RadioButton("Current Week");
RadioButton seasonBtn = new RadioButton("Entire Season");
runBtn.setStyle("-fx-font: 22 arial; -fx-base: #b6e7c9;");
seasonBtn.setDisable(true);
vBox.getChildren().add(weekBtn);
vBox.getChildren().add(seasonBtn);
vBox.getChildren().add(runBtn);
pane.add(vBox, 0, 0);
Scene scene = new Scene(pane, 500, 200);
stage.setScene(scene);
stage.setTitle("POS");
stage.show();
}
public void run(File file)
{
runBtn.setOnAction(e->
{
try
{
Scanner input = new Scanner(file);
sortFile(file, input);
input.nextLine();
input.close();
}
catch (InputMismatchException ex)
{
System.out.println("Error you seem to have typed the wrong type of file");
}
catch(IOException ex)
{
System.out.println("Error, file could not be found");
}
});
}
public ArrayList<String> sortFile(File file, Scanner input)
{
Random r = new Random();
input.next();
int homeRank = input.nextInt();
input.next();
input.next();
input.next();
input.next();
int roadRank = input.nextInt();
System.out.println("Home: " + homeRank + "road: " + roadRank);
int lowestTeamRank = Math.abs(homeRank - roadRank);
if (input.hasNext())
{
return null;
}
return null;
}
}
当我“用户”选择一个文件时,比如说,一个无效文件,程序会告诉我这是无效的。如果我选择一个名为“NFLData”的 .csv 文件,程序会告诉我“错误,您似乎输入了错误的文件类型”(A MalformedException)。如果我选择一个没有任何内容的 .xlsx 文件,程序不会抛出格式错误的异常,而是告诉我它是空的。如何让我的程序接受我的 NFLData .csv 文件?
【问题讨论】:
-
String regEx = "([^\\s]+(\\.(?i)(txt|doc|csv|pdf|xlsx))$)";我猜这个正则表达式只适用于文件的后缀。请注意,String 类中的matches方法会检查整个字符串是否可以通过正则表达式一次性匹配。因此,如果您只想测试后缀,则 `if (file.getName().matches(regEx))` 不是有效代码。尝试使用.*开始您的正则表达式,以允许它匹配后缀之前的任何字符。 -
无论如何
FileChooser应该有选项允许您只选择具有指定扩展名/后缀的文件。所以也许这对你来说是更好的策略:stackoverflow.com/questions/13634576/… -
@Pshemo 该错误仅发生在运行方法中,当我创建扫描仪时。 catch 方法捕获错误,并将其报告为 inputmismatch 异常
-
@Pshemo 我现在意识到我的错误,当我启动 input.next() 时,扫描仪正在读取整行并由 (",") 分隔符分隔