Good morning, I am having some problems in a Java exercise that I had in my class. What I need to do is in a .txt input file put any content either words or numbers but at the time of having an operation, the result should be shown in an output .txt file along with the text you have written.
At the moment I was able to realize that the contents of the input file will be reflected in the output file, but I have problems in the operations part.
I have this code where I try to carry out the operations but it marks me an error when entering the names, this is:
C: \ Users \ PC \ Desktop> java miCalc enter.txt output.txt Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at miCalc. (miCalc.java:35) at miCalc.main (miCalc.java:11)
import java.io.*;
public class miCalc{
String input, output;
char operacion;
String[] num;
float resultado;
String dataFiles;
public static void main(String args[]){
String input = args[0];
String output = args[1];
miCalc fileOp = new miCalc(input,output);
}
public miCalc(String input, String output){
this.input = input;
this.output = output;
try{
File f1 = new File(input);
FileInputStream fstream = new FileInputStream(f1);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
FileWriter fw = new FileWriter(output,true);
BufferedWriter bw = new BufferedWriter(fw);
do{
dataFiles=br.readLine();
if(dataFiles!=null){
for(int i=0;i<dataFiles.length();i++){
if(dataFiles.charAt(i)=='+' || dataFiles.charAt(i)=='-' || dataFiles.charAt(i)=='*' || dataFiles.charAt(i)=='/'){
operacion=dataFiles.charAt(i);
}
}
String c=operacion+"";
num=dataFiles.split("\"+c);
if(operacion=='+'){
resultado=Float.parseFloat(num[0])+Float.parseFloat(num[1]);
bw.write(resultado+"");
bw.newLine();
}
else if(operacion=='-'){
resultado=Float.parseFloat(num[0])-Float.parseFloat(num[1]);
bw.write(resultado+"");
bw.newLine();
}
else if(operacion=='*'){
resultado=Float.parseFloat(num[0])*Float.parseFloat(num[1]);
bw.write(resultado+"");
bw.newLine();
}
else if(operacion=='/'){
resultado=Float.parseFloat(num[0])/Float.parseFloat(num[1]);
bw.write(resultado+"");
bw.newLine();
}
}
}while(dataFiles!=null);
br.close();
bw.close();
}
catch(FileNotFoundException e){}
catch(IOException e){}
}
}
Any idea what might be causing the error?
Thank you.