Good day. The problem when compiling java code below.

The essence of the program:

  1. it must read the file name from the console;
  2. read this file (the file contains integer values ​​in a column, i.e., each new number from a new row);
  3. write to the ArrayList array.

     import java.io.*; import java.util.ArrayList; public class Class1 { public static void main(String[] args) throws IOException { try { BufferedReader bufR = new BufferedReader(new InputStreamReader(System.in)); FileInputStream input = new FileInputStream(bufR.readLine()); ArrayList<Integer> ints = new ArrayList<>(); StringBuilder sbd = new StringBuilder(); while (input.available() > 0) { char ch = (char) input.read(); if (ch == '\n') { ints.add(new Integer(sbd.toString())); sbd.delete(0, sbd.length()); } else { sbd.append(ch); } } bufR.close(); input.close(); } catch (IOException e) { } } } 

enter image description here

Problem in line:

 ints.add(new Integer(sbd.toString())); 

But I do not know why. I tried parsing, it also does not work. Perhaps the problem is different, and this is only a consequence? I will be glad to any hint!

  • Bring the contents of the file - Peter Samokhin

2 answers 2

In the file, at the end of each line are special characters. Usually these are: line feed and carriage return (\ r \ n). This can be seen in the debug. As a result, you are not trying to string the string "123" in the Integer, but the string " 123 \ r ".

The simplest solution is to trim leading and trailing spaces and similar special characters through the trim() method:

 ints.add(new Integer(sbd.toString().trim())); 
  • It turns out because of what! I thought that carriage transfer already implies line feed) Now I will know. Thank! - Azad Mamedov
  • That's right, carriage return and line feed are separate independent characters. - Mikhail Grebenev

It is necessary to look at the source file, perhaps there is a Window line ending.

Then you need to do a check like this:

  if (ch == '\ n' || ch == '\ r') {