Four mixed operation of Java writing

Source: Internet
Author: User
Operation recently wrote a small program in Java, do not dare to enjoy alone.

This is a four mixed operation program, nothing to do optimization, also did not do any annotation, (people ah, always like lazy.)

This version I have set for the 2.21 version. Hehe.

From the first 1.0 to 2.0 of the changes are very large. In addition to the operation of the idea did not move, the others in the 2.0 did redesign.

This program is actually a lot of online (the algorithm is much better). This is just boring to find something to do.

/**
* Four mixed operation program
* Author: Huang Jianwu
* Time: April 29, 2005
* Version: 2.21
* Change log: 2.0
* 1. Change the expression user input method.
* 2. Validation character filtering for user-entered expressions.
* 3. Use double to replace the value of the original int, and use strict floating-point arithmetic to improve the precision of the operation.
* 4. Lifting the number of operations can only be a limit.
* 5. Optimized part of the code.
* Change LOG: 2.1
* 1. Add expression bracket matching function.
* Change LOG: 2.2
* 1. Add the expression processing function.
* Change log: 2.21
* 1. Modify some of the syntax to support generic usage in JDK1.5.
*/


Import Java.lang.reflect.Array;
Import java.util.*;
Import java.util.regex.*;
Import java.lang.*;
Import java.io.*;

Test Case: 1-3* (2+5*3) +5 -6/(1+2) =23
Test cases: 11.2+3.1* (423-(2+5.7*3.4) +5.6) -6.4/(15.5+24) =1273.4199746835445
Class Calculator
{

public static void Main (string[] args) throws IOException
{
String Str_input;
Double f_output;

while (true)
{
System.out.print ("Input expression:");
System.out.flush ();

Str_input = GetString ();
if (Str_input.equals (""))
{
Break
}

Calculator Calculator = new Calculator ();

The following rules are processed for the input string
Str_input = Calculator.checkexpression (str_input);
if (Str_input.equals (""))
{
SYSTEM.OUT.PRINTLN ("error of expression");
}

The following is an expression conversion to an input string
vector<string> V_compute = calculator.getexpression (str_input);

/*
for (int i=0;i<v_compute.size (); i++)
{
System.out.println ("" +v_compute.get (i));
}
*/

The following is a suffix-expression conversion
vector<string> V_tmp_prefix = Calculator.transformprefix (V_compute);

/*
for (int i=0;i<v_tmp_prefix.size (); i++)
{
System.out.println (V_tmp_prefix.get (i));
}
*/

The following is a suffix expression operation
F_output = Calculator.evaluateprefix (V_tmp_prefix);

SYSTEM.OUT.PRINTLN ("result =" + F_output);

}
}

/**
* static method, used to read an expression from the console
*/
public static String getString () throws IOException
{
InputStreamReader ISR = new InputStreamReader (system.in);
BufferedReader br = new BufferedReader (ISR);
String s = br.readline ();
return s;
}


/**
* Input string conversion. Converts a string read from the console into an expression that exists in a queue.
* Example: 123+321 Save as "123" "+" "321"
*/
Public vector<string> getexpression (String str)
{
vector<string> v_temp = new vector<string> ();
char[] temp = new char[str.length ()];
Str.getchars (0,str.length (), temp,0);
String fi = "";
int x=0,i=0;
String regex_fig = "[\\.\\d]"; Match numbers and decimal points
String regex_operator = "[\\+\\-\\*/\\ (\)]"; Matching operators (+,-, *,/) and parentheses ("(,"))
Pattern P_fig = Pattern.compile (regex_fig);
Pattern P_operator = Pattern.compile (regex_operator);
Matcher m = null;
Boolean B;
while (I<str.length ())
{
Character C = new Character (Temp[i]);
String s = c.tostring ();
System.out.println ("char c =" +s);
m = P_operator.matcher (s);
b = m.matches ();

if (b)
{
System.out.println ("matches operator");
V_temp.add (FI);
Fi= "";
V_temp.add (s);
}
m = P_fig.matcher (s);
b = m.matches ();
if (b)
{
System.out.println ("matches fig");
Fi=fi+s;
}
i++;
}
V_temp.add (FI);

return v_temp;
}

The  * in the

 /**
Conversion is a forward-order representation
 */
 public vector<string> transformprefix (vector< string> v_expression)
 {
  Vector<String> v_prefix = new vector<string> ();
  Stack<String> s_tmp = new stack<string> ();
  string regex_float = "\\d+ (\\.\\d+)";      //matching positive floating-point number
  pattern p_float = Pattern.compile (regex_float);
  matcher m = null; 
  boolean b;
  string Str_elem = "";

for (int i=0;i<v_expression.size (); i++)
{
Str_elem = V_expression.get (i). toString ();
m = P_float.matcher (Str_elem);
b = m.matches ();

if (b)
{
V_prefix.add (Str_elem);
}

if (str_elem.equals ("+") | | Str_elem.equals ("-"))
{
if (S_tmp.isempty ())
{
S_tmp.push (Str_elem);
}
Else
{
while (!s_tmp.isempty ())
{
String str_tmp = S_tmp.peek ();

if (Str_tmp.equals ("())
{
Break
}
Else
{
V_prefix.add (S_tmp.pop ());
}
}
S_tmp.push (Str_elem);
}
}

if (Str_elem.equals ("*") | | Str_elem.equals ("/"))
{
if (S_tmp.isempty ())
{
S_tmp.push (Str_elem);
}
Else
{
while (!s_tmp.isempty ())
{
String str_tmp = S_tmp.peek ();

if (Str_tmp.equals ("()) | | Str_tmp.equals ("+") | | Str_tmp.equals ("-"))
{
Break
}
Else
{
V_prefix.add (S_tmp.pop ());
}
}
S_tmp.push (Str_elem);
}
}

if (Str_elem.equals ("())
{
S_tmp.push (Str_elem);
}

if (Str_elem.equals (")"))
{
while (!s_tmp.isempty ())
{
String str_tmp = S_tmp.peek ();
if (Str_tmp.equals ("())
{
S_tmp.pop ();
Break
}
Else
{
V_prefix.add (S_tmp.pop ());
}
}
}
}

while (!s_tmp.isempty ())
{
V_prefix.add (S_tmp.pop ());
}
return v_prefix;
}

/**
* Prefix expression evaluation
*/
Public STRICTFP Double Evaluateprefix (vector<string> v_prefix)
{
String str_tmp = "";
Double Num1,num2,interans = 0;
stack<double> S_compute = new stack<double> ();

int i = 0;
while (I<v_prefix.size ())
{
Str_tmp = V_prefix.get (i). toString ();
if (!str_tmp.equals ("+") &&!str_tmp.equals ("-") &&!str_tmp.equals ("*") &&!str_tmp.equals (" /"))
{
Interans = S_compute.push (double.parsedouble (str_tmp));
}
Else
{
Num2= (Double) (S_compute.pop ());
Num1= (Double) (S_compute.pop ());

if (str_tmp.equals ("+"))
{
Interans = num1+num2;
}
if (Str_tmp.equals ("-"))
{
Interans = num1-num2;
}
if (Str_tmp.equals ("*"))
{
Interans = num1*num2;
}
if (Str_tmp.equals ("/"))
{
Interans = num1/num2;
}
S_compute.push (Interans);
}
i++;
}
return Interans;
}

/**
* Bracket Matching detection
*/
public boolean checkbracket (String str)
{
stack<character> S_check = new stack<character> ();
Boolean b_flag = true;

for (int i=0;i<str.length (); i++)
{
char ch = str.charat (i);
Switch (CH)
{
Case ' (':
S_check.push (CH);
Break
Case ') ':
if (!s_check.isempty ())
{
Char Chx = S_check.pop ();
if (ch== ') ' && chx!= ' (')
{
B_flag = false;
}
} else {
B_flag = false;
}
Break
Default
Break
}
}
if (!s_check.isempty ())
{
B_flag = false;
}
return b_flag;
}

/**
* Expression correctness rule processing and verification
*/
public string checkexpression (String str)
{
stack<character> S_check = new stack<character> ();
stack<character> s_tmp = new stack<character> ();
String Str_result = "";

String Str_regex = "^[\\.\\d\\+\\-\\*/\\ (\)]+$"; Match the valid operator character "digital,., +,-, *,/, (,),"
Pattern p_filtrate = Pattern.compile (Str_regex);
Matcher m = p_filtrate.matcher (str);
Boolean b_filtrate = M.matches ();
if (!b_filtrate)
{
Str_result = "";
return str_result;
}

  string str_err_float = ". * (\\.\\d*) {2,}.*";                      //Match illegal floating-point number.
  pattern p_err_float = Pattern.compile (str_err_float);
  matcher m_err_float = P_err_float.matcher (str);  
  boolean b_err_float = m_err_ Float.matches ();
  if (b_err_float)
  {
   str_result = "";
   return Str_result;
  }

for (int i=0;i<str.length (); i++)
{
char ch = str.charat (i);
if (Checkfig (CH))
{
if (!s_tmp.isempty () &&s_tmp.peek () = = ')
{
Str_result = "";
return str_result;
}
S_tmp.push (CH);
Str_result = Str_result+ch;
}

Switch (CH)
{
Case ' (':
if (!s_tmp.isempty () &&s_tmp.peek () = = '. ')
{
Str_result = "";
return str_result;
}
S_check.push (CH);
if (S_tmp.isempty () | | (!this.checkfig (S_tmp.peek ()) &&s_tmp.peek ()!= '))
{
Str_result = Str_result+ch;
} else {
Str_result = str_result+ "*" +CH;
}
S_tmp.push (CH);
Break
Case ') ':
if (!s_check.isempty ())
{
Char Chx = S_check.pop ();
if (ch== ') ' && chx!= ' (')
{
Str_result = "";
return str_result;
}
} else {
Str_result = "";
return str_result;
}
if (s_tmp.peek () = = '. ' | | (!this.checkfig (S_tmp.peek ()) &&s_tmp.peek ()!= '))
{
Str_result = "";
return str_result;
}
S_tmp.push (CH);
Str_result = Str_result+ch;
Break
Case ' + ':
Case '-':
if (!s_tmp.isempty () && (s_tmp.peek () = = ' + ' | | S_tmp.peek () = = '-' | | S_tmp.peek () = = ' * ' | | S_tmp.peek () = = '/' | | S_tmp.peek () = = = '. ')
{
Str_result = "";
return str_result;
}
if (S_tmp.isempty () | | S_tmp.peek () = = ' (')
{
Str_result = str_result+ "0" +CH;
} else {
Str_result = Str_result+ch;
}
S_tmp.push (CH);
Break
Case ' * ':
Case '/':
if (S_tmp.isempty () | | S_tmp.peek () = = '. ' | | (!this.checkfig (S_tmp.peek ()) &&s_tmp.peek ()!= '))
{
Str_result = "";
return str_result;
}
S_tmp.push (CH);
Str_result = Str_result+ch;
Break
Case '. ':
if (S_tmp.isempty () | |! This.checkfig (S_tmp.peek ()))
{
Str_result = str_result+ "0" +CH;
} else {
Str_result = Str_result+ch;
}
S_tmp.push (CH);
Break

Default
Break
}
}
if (!s_check.isempty ())
{
Str_result = "";
return str_result;
}


return str_result;

}

private static Boolean checkfig (Object ch)
{
String s = ch.tostring ();
String str_regexfig = "\\d"; Matching numbers
Pattern P_fig = Pattern.compile (str_regexfig);
Matcher M_fig = P_fig.matcher (s);
Boolean b_fig = M_fig.matches ();
return b_fig;
}

};



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.