SMOKEN

23 views
Skip to first unread message

Ira Ragle

unread,
Apr 27, 2020, 6:44:00 AM4/27/20
to I<code> GO
import java.util.Scanner;

// This will solve any linear equation for one variable.
// ie: 2x+5=4x+9

class LEquation
{
public static void main(String args[])
{
String eqn = "";
float ans = 0;
float coeffSum = 0;
float constSum = 0;
float coeffx[] = new float[100];
float[] constant = new float[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter a linear equation\n");
eqn = in.nextLine();
eqn += "\n";
System.out.println(eqn);
for (int i = 0, j = 0, k = 0; i < eqn.length() - 1;)
{
if (eqn.charAt(i + 1) == 'x' && i < eqn.indexOf("="))
{
if (i != 0 && eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
coeffx[j++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
coeffx[j++] = n;
}
}
i += 3;
}
if (eqn.charAt(i + 1) == 'x' && i > eqn.indexOf("="))
{
if (eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
coeffx[j++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
coeffx[j++] = n;
}
}
i += 3;
}
if (eqn.charAt(i + 1) != 'x' && i < eqn.indexOf("="))
{
if (eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
constant[k++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
constant[k++] = n;
}
}
i += 2;
}
if (eqn.charAt(i + 1) != 'x' && i > eqn.indexOf("="))
{
if (eqn.charAt(i - 1) == '-')
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = Integer.parseInt(x, 10);
constant[k++] = n;
}
} else
{
String x = eqn.substring(i, i + 1);
if (x != "+" && x != "-")
{
int n = -(Integer.parseInt(x, 10));
constant[k++] = n;
}
}
i += 2;
}

}
for (int i = 0; i < coeffx.length; i++)
coeffSum += coeffx[i];
for (int i = 0; i < constant.length; i++)
constSum += constant[i];
ans = constSum / coeffSum;
System.out.println("Value of x = " + (-ans));
in.close();
}

}

John TZ

unread,
Apr 27, 2020, 9:08:17 PM4/27/20
to I<code> GO
I came up with an interesting solution using eval of js
Screenshot_20200428-083451660.jpg

Ira Ragle

unread,
May 21, 2020, 11:42:40 PM5/21/20
to I<code> GO
Reply all
Reply to author
Forward
0 new messages