我需要在文本文件中写入数字,然后我必须阅读该文件,最后是数字。我可以写和读文件,但我不知道如何进行数学运算。
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
}
}
}
答案 0 :(得分:2)
使用Integer.parseInt(string)
将字符串转换为整数。然后你可以对它们进行正常的数学运算。
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
答案 1 :(得分:1)
我建议您使用扫描仪。
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);
打印
Numbers:
[1, 2]
Sum: 3
答案 2 :(得分:0)
尝试此更新代码(假设每行包含一个数字)。请参阅“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
}
}
}