我正在尝试将.csv文件中的文件读入一个数组,其中包含文件中每行的第一个索引。
我想要实现的只是每行的第一个单词,而不是下图:
Bonaqua
California
Gallardo
City
Skyline
以下是我的阅读文件类:
import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class readfile {
private Scanner s;
public void openFile() {
try {
s = new Scanner(new File(readpath.a));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "File not found!");
}
}
public void readFile() {
String read = "";
while (s.hasNextLine()) {
read += s.nextLine() + "\n";
}
String menu[] = read.split("\n");
Object[] selectionValues = menu;
String initialSelection = "";
Object selection = JOptionPane.showInputDialog(null,
"Please select the Topic.", "Reseach Forum Menu",
JOptionPane.QUESTION_MESSAGE, null, selectionValues,
initialSelection);
JOptionPane.showMessageDialog(null, "You have choosen "
+ selection + ".", "Reseach Forum Menu",
JOptionPane.INFORMATION_MESSAGE);
if (selection == null) {
JOptionPane.showMessageDialog(null, "Exiting program...",
"Research Forum Menu", JOptionPane.INFORMATION_MESSAGE);
System.exit(0);
}
}
public void closeFile() {
s.close();
}
}
答案 0 :(得分:4)
将s.nextLine()
更改为s.nextLine().split(",")[0]
答案 1 :(得分:0)
你能告诉我为什么你先用“\ n”
连接字符串while (s.hasNextLine()) {
read += s.nextLine() + "\n";
}
然后你分开了吗?
String menu[] = read.split("\n");
构建字符串然后按照构建它的方式拆分它是没有意义的。
ArrayList<String> firstWords = new ArrayList<String>(); // ArrayList instead of a normal String list because you don't know how long the list will be.
while (s.hasNextLine()) {
firstWords.add(s.nextLine().split(",")[0]);
}
现在,您已将所有首字母列入清单。