【发布时间】:2015-12-05 03:11:15
【问题描述】:
我有一个包含一行内容的 .CSV 文件:
Detroit 25 4 7 W Green Bay 7 7 4 L
我创建了一个名为 input 的新 Scanner
Scanner input = new Scanner(file); //file here is the .csv file
如果我打印 input.next(),这就是显示的内容:
Detroit,25,4,7,W,Green
Bay,7,7,4,L
如果我创建一个新数组并指定一个分隔符,如下所示:
String[] list = input.next().split(",");
然后打印数组的索引
System.out.println(list[2]);
我明白了:
Detroit,25,4,7,W,Green
7
而不是 4。如何将 .csv 的每个值放在其自己的逻辑索引中? 示例:
list[0] = Detroit list[1] = 25 and so on.
这是我的完整代码:
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");
FileChooser.ExtensionFilter extFilter =
new FileChooser.ExtensionFilter("TEXT files (*.csv)", "*.CSV", ".xlsv", ".XLSV");
fileChooser.getExtensionFilters().add(extFilter);
File file = fileChooser.showOpenDialog(stage);
run(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);
input.nextLine();
System.out.println(input.next());
sortFile(file, input);
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)
{
String[] list = input.next().split(",");
System.out.println(list[2]);
if (input.hasNext())
{
return null;
}
return null;
}
}
【问题讨论】:
-
可能你从
Bay,7,7,4,L线得到输出。 -
@ElliottFrisch 我已经添加了我的完整代码
-
您的 csv 文件没有“
,”,而您说的是input.next()打印Detroit,25,4,7,W,Green Bay,7,7,4,L。这是不可能的。 -
对于 .csv 文件,每行的列用“,”分隔,如下所示:stackoverflow.com/questions/29886714/…
标签: java arrays java.util.scanner