java read comma separated integers from textfile and store each as integer

Question

I want to scan comma separated integers from a text file and store them as single variable. i.e two integers from each line of input.txt and

import java.io.*; 
import java.io.BufferedReader;
import java.io.FileReader;

public class ReadingFiles{


public String  int_to_String(int i){
     String p= Integer.toString(i);
        return p;
    }

    public String str_Reverse(String j){
        String q = new StringBuilder(j).reverse().toString();
        return q;
    }

    public int str_to_Int(String k){
        int r = Integer.parseInt(k);
        return r;
    }

Read File and Scan the integers from file and store them as integer variable

  public static void main(String [] args){


   try {
      BufferedReader in = new BufferedReader(new FileReader("input.txt")); 
      //input.txt file contains integer values separated by comma 
      String str;
      str = in.readLine();
      while ((str = in.readLine()) != null) {
          System.out.println(str);
          String [] ar=str.split(",");

          int first = Integer.parseInt(ar[0]); //get first= 199 from input.txt 
          int sec = Integer.parseInt(ar[1]);   //get sec = 911 from input.txt 

call the class and perform opeartion with integer variables obtained from input.txt

       ReadingFiles ps = new ReadingFiles();
       String m=    ps.int_to_String(first);
       String n =   ps.int_to_String(sec);

      m=ps.str_Reverse(m);
      n=ps.str_Reverse(n);

      first=ps.str_to_Int(m);
      sec=ps.str_to_Int(n);
      int sum =first+sec;

      String  sume = ps.int_to_String(sum);

       sume = ps.str_Reverse(sume);

       String value;
       if (sume.startsWith("0")){
          value=sume.substring(1);
       }else {
         value=sume; 
       }
        sum =ps.str_to_Int(value);
       System.out.println(sum); 

      }
      in.close();
  } catch (IOException e) {
      System.out.println("File Read Error");
  }

} 

    }

CSV:

199, 911
119, 991
24, 13

Expected Output: 111 111 37 current Output

    119, 991
    Exception in thread "main" java.lang.NumberFormatException: For input                           string: " 991"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at ProblemSolve.ReadingFiles.main(ReadingFiles.java:37)

Show source
| java   | integer   | io   2017-01-04 22:01 0 Answers

Answers to java read comma separated integers from textfile and store each as integer ( 0 )

Leave a reply to - java read comma separated integers from textfile and store each as integer

◀ Go back