【发布时间】:2020-03-26 03:40:04
【问题描述】:
我正在做这个项目,我应该解析包含虚构公司数据和其他相关详细信息的文件,为每条记录创建一个对象并将对象存储到合适的集合中。我已经开始了,但现在我陷入困境并寻求帮助。
我设法从本地存储读取文件并将其输出到控制台,但奇怪的是它输出了六次详细信息,与我拥有的变量数量相匹配。有没有简单的解决方法?
另外,我将使用什么技术来为每条记录生成 ID,这些记录会随着每条记录的增加而增加?例如1, 2 ... 11, 12, 13 等等
我已经阅读了有关映射到数据成员的 getter 方法和 toString() 方法,但似乎无法充分理解它以将其实现到我的程序中。是否有任何类似的项目可以帮助我了解这些技术的工作原理并对我的工作有所帮助?
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
public class ApplicationRunner {
static void menu() {
try {
char quit = 'n';
String menuInput;
int menuChoice = 0;
Scanner scan = new Scanner(System.in);
while (quit != 'y') {
System.out.println(
"\n List traders.......1"
+ "\n Select trader......2"
+ "\n Search locations...3"
+ "\n Search services....4"
+ "\n Exit...............0"
+ "\n\n Enter choice:>");
menuChoice = scan.nextInt();
switch (menuChoice) {
case 1:
listTraders();
break;
case 2:
selectTrader();
break;
case 3:
searchLocation();
break;
case 4:
searchServices();
break;
case 0:
System.out.println("Exiting...");
System.exit(0);
break;
default:
System.out.println("Invalid menu selection.");
}
System.out.println("Quit? y/n");
menuInput = scan.next().toLowerCase();
quit = menuInput.charAt(0);
}
}
catch (Exception inputError)
{
System.out.println("\nInvalid input value. Valid values 0-4.");
menu();
}
}
static void listTraders() {
String dataFile = System.getProperty("user.dir") + File.separator + "traders.txt";
try {
BufferedReader br = new BufferedReader(new FileReader(dataFile));
String line = null;
while ((line = br.readLine()) != null) {
String[] details = line.split(":");
String companyName = details[0];
String location = details[1];
String services = details[2];
String description = details[5];
int numEmployees = Integer.parseInt(details[3]);
double dailyRate = Double.parseDouble(details[4]);
for (String printDetails : details) {
System.out.println(companyName + "\t" + location + "\t" + services +
"\t" + description + "\t" + numEmployees + "\t" + dailyRate);
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void selectTrader() {
}
static void searchLocation() {
}
static void searchServices() {
}
public static void main(String[] args) {
menu();
}
}
此程序中使用的交易者文件 - https://gist.github.com/senotajs/0011c93460f0e9603a53858de15f8639
【问题讨论】:
-
您正在迭代您的拆分字符串,并且对于每个拆分值,一个,打印您之前从该拆分字符串中提取的所有值。你会为 id 使用计数器(根据你所说的你想要的)。
-
我收到 404(未找到)作为指向您的文本文件的链接。
-
修复了链接。
-
@DaveNewton 我该如何做柜台的事情?将记录放入数组中,然后在数组上循环计数器?我有点迷茫