Read in 5 likes of Equations from a text file and then solve them equations and display their final answer *oerder of operation not required. Also there will be an x that we will have to ask the user to enter the value of Well here is my text file
4 + 10 - 20 / 3 * x 4 + 10 - 20 / 3 * x 4 + 10 - 20 / 3 * x 4 + 10 - 20 / 3 * x 4 + 10 - 20 / 3 * x
Here is my code and it tells me i can't divide by zero...
import java.util.*;
import java.io.*;
public class SS24 {
public static void main(String[] args) throws IOException {
double dAns;
equation arCequations[] = new equation[5];
String sLine;
Scanner sin = new Scanner(new FileReader("Eq.txt"));
for (int i = 0; i < 5; i++) {
arCequations[i] = new equation();
sLine = sin.nextLine();
dAns = arCequations[i].populate(sLine);
System.out.println(dAns);
}
}
}
class equation {
Scanner sin = new Scanner(System.in);
String sChar, sLine;
int nString = 0, nX, nInt = 0;
boolean bCheck = false;
int[] arnNumbers = new int[6];
char[] arcStrings = new char[4];
double dAns;
char arcTest[] = {'+', '-', '/', '*', 'x'};
double populate(String _sLine) {
sLine = _sLine;
for (int i = 0; i < sLine.length(); i++) {
for (int j = 0; j < arcTest.length; j++) {
if (sLine.charAt(i) == arcTest[j]) {
if (sLine.charAt(i) == 'x') {
System.out.println("Enter value of X");
nX = sin.nextInt();
arnNumbers[nInt] = nX;
bCheck = true;
nInt++;
} else {
arcStrings[nString] = sLine.charAt(i);
bCheck = true;
nString++;
}
}
}
if (sLine.charAt(i) != ' ' && !bCheck) {
System.out.println(nInt);
arnNumbers[nInt] += (int) sLine.charAt(i);
System.out.println(arnNumbers[nInt]);
nInt++;
}
}
dAns = calculate(arnNumbers, arcStrings);
return dAns;
}
double calculate(int arnNumbers[], char[] arcOperators) {
double dFinal = 0;
for (int i = 0; i < arnNumbers.length - 2; i++) {
if (arcOperators[i] == '+') {
dFinal = arnNumbers[i] + arnNumbers[i + 1];
}
if (arcOperators[i] == '-') {
dFinal = arnNumbers[i] - arnNumbers[i + 1];
}
if (arcOperators[i] == '*') {
dFinal = arnNumbers[i] * arnNumbers[i + 1];
}
if (arcOperators[i] == '/') {
System.out.println(arnNumbers[i]+" "+arnNumbers[i+3]);
dFinal = arnNumbers[i] / arnNumbers[i + 1];
}
}
return dFinal;
}
}
Stack trace
Exception in thread "main" java.lang.ArithmeticException: / by zero at equation.calculate(SS24.java:76) at equation.populate(SS24.java:58) at SS24.main(SS24.java:15) Java Result: 1
for some reason the integer that gets accumulated to the array is not correct ....
help plox
This post has been edited by JavaSuperNoob: 11 June 2012 - 05:31 PM

New Topic/Question
Reply



MultiQuote



|