2016-05-08 2 views
1

У меня возникает следующая ошибка при компиляции и запуске моей программы. Что я пропустил в форматировании?numberformatexception error on output

мой CSV-файл выглядит следующим образом:

Дэвид, Curtis, 138, W Plumtree Ln, 8012985656 Пол Тейлор, 99, Wikapee St, 8015984578

Exception in thread "main" java.lang.NumberFormatException: For input string: "8012985656" 
    at java.lang.NumberFormatException.forInputString(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at java.lang.Integer.parseInt(Unknown Source) 
    at database.DataEntry.createContactInfo(DataEntry.java:76) 
    at database.DataEntry.readcontactlistFromCSV(DataEntry.java:49) 
    at database.DataEntry.main(DataEntry.java:15) 

Это моя основная

package database; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.nio.charset.StandardCharsets; 
import java.nio.file.Files; 
import java.nio.file.Path; 
import java.nio.file.Paths; 
import java.util.ArrayList; 
import java.util.List; 

public class DataEntry { 

     public static void main(String...args) { 
      List<ContactInfo> contactlist = readcontactlistFromCSV("C:\\Users\\dcurtis\\Desktop\\DataBaseContactList.csv"); 

      for (ContactInfo c : contactlist) { 
       System.out.println(c); 

     } 
    } 

    private static List<ContactInfo> readcontactlistFromCSV(String DataBaseContactList) { 
      List<ContactInfo> contactlist = new ArrayList<>(); 

      Path pathToFile = Paths.get("C:\\Users\\dcurtis\\Desktop\\DataBaseContactList.csv"); 

      //create an instance of BufferedReader 
      //using try with resource 


      try (BufferedReader br = Files.newBufferedReader(pathToFile, 
        StandardCharsets.US_ASCII)) { 

       //READ THE FIRST line from the text file 

       String line = br.readLine(); 

       //loop until all lines are read 

       while (line != null) { 

        //use string.split to load a string array with the values from 
        //each line of the file 
        //using a comma as the delimiter 

        String[] attributes = line.split(","); 

        ContactInfo contactlist1 = createContactInfo(attributes); 

        // add a contact into ArrayList 

        contactlist.add(contactlist1); 

        //read next line before looping 
        //if end of file reached, line would be null 

        line = br.readLine(); 

       } 

      } catch (IOException ioe) { 
       ioe.printStackTrace(); 

      } 

return contactlist; 

} 

private static ContactInfo createContactInfo(String[] metadata) { 
    String firstName = metadata[0]; 
    String lastName = metadata[1]; 
    int addressNumber = Integer.parseInt(metadata[2]); 
    String addressStreet = metadata[3]; 
    int phoneNumber = Integer.parseInt(metadata[4]); 

    //create and return contact of this metadata 

    return new ContactInfo(firstName, lastName, addressNumber, addressStreet, phoneNumber); 

    } 

} 

Это мой класс ContactInfo

package database; 


import java.util.*; 



public class ContactInfo { 
    Scanner input = new Scanner(System.in); 

private String firstName; 
private String lastName; 
private int addressNumber; 
private String addressStreet; 
private int phoneNumber; 

public ContactInfo(String firstName, String lastName, int addressNumber, String addressStreet, int phoneNumber) { 
    this.firstName = firstName; 
    this.lastName = lastName; 
    this.addressNumber = addressNumber; 
    this.addressStreet = addressStreet; 
    this.phoneNumber = phoneNumber; 

} 
// get the first name when called 
public String getFirstName() { 
return firstName; 

} 

//sets the first name for user or throught the application 
public void setFirstName(String firstName) { 
this.firstName = firstName; 

} 

//gets the last name when called 
public String getLastName() { 
return lastName; 

} 

//sets the last name though the user or application 
public void setLastName(String lastName) { 
this.lastName = lastName; 

} 

// gets the number of the address when called 
public float getAddressNumber() { 
return addressNumber; 
    } 

boolean realNumber; 
    //sets the address number from the user or through the application 

public void setAddressNumber(int addressNumber) { 
//checks to make sure they are only entering intergers 

    if (input.hasNextInt()) { 
     this.addressNumber = addressNumber; 
     realNumber = true; 
    } else { //returns an error message if an invalid number is entered 
     System.out.println("This is not a valid address number. Please eneter again."); 
     realNumber = false; 
     input.next(); 

     } 

} 

// gets the street name 

public String getAddressStreet() { 
return addressStreet; 

} 

//sets the street name by the user or trhough application 

public void setAddressStreet(String addressStreet) { 
this.addressStreet = addressStreet; 

} 

//gets a phone number when called 

public double getPhoneNumber() { 
return phoneNumber; 

} 

//sets a phone number by user or through application 

public void setPhoneNumber(String phoneNumber) { 

//removes any non number and converts to the next comment 

String onlyNums = phoneNumber.replaceAll("[^\\d.]", ""); 

// onlyNums == "8" 

if (onlyNums.length() != 10) { 

System.out.println("Not a vaild number. Please enter 10-digit number."); 

} else { 

this.phoneNumber = Integer.parseInt(onlyNums); 
} 
} 
} 
+2

Что представляет собой наибольшее значение для int? Это больше, чем тот, который вы пытаетесь разобрать? –

+0

Никогда не храните телефонные номера как «номер». В идеале это их собственный объект домена. Как минимум, это строка. – KevinO

+2

Теперь было бы неплохо научиться сокращать проблемы до [mcve] - вам действительно нужна только одна активная строка кода, чтобы продемонстрировать проблему ... вызов Integer.parseInt с этим значением. Затем поместите это в полную программу, чтобы облегчить для всех, кто читает вопрос, и у вас все еще есть только 6 строк кода ... –

ответ

0

Целочисленный максимальный размер составляет 2,147,483,647, вы пытаетесь разобрать 8,012,985,656.

Используйте вместо этого Long и Long.valueOf().

+0

А что происходит, когда телефон "011 64 3 477 4000"? Ведущий 0 будет вызывать проблемы. Этот ответ может решить немедленный вопрос ОП, но это не очень хорошее предложение в долгосрочной перспективе. Не ответит DV, но этот подход обычно не применим. – KevinO