Question
JAVA CODE NEEDED! The formNum() method has to be rewritten so that it scans from left to right when it encounters the leftmost digit of
JAVA CODE NEEDED!
The formNum() method has to be rewritten so that it scans from left to right when it encounters the leftmost digit of a number or a leading decimal point. Of course the method of building up the double value from the successive digits has to be adjusted since you are scanning from left to right- try some examples to discover the correct approach
MY CODE:
import java.util.Scanner;
//class for evaluating arithmetic expressions public class Expr { Scanner kb = new Scanner(System.in);
//variables for an Expr object private String e; private int p; //pointer to characters within the expression string e private int len;
//constructor public Expr() { System.out.println("Enter an expression"); e = kb.nextLine(); //input a string as a line of keyboard input. len = e.length(); p = len-1; //position pointer at right end of the expression }
//print the current character and advance the pointer (to the left) public void printChar() { System.out.println(e.charAt(p)); p = p-1; }
public String getExpr() { return e; }
public int getp() { return p; }
public void setp(int pp) { p = pp; }
//if string e represents a number (possibly with a decimal point, possibly negative), //return the numerical value of the string as a double value public double formNum() { double total = 0.0; int count = 0; int flag = 0; double mult = 1.0; char c,d; do { c = e.charAt(p); //examine the current character in the string (from right to left) if(c == '.') { flag = 1; //set a flag to remember that the character is a decimal point } else { //if the current character is a digit, convert to its //int value and include it in the value corresponding to the string. if((c >= '0') && (c<= '9')) { total = total + mult*(c-'0'); mult = mult*10.0; if(flag==0) { count++; //count the number of digits to the right of a possible decimal point } } else { if(c == '_') { total = -total; //an underscore character represents a negative value } } } p--; //prepare to move to the next character to the left d = '?'; if(p>= 0) { d = e.charAt(p); //the next character to the left } }while((p>=0) && (((d<='9')&&(d>='0'))||(d=='_')||(d=='.')));//check for a valid character if(flag==1) { total = total/Math.pow(10.0,count*1.0); //compute the value taking into account //the number of decimal places } return total; } }
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started