如何从txt文件中读取方程并获得这些方程系数,例如3.2x-5.6y=10
在txt文件中,我需要3.2
、-5.6
和10
来制作图形gui程序。
我试过bufferedreader
,但无法得到系数。
BufferedReader reader = null;
reader = new BufferedReader(new FileReader("input.txt"));
String line = reader.readLine();
这是解决方案。
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
/*
* Constructor just for test
*/
Test()
{
Equation equation = getMembers("-3.2x - 5.6y + 34 = -10");
System.out.print("Left members: ");
for(EquationMember m : equation.leftMembers)
System.out.print(m + " ");
System.out.print("nRight members: ");
for(EquationMember m : equation.rightMembers)
System.out.print(m + " ");
}
/*
* Main method
*/
public static void main(String args[])
{
new Test();
}
/*
* Transforms a strings representation of an equation into an Equation class
*/
Equation getMembers(String equationString)
{
Equation equation = new Equation();
String eq = equationString.replace(" ", "");
char[] charArray = eq.toCharArray();
boolean isLeft = true;
String lastMember = "";
for(int i = 0; i < charArray.length; i++)
{
if(charArray[i] == '-' || charArray[i] == '+' || charArray[i] == '=')
{
if(lastMember.length() > 0)
{
EquationMember m = new EquationMember();
m.constant = Float.parseFloat(match("([-+]?[\d\.]+)[A-Za-z]?", lastMember, 1));
m.variable = match("[\d\.]+([A-Za-z]?)", lastMember, 1);
if(isLeft)
equation.leftMembers.add(m);
else
equation.rightMembers.add(m);
}
lastMember = charArray[i] == '=' ? "" : String.valueOf(charArray[i]);
}
else
{
lastMember += charArray[i];
}
if(charArray[i] == '=')
{
isLeft = false;
}
}
EquationMember m = new EquationMember();
m.constant = Float.parseFloat(match("([-+]?[\d\.]+)[A-Za-z]?", lastMember, 1));
m.variable = match("[\d\.]+([A-Za-z]?)", lastMember, 1);
equation.rightMembers.add(m);
return equation;
}
/*
* Performs a regex match
*/
String match(String regexp, String text, int group)
{
Pattern p1 = Pattern.compile(regexp);
Matcher m1 = p1.matcher(text);
if(m1.find())
return m1.group(group);
else
return null;
}
/*
* Class that represents a single member inside an equation
*/
class EquationMember
{
float constant;
String variable;
public String toString()
{
return constant + "" + variable;
}
}
/*
* Class that represents an entire equation
*/
class Equation
{
ArrayList<EquationMember> leftMembers;
ArrayList<EquationMember> rightMembers;
Equation()
{
leftMembers = new ArrayList<EquationMember>();
rightMembers = new ArrayList<EquationMember>();
}
}
}
使用扫描仪对象。您可以使用它来使用RegExp或任何其他您想要的工具解析一行。
您提到了split
,那么为什么不将字符串拆分为任何非数字的字符串呢?
final String s = "3.2x-5.6y=10";
String[] result = s.split("([^\d\.\+\-])+");
System.out.println(Arrays.toString(result));
// [3.2, -5.6, 10]
该正则表达式不适用于一般数字情况(考虑123456或无效输入+24-.2),但可以根据需要进行修复。
这并不能使变量与系数匹配,但您声明只需要值。