如何使用split()并读取文件字符串的第一个字符?

时间:2017-02-28 21:03:14

标签: java arrays file polymorphism

例如,我想拆分此文件的逗号并读取每行的第一个字符。基于第一个字符(#,*,@),我想在每个字符(Steve Davis 2000)之后使用数据创建一个对象。

4     
#Steve,Davis,2000
*John,Kanet,800,7000,0.10
@Thomas,Hill,20,50
*Lisa,Green,800,6000,0.10

4用作我的数组的大小

到目前为止,这是我的代码:

import java.util.Scanner;
import java.io.*;

public class PayRoll3{
public static void main(String[] args) throws FileNotFoundException{

    Scanner input=new Scanner(new File(args[0]));  
    int size=input.nextInt();
    input.nextLine();

    Employee[] employees = new Employee[size];
    int index = 0;

    while(input.hasNext()){
        String tmp= input.next();
        String[] commas = tmp.split(",");

        if(tmp.substring(0,1).equals("#")){
        employees[index++]=new Manager2(input.next(), input.next(), input.nextDouble() );
        }
        else if(tmp.substring(0,1).equals("*")){
        employees[index++]=new CommissionEmployee2(input.next(), input.next(), input.nextDouble(), input.nextDouble(), input.nextDouble());
        }
        else if(tmp.substring(0,1).equals("@")){
                employees[index++]=new HourlyWorker2(input.next(), input.next(), input.nextDouble(), input.nextDouble()); 
        }
         }

      input.close();

      for ( Employee currentEmployee : employees ){
          System.out.println( currentEmployee );
          }               
}

当我运行代码时,我得到了

 Exception in thread "main" java.util.InputMismatchException 
 at java.util.Scanner.throwFor(Unknown Source) 
 at java.util.Scanner.next(Unknown Source) 
 at java.util.Scanner.nextDouble(Unknown Source) 
 at PayRoll3.main(PayRoll3.java:19) 

1 个答案:

答案 0 :(得分:4)

使用charAt()来获取字符串的第一个字符,以决定要创建哪个对象。

使用nextLine()代替next()获取整行,然后使用split方法用逗号分隔整行。

使用substring(1)删除第一个字符。这将假设您希望整个字符串字符从第二个索引(从1开始)到字符串的结尾,从而最终为您提供所需的字符串,而不是第一个字符。

import java.util.Scanner;
import java.io.*;

public class PayRoll3{
public static void main(String[] args) throws FileNotFoundException{

    Scanner input=new Scanner(new File(args[0]));  
    int size=input.nextInt();
    input.nextLine();

    Employee[] employees = new Employee[size];
    int index = 0;

    while(input.hasNext()){
        String tmp= input.nextLine();
        String[] commas = tmp.split(",");

        if(commas[0].charAt(0) == '#'){
            employes[index++] = new Manager2(commas[0].substring(1), commas[1], Double.parseDouble(commas[2]));
        }
        else if (commas[0].charAt(0) == '*'){
            employes[index++] = new ComissionEmployee2(commas[0].substring(1), commas[1], Double.parseDouble(commas[2]), Double.parseDouble(commas[3]), Double.parseDouble(commas[4]));
        }
        else if (commas[0].charAt(0) == '@'){
        employes[index++] = new HourlyWorkey2(commas[0].substring(1), commas[1], Double.parseDouble(commas[2]), Double.parseDouble(commas[3]));
        }

    }

    input.close();

    for (Employee currentEmployee : employees ){
        System.out.println( currentEmployee );
    }