Java substring difficulty -
i know how use substring()
why isn't working, user inputs equation "5t + 1" space before , after "+". want tvariable
hold integer before it, in case 5
, constant should hold constant integer in case 1
, out of range error.
import java.util.*; import javax.swing.joptionpane; public class project3030 { public static void main(string[] args) { string l1x, tvariable, constant; l1x = joptionpane.showinputdialog("this format (x=5t + 1)"); int endindex = l1x.indexof("t"); tvariable = l1x.substring(0, endindex); int beginindex = l1x.lastindexof(" "); int endindex2 = l1x.indexof(""); constant = l1x.substring(beginindex, endindex2); system.out.println(tvariable + constant); } }
you need change more like
constant = l1x.substring(l1x.lastindexof(" ")).trim();
then when add numbers, have parse them before add them.
int constantint = integer.parseint(constant);
or use solution:
string[] input = l1x.split(" "); // remove 't' string tnum = input[0].substring(0, input[0].length() - 1); int t = integer.parseint(tnum); int constant = integer.parseint(input[2]); string operator = input[1]; if (operator == "-") constant *= -1;
Comments
Post a Comment