SantyCortes94
SantyCortes94

Reputation: 3

How can I convert a Stream into an Int?

I need to write numbers in a text file, then I have to read the file, and finally sume the numbers. I can write and read the file, but I don´t know how to make the math opperation.

package clase.pkg13.de.septiembre;
import java.io.*;

public class FicheroTexto {
    public static void main (String args[]) {
        try {
            PrintWriter salida = new PrintWriter ( new BufferedWriter(new FileWriter("C:\\Users\\Santiago\\Desktop\\prueba.txt")));
            salida.println("1");
            salida.println("2");
            salida.close();

            BufferedReader entrada = new BufferedReader(new FileReader("C:\\Users\\Santiago\\Desktop\\prueba.txt"));
            String s, s2 = new String();
            while((s= entrada.readLine()) !=null)
                s2 = s2 + s + "\n";
            System.out.println("Numbers:"+"\n"+s2);
            entrada.close();
        } catch (java.io.IOException e) {
            // Do nothing
        }
    }
}

Upvotes: 0

Views: 280

Answers (3)

Trey Jonn
Trey Jonn

Reputation: 360

Try this updated code (which assumes that each line holds a single number). Refer to a tutorial on parsing integers from a String at 'Java - parseInt() Method'(http://www.tutorialspoint.com/java/lang/integer_parseint.htm) :

package clase.pkg13.de.septiembre;
import java.io.*;

public class FicheroTexto {
    public static void main (String args[]) throws Exception{
    try {
        PrintWriter salida = new PrintWriter ( new BufferedWriter(new FileWriter("C:\\Users\\Santiago\\Desktop\\prueba.txt")));
        salida.println("1");
        salida.println("2");
        salida.close();

        BufferedReader entrada = new BufferedReader(new FileReader("C:\\Users\\Santiago\\Desktop\\prueba.txt"));
        String s, s2 = new String();
        int sum = 0;
        while((s= entrada.readLine()) !=null)
        {
        s2 = s2 + s + "\n";
        sum += Integer.parseInt(s);

        }
        System.out.println("Numbers:"+"\n"+s2);
        System.out.println("Sum: " + sum);
        entrada.close();
    } catch (java.io.IOException e) {
        // Do nothing
    }
    }
}

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

I suggest you use a scanner.

PrintWriter salida = new PrintWriter (new FileWriter("prueba.txt"));
salida.println(1);
salida.println(2);
salida.close();

Scanner scanner = new Scanner(new FileReader("prueba.txt"));
long total = 0;
List<Long> longs = new ArrayList<>();
while(scanner.hasNextLong()) {
    long l = scanner.nextLong();
    longs.add(l);
    total += l;
}
scanner.close();
System.out.println("Numbers:\n" + longs);
System.out.println("Sum: " + total);

prints

Numbers:
[1, 2]
Sum: 3

Upvotes: 1

Colin D
Colin D

Reputation: 5661

Use Integer.parseInt(string) to convert your strings into integers. Then you can do normal math operations on them.

parseInt

public static int parseInt(String s)
                    throws NumberFormatException

Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.

Parameters:
    s - a String containing the int representation to be parsed
Returns:
    the integer value represented by the argument in decimal.
Throws:
    NumberFormatException - if the string does not contain a parsable integer.

http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

Upvotes: 2

Related Questions