More Related Content Similar to java assignment Similar to java assignment (20) java assignment1. importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.*;
publicclassassignment_copy{
// global variablesthatwillbe usedforevaluations
staticfloataggregate = 0, highest= -Float.MAX_VALUE,lowest=Float.MAX_VALUE, average,
result;
staticint valid,invalid;//will holdall the validandinvalidexpressions
staticvoidstatistics(floatresult){ //sumfrom the operationiscarriedin
aggregate += result;//addsthe resultto the aggregate (togive the total of all the
sums)
highest= (result>highest) ?result:highest;//resultisstoredinhighestfirst,then
the nextresultiscomparedto
// the currenthighestsum, andif the currentresultishigherthenitgets
// storedinthe highestvariable
lowest=(result< lowest) ?result:lowest;
average = aggregate / valid;//dividedthe total sumsinthe aggregate variable
}
staticvoidextraOperators(String[] text,Stringinput) {
Stringoperation;
Stack<Float>stack = new Stack<Float>();//a stack iscreatedto deal with
expressions
floatnum1;
floatnum2;
2. for (inti = 0; i < text.length;i++) { //goesthrough eachelementinthe textarray
try {
operation= text[i];//storeseach elementinthe array to operation
if (!"+".equals(operation) &&!"*".equals(operation)&&!"-
".equals(operation)&&!"/".equals(operation)
&& !"<<".equals(operation) &&
!">>".equals(operation) &&!"%".equals(operation)
&& !"&".equals(operation)&&
!"|".equals(operation)) {
stack.push(Float.parseFloat(operation));
} else {
num2 = (float)stack.pop();
num1 = (float)stack.pop();
if (operation.equals("+")) {
System.out.println("nYourequationis:"+ num1 + "
+ " + num2 + " = " + (num1+ num2));
result= num1 + num2;
valid++;
} else if (operation.equals("-")) {
System.out.println("nYourequationis:"+ num1 + "
- " + num2 + " = " + (num1- num2));
result= num1 - num2;
valid++;
} else if (operation.equals("/")) {
System.out.println("nYourequationis:"+ num1 + "
/ " + num2 + " = " + (num1/ num2));
result= num1 / num2;
valid++;
3. } else if (operation.equals("*")){
System.out.println("nYourequationis:"+ num1 + "
* " + num2 + " = " + (num1* num2));
result= num1 * num2;
valid++;
} else {
System.out.print("nInvalidoperator.Please inputa
validoperator.n");
invalid++;//invalid isincreasedbyone forevery
invalidexpression
}
stack.push(result);
statistics(result);//the resultsthengetsenttobe calculated
for evaluations
}
} catch (NumberFormatExceptione) {
System.out.print("Invalid operandsentered:"+ input+". Please
entervalidoperands.nn");
invalid++;
} catch (EmptyStackExceptions) {
System.out.print("Invalidoperandsentered:"+ input+". Please
entervalidoperands.nn");
invalid++;
}
}
}
4. staticvoidevaluations(floathighest,floatlowest,floataggregate,floataverage,intinvalid,
intvalid) {
if (valid== 0) { // if there'snovalidexpressions,then"n/a"isdisplayed
System.out.println("nEvaluationscompleten----------------------------------------
---");
System.out.println("Highestvalue:n/a");
System.out.println("Lowestvalue:n/a");
System.out.println("Aggregateresult:"+ aggregate);
System.out.println("Average result:n/a");
System.out.println("Invalidexpressions:"+ invalid);
System.out.println("Validexpresssions:"+ valid+ "n");
} else {
System.out.println("nEvaluationscompleten----------------------------------------
---");
System.out.println("Highestvalue:"+ highest);
System.out.println("Lowestvalue:"+ lowest);
System.out.println("Aggregateresult:"+ aggregate);
System.out.println("Average result:"+ average);
System.out.println("Invalidexpressions:"+ invalid);
System.out.println("Validexpresssions:"+ valid+ "n");
}
}
staticvoidfileReader(Stringchoice) {
Stringfilename ="";
booleanfile =true ;
5. Stringfileline ="";
Stringoperandone1= "";
Stringoperandtwo2= "";
Stringoperator= "";
while (file ==true) {
try {
System.out.print("Please enteravalidfilename:");
Scannerscan = new Scanner(System.in);
filename =scan.nextLine();
if (filename.length() ==0) {
System.out.println("Exitingprogram...");
file =false;
System.exit(0);
break;
}
Scannerfilescan=new Scanner(new File(filename));
System.out.println(filename +" hasbeenselected. n--------------------
-----");
System.out.println("Processingdata...");
while ( filescan.hasNext()){ //loopsthroughthe file until itreadsthe
entire file
try {
fileline =filescan.nextLine();//readsthe firstline in
the file
System.out.println("nPostfixedexpressionis:"+
fileline);
String[] filevar=fileline.split("");//splitsthe tokens
inthe selected
6. // line inanarray calledfilevarandputsa space
betweenthem
if (filevar.length>3) { //if there'smore than 2
operands/1operatorinthe array, thenthe extraoperatormethod
// iscalled
extraOperators(filevar,fileline);
} else {
operandone1=filevar[0];//firsttokeninthe array
is
// the firstoperand
operandtwo2= filevar[1];
operator= filevar[2];
if (operator.equals("+")) {
Double operand1=
Double.parseDouble(operandone1);//operandsare convertedtodoubletypes
Double operand2=
Double.parseDouble(operandtwo2);
System.out.println("Yourequationis:"+
operand1+ " + " + operand2+ " = " + (operand1+ operand2));
result= (float) (operand1+operand2);//
the sum of the 2 operandsare convertedtofloat'sthenaddedto result
valid++;// adddsone to the validglobal
variable everytime avalidexpression iscalculated
} else if (operator.equals("-")) {
Double operand1=
Double.parseDouble(operandone1);
Double operand2=
Double.parseDouble(operandtwo2);
7. System.out.println("Yourequationis:"+
operand1+ " - " + operand2+ " = " + (operand1- operand2));
result= (float) (operand1- operand2);
valid++;
} else if (operator.equals("/")) {
Double operand1=
Double.parseDouble(operandone1);
Double operand2=
Double.parseDouble(operandtwo2);
System.out.println("Yourequationis:"+
operand1+ " / " + operand2+ " = " + (operand1/ operand2));
result= (float) (operand1/operand2);
valid++;
} else if (operator.equals("*")) {
Double operand1=
Double.parseDouble(operandone1);
Double operand2=
Double.parseDouble(operandtwo2);
System.out.println("Yourequationis:"+
operand1+ " * " + operand2+ " = " + (operand1* operand2));
result= (float) (operand1*operand2);
valid++;
} else if (operator.equals("<<")) { //restof the else
statementsare forthe extraoperators
intconversion1=
Integer.parseInt(operandone1);//the operandsare convertedtointegers
intconversion2=
Integer.parseInt(operandtwo2);
8. System.out.println("Yourequationis:"+
conversion1+ " << " + conversion2+" = " + (conversion1<<conversion2));
result= conversion1<< conversion2;
valid++;
} else if (operator.equals(">>")) {
intconversion1=
Integer.parseInt(operandone1);
intconversion2=
Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " >> " + conversion2+" = " + (conversion1>>conversion2));
result= conversion1>> conversion2;
valid++;
} else if (operator.equals("%")) {
intconversion1=
Integer.parseInt(operandone1);
intconversion2=
Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " % " + conversion2+ " = " + (conversion1% conversion2));
result= conversion1% conversion2;
valid++;
} else if (operator.equals("&")) {
intconversion1=
Integer.parseInt(operandone1);
intconversion2=
Integer.parseInt(operandtwo2);
9. System.out.println("Yourequationis:"+
conversion1+ " & " + conversion2+ " = " + (conversion1&conversion2));
result= conversion1&conversion2;
valid++;
} else if (operator.equals("|")) {
intconversion1=
Integer.parseInt(operandone1);
intconversion2=
Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " | " + conversion2+" = " + (conversion1|conversion2));
result= conversion1|conversion2;
valid++;
} else {
System.out.print("Invalidoperator.Please
inputa validoperator.n");
invalid++;//invalidisincreasedbyone for
everyinvalidexpression
}
assignment_copy.statistics(result); //the results
thengetsentto be calculatedforevaluations
// everyexpressionhasbeenread
}
} catch (InputMismatchExceptione) { //if characters are
enteredinsteadof numbersormore than 3 operands+ operatorare i the file thenthese will be
printed
System.out.print("Invalidoperandsentered:"+
fileline +"n");
invalid++;
10. } catch (NumberFormatExceptione) {
System.out.print("Invalidoperandsentered:"+
fileline +"n");
invalid++;
} catch (ArrayIndexOutOfBoundsExceptione) {
System.out.println("Incorrectoperands/operator
entered.Please enterinformat(o1-o2-op).");
invalid++;
}
}
filescan.close();
System.out.println("---------------------------ntEndof filen---------------
------------");
evaluations(highest,lowest,aggregate,average,invalid,valid);//
evaluationsare shownassoonas the file isended
main(null);//goesbackto start of program afterevaluationshave
beenshown
} catch (FileNotFoundExceptione) {
System.out.println("Invalidfile.Please enteravalidfilename: n");
}
}
}
staticvoiduserInput(Stringchoice) throwsFileNotFoundException{
Stringinput= null;
booleanreset=true;
Stringoperandone1= "";
Stringoperandtwo2= "";
11. Stringoperator= "";
Scannerscan = newScanner(System.in);
while (reset== true) {
try {
System.out.print("nPlease enterapost-fixedexpression:");
input= scan.nextLine();
// If userinput'semptystringthenprogramexits
if (input.length() ==0) {
System.out.println("nExitingprogram...");
reset= false;
System.exit(0);
break;
}
String[] text= input.split("");//splitsthe tokensfromthe userinput
and putsa space inbetweenthem
// andstoresthemin an array calledtext
if (text.length>3) { //if there are more than 3 elementsinthe array
thenthiswill be treatedashavingmore than
// 2 operands/1 operator
extraOperators(text,input);
} else {
operandone1=text[0];//firstelementisthe 1stoperand
operandtwo2= text[1];//secondelementis2ndoperand
operator= text[2];//thirdelementstoredisoperator
// getanswers
12. if (operator.equals("+")) {
Double operand1=
Double.parseDouble(operandone1);//operands1+ 2 are convertedtodouble forthe calculations
Double operand2=
Double.parseDouble(operandtwo2);
System.out.println("Yourequationis:"+ operand1+
" + " + operand2+ " = " + (operand1+ operand2) + "n");
result= (float) (operand1+operand2);
valid++;
} else if (operator.equals("-")) {
Double operand1=
Double.parseDouble(operandone1);//operands1+ 2 are convertedtodouble forthe calculations
Double operand2=
Double.parseDouble(operandtwo2);
System.out.println("Yourequationis:"+ operand1+
" - " + operand2+ " = " + (operand1- operand2) + "n");
result= (float) (operand1- operand2);
valid++;
} else if (operator.equals("/")) {
Double operand1=
Double.parseDouble(operandone1);//operands1+ 2 are convertedtodouble forthe calculations
Double operand2=
Double.parseDouble(operandtwo2);
System.out.println("Yourequationis:"+ operand1+
" / " + operand2+ " = " + (operand1/ operand2) + "n");
result= (float) (operand1/operand2);
valid++;
} else if (operator.equals("*")) {
Double operand1=
Double.parseDouble(operandone1);//operands1+ 2 are convertedtodouble forthe calculations
Double operand2=
Double.parseDouble(operandtwo2);
13. System.out.println("Yourequationis:"+ operand1+
" * " + operand2+ " = " + (operand1* operand2) + "n");
result= (float) (operand1*operand2);
valid++;
} else if (operator.equals("<<")) { //restof the else
statementsare forthe extraoperators
intconversion1= Integer.parseInt(operandone1);//
the operandsare convertedtointegers
intconversion2= Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " << " + conversion2+" = " + (conversion1<<conversion2));
result= conversion1<< conversion2;
valid++;
} else if (operator.equals(">>")) {
intconversion1= Integer.parseInt(operandone1);
intconversion2= Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " >> " + conversion2+" = " + (conversion1>>conversion2));
result= conversion1>> conversion2;
valid++;
break;
} else if (operator.equals("%")) {
intconversion1= Integer.parseInt(operandone1);
intconversion2= Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " % " + conversion2+ " = " + (conversion1% conversion2));
result= conversion1% conversion2;
valid++;
} else if (operator.equals("&")) {
14. intconversion1= Integer.parseInt(operandone1);
intconversion2= Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " & " + conversion2+ " = " + (conversion1&conversion2));
result= conversion1&conversion2;
valid++;
} else if (operator.equals("|")) {
intconversion1= Integer.parseInt(operandone1);
intconversion2= Integer.parseInt(operandtwo2);
System.out.println("Yourequationis:"+
conversion1+ " | " + conversion2+" = " + (conversion1|conversion2));
result= conversion1|conversion2;
valid++;
} else {
System.out.print("Invalidoperator:"+ operator+ ".
Please inputavalidoperator: nn");
invalid++;
}
}
} catch (InputMismatchExceptione) {
System.out.print("Invalidoperandsentered:"+ input+".
Please entervalidoperands.nn");
invalid++;
} catch (NumberFormatExceptione) {
System.out.print("Invalidoperandsentered:"+ input+".
Please entervalidoperands.nn");
invalid++;
} catch (ArrayIndexOutOfBoundsExceptione) {
15. System.out.println("Incorrectoperands/operatorentered.
Please enterinformat(o1-o2-op).n");
invalid++;
}
System.out.print("Wouldyouliketoinputmore numbers?:");
input= scan.nextLine().toUpperCase();
while (!input.equals("YES") ||!input.equals("NO")) {
if (input.equals("YES")) {
statistics(result);//the resultgetssentforcalculations
userInput(input);//goesbackto userinputmethod
} else if (input.equals("NO")) {
statistics(result);//the resultgetssentforcalculations
evaluations(highest,lowest,aggregate,average,invalid,
valid);//evaluationsare displayed
main(null);//goesbackto start of program
} else if (input.length() ==0) {
System.out.println("nExitingprogram.Goodbye!");
System.exit(0);
break;
} else {
System.out.print("Invalidchoice.Please entereitherYesorNo.
nn");
}
}
scan.close();
}
}
publicstaticvoidmain(String[] args) throwsFileNotFoundException{