[java] Got a NumberFormatException while trying to parse a text file for objects

While trying to create objects and add them to an ArrayList using data from a text file, the program threw a NumberFormatException and I have absolutely no clue why, everything seemed OK to me. Here's the method in which the exception occurred:

static void read(String file) {     anime.clear();      try {         Scanner fin = new Scanner(file);          while (fin.hasNextLine()) {             String[] vals = fin.nextLine().split("[ ]");             anime.add(new Anime(Integer.parseInt(vals[0]),                                  vals[1],                                  Integer.parseInt(vals[2]),                                  Integer.parseInt(vals[3])));         }         fin.close();      } catch(Exception e) {         System.out.println("ERROR: Something went wrong!");         e.printStackTrace();         System.exit(-1);     }        } 

and here's the text file:

0 Angel_Beats! 13 2010 0 Baccano! 13 2007 0 Bakemonogatari 15 2009 0 Berserk 25 1997 0 Clannad 23 2007 

This question is related to java parsing numberformatexception

The answer is

The problem might be your split() call. Try just split(" ") without the square brackets.

NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc" value to integer..

this is valid string is eg"123". in your case split by space..

split(" "); will split line by " " by space..

Questions with java tag:

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error Instantiating a generic type When to create variables (memory management) java doesn't run if structure inside of onclick listener String method cannot be found in a main class method Are all Spring Framework Java Configuration injection examples buggy? Calling another method java GUI I need to know how to get my program to output the word i typed in and also the new rearranged word using a 2D array Java and unlimited decimal places? Read input from a JOptionPane.showInputDialog box Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable Two Page Login with Spring Security 3.2.x Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java) Got a NumberFormatException while trying to parse a text file for objects Best way for storing Java application name and version properties Call japplet from jframe FragmentActivity to Fragment Comparing two joda DateTime instances Maven dependencies are failing with a 501 error IntelliJ: Error:java: error: release version 5 not supported Has been compiled by a more recent version of the Java Runtime (class file version 57.0) Why am I getting Unknown error in line 1 of pom.xml? Gradle: Could not determine java version from '11.0.2' Error: Java: invalid target release: 11 - IntelliJ IDEA Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Why is 2 * (i * i) faster than 2 * i * i in Java? must declare a named package eclipse because this compilation unit is associated to the named module How do I install Java on Mac OSX allowing version switching? How to install JDK 11 under Ubuntu? Java 11 package javax.xml.bind does not exist IntelliJ can't recognize JavaFX 11 with OpenJDK 11 Difference between OpenJDK and Adoptium/AdoptOpenJDK OpenJDK8 for windows How to allow all Network connection types HTTP and HTTPS in Android (9) Pie? Find the smallest positive integer that does not occur in a given sequence Error: JavaFX runtime components are missing, and are required to run this application with JDK 11 How to uninstall Eclipse? Failed to resolve: com.google.firebase:firebase-core:16.0.1 How to resolve Unable to load authentication plugin 'caching_sha2_password' issue

Questions with parsing tag:

Got a NumberFormatException while trying to parse a text file for objects Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Python/Json:Expecting property name enclosed in double quotes Correctly Parsing JSON in Swift 3 How to get response as String using retrofit without using GSON or any other library in android UIButton action in table view cell "Expected BEGIN_OBJECT but was STRING at line 1 column 1" How to convert an XML file to nice pandas dataframe? How to extract multiple JSON objects from one file? How to sum digits of an integer in java? Pandas read_csv low_memory and dtype options How can I fix MySQL error #1064? Convert JSON String to JSON Object c# IsNumeric function in c# A JSONObject text must begin with '{' at 1 [character 2 line 1] with '{' error Parse json string to find and element (key / value) Retrieving values from nested JSON Object C# Parsing JSON array of objects Parsing JSON in Java without knowing JSON format Parse String date in (yyyy-MM-dd) format Jquery Smooth Scroll To DIV - Using ID value from Link Parsing JSON array into java.util.List with Gson Parsing Json rest api response in C# Parsing a pcap file in python In C#, how to check whether a string contains an integer? How can I parse a String to BigDecimal? PHP parse/syntax errors; and how to solve them PHP CSV string to array Reading input files by line using read command in shell scripting skips last line JSON Parse File Path Parse JSON file using GSON Parsing huge logfiles in Node.js - read in line-by-line Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss Splitting on last delimiter in Python string? How to avoid warning when introducing NAs by coercion Parser Error when deploy ASP.NET application Malformed String ValueError ast.literal_eval() with String representation of Tuple Loop through all elements in XML using NodeList Finding last occurrence of substring in string, replacing that Parse (split) a string in C++ using string delimiter (standard C++) JSON response parsing in Javascript to get key/value pair Extract data from XML Clob using SQL from Oracle Database Parse a URI String into Name-Value Collection Read and parse a Json File in C# ParseError: not well-formed (invalid token) using cElementTree Read .csv file in C How to install beautiful soup 4 with python 2.7 on windows Text File Parsing with Python Parsing JSON string in Java How to parse freeform street/postal address out of text, and into components

Questions with numberformatexception tag:

Got a NumberFormatException while trying to parse a text file for objects How can I prevent java.lang.NumberFormatException: For input string: "N/A"? Convert hex color value ( #ffffff ) to integer value How to avoid Number Format Exception in java? Double value to round up in Java