简体   繁体   English

如何将Stream转换为Int?

[英]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
        }
    }
}

Use Integer.parseInt(string) to convert your strings into integers. 使用Integer.parseInt(string)将字符串转换为整数。 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 http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29

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

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 ) : 请参阅“ Java-parseInt()方法”( 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
    }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM