我在如何在scanner.next()
的while循环中添加标签时遇到问题
这里是我的代码:
public void readCSV() throws FileNotFoundException{
try (Scanner scanner = new Scanner(new File("C:/Sample/employees.csv"))) {
scanner.useDelimiter(",");
int c = 1;
while(scanner.hasNext()){
String a ="";
if(c == 1){
a = "ID:";
}
if (c ==2){
a = "Name:";
}
if (c ==3){
a = "Age:";
}
if (c ==4){
a = "Position:";
}
if (c ==5){
a = "Salary:";
}
if (c ==6){
c = 1;
}
System.out.print(a+scanner.next()+"\n");
c++;
}
}
}
此功能的结果:
Employee Record System!
Choose an Operation
(1) View Employee
(2) Add Employee
(3) View Employee by Id
(4) Generate Employee Record
(5) Exit
1
ID:2095
Name:Juan Dela Cruz
Age:24
Position:Programmer
Salary:50000.00
6727
Bruce
25
Programmer
35000.00
3750
John
23
Junior Programmer
35000.00
8435
Alvin
41
Senior Programmer
100000.00
我想要的是每5个获取数据的数据都有其特定的标签:
预期输出:
ID:2095
Name:Juan Dela Cruz
Age:24
Position:Programmer
Salary:50000.00
ID:6727
Name:Bruce
Age:25
Position:Programmer
Salary:35000.00
ID:3750
Name:John
Age:23
Position:Junior Programmer
Salary:35000.00
ID:8435
Name:Alvin
Age:41
Position:Senior Programmer
Salary:100000.00
答案 0 :(得分:3)
将循环更改为此
while(scanner.hasNext()){
String a ="";
if(c == 1){
a = "ID:";
}
if (c ==2){
a = "Name:";
}
if (c ==3){
a = "Age:";
}
if (c ==4){
a = "Position:";
}
if (c ==5){
a = "Salary:";
c = 0;
}
当你在一个单独的if子句中设置c = 1时,它已经读取了id值,它将被打印而没有标签。它还会以错误的顺序显示其他标签。同样正如Johnny所指出的那样,您可能还需要在分隔符中添加换行符。