2014-11-08 3 views
-1

Я использую BlueJ, для справки.Получение java.lang.NumberFormatException при выводе

Программа компилируется в порядке. Он прекрасно работает, а кроме того, что это:

java.lang.NumberFormatException: For input string: "Washington,George" 
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2043) 
at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110) 
at java.lang.Double.parseDouble(Double.java:538) 
at WorkerApp.main(WorkerApp.java:53) 
at __SHELL112.run(__SHELL112.java:6) 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
at java.lang.reflect.Method.invoke(Method.java:483) 
at bluej.runtime.ExecServer$3.run(ExecServer.java:730) 

частности подсветка:

java.lang.NumberFormatException: For input string: "Washington,George" 

    at WorkerApp.main(WorkerApp.java:53) 

Суть этой программы заключается, чтобы прочитать текстовый файл и добавить в указанный текстовый файл.

Программа должна читать и открытым «EmployeeData.txt»:

S  Washington,George  000001  125000 
H MacDonald,Ronald  386218  7.80 true 40 
H  Walton,Samuel   268517 8.21 false 
H Thomas,David   131313 9.45 true 38 
H Sanders,HarlandDavid 277651 8.72 false 
S Baron,James   368535 310236 

Когда я нажимаю на исключении он подчеркивает это от моего основного класса

double salary = Double.parseDouble(Employee[3]); 

Это полное основного класс WorkerApp, в котором я пытаюсь прочитать и открыть текстовый файл:

import java.io.*; 
import java.util.*; 
public class WorkerApp{ 
/** 
* Reads the infile, runs tests, and prints the output. 
*/ 
public static void main (String args[]){ 
    Company company = new Company(); 
    try{ 
     Scanner reader = new Scanner (new File("EmployeeData.txt")); 
     while(reader.hasNext()){ 
      String line = reader.nextLine(); 
      String Employee[] = line.split(" "); 
      String sorh = Employee[0]; 
      String name = Employee[1]; 
      String id = Employee[2]; 
      double salary = Double.parseDouble(Employee[3]); 
      Employee e; 
      if (Employee[0].equals("S")){ 
       e = new SalariedWorker(sorh, name, id, salary);} 
      else { 
       boolean overtime = Boolean.parseBoolean(Employee[4]); 
       if(overtime){ 
        int maxHours = Integer.parseInt(Employee[5]); 
        e = new HourlyWorker(sorh, name, id, salary, maxHours); 
       } 
       else{ 
        e = new HourlyWorker(sorh, name, id, salary); 
       } 
      } 
      company.add(e); 
     } 
    }catch (Exception err){ 
     //System.out.println(err); 
     err.printStackTrace(); 
    } 

    company.print(); 
    System.out.println(); 

    //Test Number 1 
    System.out.println("1) Add a salaried worker"); 
    SalariedWorker SWorker1 = new SalariedWorker("S", "Moran,Blake", "123456", 260000); 
    company.add(SWorker1); 
    company.print(); 

    //Test Number 2 
    System.out.println("2) Add an hourly worker who has no overtime allowed"); 
    HourlyWorker HWorker1 = new HourlyWorker("H", "Bob,Billy", "654321", 15); 
    company.add(HWorker1); 
    company.print(); 

    //Test Number 3 
    System.out.println("3) Add an hourly worker who has overtime allowed"); 
    HourlyWorker HWorker2 = new HourlyWorker("H", "Smith,Will", "345612", 10.5, 30); 
    company.add(HWorker2); 
    company.print(); 

    //Test Number 4 
    System.out.println("4) Add a worker that is already in the database"); 
    try{ 
     company.add(SWorker1); 
    }catch(Exception err){ 
     System.out.println(err); 
     System.out.println(); 
    } 

    //Test Number 5 
    System.out.println("5) Print the sorted list"); 
    company.print(); 

    //Test Number 6 
    System.out.println("6) Remove a worker who is NOT in the list"); 
    company.remove("Brooks,Phil"); 
    System.out.println(); 

    //Test Number 7 
    System.out.println("7) Remove a worker who is the first in the list "); 
    company.remove("Moran,Blake"); 
    company.print(); 
    System.out.println(); 

    //Test Number 8 
    System.out.println("8) Find a worker who is the middle of the list"); 
    int index = company.find("Bob,Billy"); 
    System.out.println("Found at "+ index); 
    System.out.println(); 

    //Test Number 9 
    System.out.println("9) Find a worker who is NOT in the list"); 
    index = company.find("Harrison,Ford"); 
    System.out.println("Found at "+ index); 
    System.out.println(); 

    //Test Number 10 
    System.out.println("10) Find the weekly salary of a worker who is salaried"); 
    System.out.println(SWorker1.FindSalary()); 
    System.out.println(); 

    //Test Number 11 
    System.out.println("11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours]"); 
    System.out.println(HWorker1.FindSalary(50)); 
    System.out.println(); 

    //Test Number 12 
    System.out.println("12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours]"); 
    System.out.println(HWorker2.FindSalary(50)); 
    System.out.println(); 

    //Test Number 13 
    System.out.println("13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours]"); 
    System.out.println(HWorker2.FindSalary(20)); 
    System.out.println(); 

    //Test Number 14 
    System.out.println("14) Print the sorted list"); 
    company.print(); 

    //Test Number 15 
    System.out.println("\n15) End the process"); 
} 
} 

Следует отметить, что в верхней части исключения он выплевывает этот вывод:

1) Add a salaried worker 
S Moran,Blake 123456 260000.0 
2) Add an hourly worker who has no overtime allowed 
S Moran,Blake 123456 260000.0 
H Bob,Billy 654321 15.0 false 
3) Add an hourly worker who has overtime allowed 
S Moran,Blake 123456 260000.0 
H Bob,Billy 654321 15.0 false 
H Smith,Will 345612 10.5 true 30 
4) Add a worker that is already in the database 
java.lang.RuntimeException: The Employee Is Not New 

5) Print the sorted list 
S Moran,Blake 123456 260000.0 
H Bob,Billy 654321 15.0 false 
H Smith,Will 345612 10.5 true 30 
6) Remove a worker who is NOT in the list 
The Employee is not Found 

7) Remove a worker who is the first in the list 
H Bob,Billy 654321 15.0 false 
H Smith,Will 345612 10.5 true 30 

8) Find a worker who is the middle of the list 
Found at 0 

9) Find a worker who is NOT in the list 
Found at -1 

10) Find the weekly salary of a worker who is salaried 
5000.0 

11) Find the weekly salary of an hourly worker who has no overtime allowed [50 hours] 
750.0 

12) Find the weekly salary of an hourly worker who has overtime allowed [50 hours] 
630.0 

13) Find the weekly salary of an hourly worker who has overtime allowed [20 hours] 
210.0 

14) Print the sorted list 
H Bob,Billy 654321 15.0 false 
H Smith,Will 345612 10.5 true 30 

15) End the process 

Если это помогает, вот мои другие классы для справки, так как они могут быть источником проблемы.

Company:

import java.io.*; 
import java.util.*; 
public class Company{ 
private Employee[] employeeArray; 
private final int InitialCapacity = 7; 
private int employCount; 

/** 
* Creates the employee array and sets employCount to 0. 
*/ 
public Company(){ 
    employeeArray = new Employee[InitialCapacity]; 
    employCount = 0; 
} 

/** 
* Finds an employee in the list. 
*/ 
public int find(String name){ 
    for (int i = 0; i < employCount; i++){ 
     if (employeeArray[i].getName().equals(name)){ 
      return i; 
     } 
    } 

    return -1; 
} 

/** 
* Adds an employee to the list. 
*/ 
public int add(Employee employ){ 
    int index; 
    for (index = 0; index < employCount; index++){ 
     int result = employeeArray[index].getName().compareTo(employ.getName()); 
     if(result == 0){ 
      throw new RuntimeException ("The Employee Is Not New"); 
     } 
    } 

    if (employeeArray.length == employCount){ 
     expand(); 
    } 

    employeeArray[index] = employ; 
    employCount++; 
    return index; 
} 

/** 
* Removes an employee to the list. 
*/ 
public void remove(String name){ 
    int index = find(name); 
    if (index == -1){ 
     System.out.println("The Employee is not Found"); 
     return; 
    } 

    for (int i = index; i < employCount - 1; i++){ 
     employeeArray[i] = employeeArray[i + 1]; 
    } 

    employCount--; 
} 

/** 
* Prints the list. 
*/ 
public void print(){ 
    if(employCount == 0){ 
     System.out.println("The List is Empty"); 
     return; 
    } 

    for(int i = 0; i < employCount; i++){ 
     System.out.println(employeeArray[i]); 
    } 
} 

/** 
* Expands the list. 
*/ 
private void expand(){ 
    Employee[] newArray = new Employee[employeeArray.length + InitialCapacity]; 
    for (int i = 0; i < employeeArray.length; i++){ 
     newArray[i] = employeeArray[i]; 
    } 

    employeeArray = newArray; 
} 
} 

Employee:

import java.io.*; 
import java.util.*; 
public class Employee{ 
private String SorH; 
private String name; 
private String ID; 

/** 
* Sets sets SorH, name, and ID to SH, n, and id. 
*/ 
public Employee (String SH, String n, String id){ 
    SorH = SH; 
    name = n; 
    ID = id; 
} 

/** 
* Gets the first part (S or H) of the employee list. 
*/ 
public String getSorH(){ 
    return SorH; 
} 

/** 
* Gets the name of the employee list. 
*/ 
public String getName(){ 
    return name; 
} 

/** 
* Gets the ID of the employee list. 
*/ 
public String getID(){ 
    return ID; 
} 

/** 
* Sets SorH to SH. 
*/ 
public void setSorH(String SH){ 
    SorH = SH; 
} 

/** 
* Sets name to n. 
*/ 
public void setName(String n){ 
    name = n; 
} 

/** 
* Sets ID to id. 
*/ 
public void setID(String id){ 
    ID = id; 
} 

/** 
* Returns a string representing the employee list. 
*/ 
public String toString(){ 
    return String.format("%s %s %s", getSorH(), getName(), getID()); 
} 
} 

HourlyWorker:

import java.io.*; 
import java.util.*; 
public class HourlyWorker extends Employee{ 
private double hourlySalary; 
private boolean overtime; 
private int maxHours; 

/** 
* Contains the super and sets the hourly salary and maxHours to hourlySal and maxH and 
* overtime to true. 
*/ 
public HourlyWorker(String SH, String n, String id, double hourlySal, int maxH){ 
    super(SH, n, id); 
    hourlySalary = hourlySal; 
    overtime = true; 
    maxHours = maxH; 
} 

/** 
* Contains the super and sets the hourly salary to hourlySal and overtime to false. 
*/ 
public HourlyWorker(String SH, String n, String id, double hourlySal){ 
    super(SH, n, id); 
    hourlySalary = hourlySal; 
    overtime = false; 
} 

/** 
* Returns if overtime is true or false. 
*/ 
public boolean overtime(){ 
    return overtime; 
} 

/** 
* Gets the max hours of an hourly worker. 
*/ 
public int getmaxH(){ 
    return maxHours; 
} 

/** 
* Gets the hourly salary of an hourly worker. 
*/ 
public double gethourlySalary(){ 
    return hourlySalary; 
} 

/** 
* Sets hourly salary to hSalary. 
*/ 
public void sethourlySalary (double hSalary){ 
    hourlySalary = hSalary; 
} 

/** 
* Finds the weekly salary of an hourly worker. 
*/ 
public double FindSalary(double hoursWorked){ 
    if (overtime){ 
     if (hoursWorked <= maxHours){ 
      return hoursWorked * hourlySalary; 
     } else{ 
      return maxHours * hourlySalary + 
           (hoursWorked - maxHours) * hourlySalary * 1.5; 
     } 
    } else{ 
     return hoursWorked * hourlySalary; 
    } 
} 

/** 
* Contains the super string and adds onto the string. 
*/ 
public String toString(){ 
    String str = super.toString() + String.format(" %s %s", gethourlySalary(),overtime()); 

    if (overtime){ 
     str = str + String.format(" %s", getmaxH()); 
    } 

    return str; 
} 
} 

SalariedWorker:

import java.io.*; 
import java.util.*; 
public class SalariedWorker extends Employee{ 
private double yearlySalary; 

/** 
* Contains the super and sets yearly salary to ySalary. 
*/ 
public SalariedWorker(String SH, String n, String id, double ySalary){ 
    super(SH, n, id); 
    yearlySalary = ySalary; 
} 

/** 
* Gets the yearly salary of a salaried worker. 
*/ 
public double getyearlySalary(){ 
    return yearlySalary; 
} 

/** 
* Sets the yearly salary of a salaried worker. 
*/ 
public void setyearlySalary(double ySalary){ 
    yearlySalary = ySalary; 
} 

/** 
* Finds the weekly salary of a salaried worker. 
*/ 
public double FindSalary(){ 
    return yearlySalary/52; 
}  

/** 
* Contains the super string and adds onto the string. 
*/ 
public String toString(){ 
    return super.toString() + String.format(" %s", getyearlySalary()); 
} 
} 

Спасибо заранее!

+1

Скажите, какой номер * Вашингтон, Джордж *? –

+1

Не публикуйте весь ваш код. Вместо этого создайте [SSCCE] (http://sscce.org/). Существует даже большая вероятность того, что вы найдете корень своей проблемы (а может быть, даже решение) при ее создании, поэтому определенно стоит потратить ваше время на создание. – Pshemo

ответ

2

Вместо line.split(" "); вы можете попробовать line.split("\\s+"). Я думаю, что расщепление происходит неправильно.

+0

Это привело к тому, что текстовый файл появился на моем выходе, спасибо! Единственная проблема в том, что когда я запускаю код, он показывает только нижнюю половину моего вывода, более конкретно он отображает вторую половину из 5), а остальное. Ничего раньше. – BBladem83

0

У вас нет доступа к отладчику? Должен быть один в любой IDE, которую вы можете использовать, будь то Netbeans, Eclipse, IntelliJ или ...

Просто поставьте точку останова на строке, где возникает исключение, и посмотрите на значения в массиве Employee. Причина ошибки должна быть очевидна.

В случае, если это еще не очевидно для вас, вот следующая подсказка: прочитайте снова javadoc для String.split() и сравните с тем, что у вас есть в Employee.

Смежные вопросы