SlideShare a Scribd company logo
1 of 16
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;
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++;
} 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++;
}
}
}
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 ;
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
// 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);
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);
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);
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++;
} 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= "";
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
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);
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("&")) {
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) {
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{
Stringchoice;
Scannerscan = newScanner(System.in);
System.out.print("Press‘F’toreadexpressionsfromafile,or‘K’toenter
expressionsfromthe keyboard:");
choice = scan.nextLine().toUpperCase();
while (!choice.equals("F") ||!choice.equals("K")){
if (choice.equals("F")) {
fileReader(choice);
} else if (choice.equals("K")) {
userInput(choice);
} else if (choice.length() ==0) {
System.out.println("nExitingprogram.Goodbye!");
System.exit(0);
break;
} else {
System.out.print("Invalidchoice.Please enteravalidchoice. nn");
assignment_copy.main(args);
}
}
scan.close();
}
}

More Related Content

What's hot

Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptRyan Anklam
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticinoArnaud Bos
 
The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210Mahmoud Samir Fayed
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180Mahmoud Samir Fayed
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J ScriptRoman Agaev
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212Mahmoud Samir Fayed
 
merged_document_3
merged_document_3merged_document_3
merged_document_3tori hoff
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensionsOleksandr Zhevzhyk
 
Security Events correlation with ESPER
Security Events correlation with ESPERSecurity Events correlation with ESPER
Security Events correlation with ESPERNikolay Klendar
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84Mahmoud Samir Fayed
 

What's hot (17)

Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino2019-10-05 - Untangled - Voxxed days ticino
2019-10-05 - Untangled - Voxxed days ticino
 
New text document
New text documentNew text document
New text document
 
The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210The Ring programming language version 1.9 book - Part 92 of 210
The Ring programming language version 1.9 book - Part 92 of 210
 
The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180The Ring programming language version 1.5.1 book - Part 75 of 180
The Ring programming language version 1.5.1 book - Part 75 of 180
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
Logic Equations Resolver J Script
Logic Equations Resolver   J ScriptLogic Equations Resolver   J Script
Logic Equations Resolver J Script
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181The Ring programming language version 1.5.2 book - Part 76 of 181
The Ring programming language version 1.5.2 book - Part 76 of 181
 
The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212The Ring programming language version 1.10 book - Part 94 of 212
The Ring programming language version 1.10 book - Part 94 of 212
 
Easy Button
Easy ButtonEasy Button
Easy Button
 
merged_document_3
merged_document_3merged_document_3
merged_document_3
 
Understanding reactive programming with microsoft reactive extensions
Understanding reactive programming  with microsoft reactive extensionsUnderstanding reactive programming  with microsoft reactive extensions
Understanding reactive programming with microsoft reactive extensions
 
Security Events correlation with ESPER
Security Events correlation with ESPERSecurity Events correlation with ESPER
Security Events correlation with ESPER
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84The Ring programming language version 1.2 book - Part 16 of 84
The Ring programming language version 1.2 book - Part 16 of 84
 

Viewers also liked

Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...
Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...
Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...Gabriela Angelita Dominguez
 
Know your characters: understand your clients to connect better and sell more...
Know your characters: understand your clients to connect better and sell more...Know your characters: understand your clients to connect better and sell more...
Know your characters: understand your clients to connect better and sell more...David Marciniak
 
Karstens Conference Kit 2016
Karstens Conference Kit 2016Karstens Conference Kit 2016
Karstens Conference Kit 2016David Perry
 
4. a torres-las reformas educativas en méxico
4.  a torres-las reformas educativas en méxico4.  a torres-las reformas educativas en méxico
4. a torres-las reformas educativas en méxicoArmando Torres Ruiz
 
2016 membership letter-final
2016 membership letter-final2016 membership letter-final
2016 membership letter-finalJerry Raehal
 
ЗРАЗКОВА ТВОРЧА МАЙСТЕРНЯ “СВІТ СУВЕНІРІВ”
ЗРАЗКОВА ТВОРЧА  МАЙСТЕРНЯ  “СВІТ СУВЕНІРІВ”ЗРАЗКОВА ТВОРЧА  МАЙСТЕРНЯ  “СВІТ СУВЕНІРІВ”
ЗРАЗКОВА ТВОРЧА МАЙСТЕРНЯ “СВІТ СУВЕНІРІВ”cdt1924
 
CI 350 Power Point
CI 350 Power Point CI 350 Power Point
CI 350 Power Point Slamie94
 
Via positivas del sena
Via positivas del senaVia positivas del sena
Via positivas del senaMary Polo
 
גליון ציונים
גליון ציוניםגליון ציונים
גליון ציוניםSarah Gabriel
 
3 Spatial_Macroeconomics_eng
3 Spatial_Macroeconomics_eng3 Spatial_Macroeconomics_eng
3 Spatial_Macroeconomics_engmafled
 
Presentacion ecosistemas
Presentacion ecosistemasPresentacion ecosistemas
Presentacion ecosistemassussydeleon
 

Viewers also liked (17)

Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...
Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...
Diferencias y similitudes en los enfoques para la enseñanza de la lengua espa...
 
Presentacion de herramientas web 2.0
Presentacion de herramientas web 2.0Presentacion de herramientas web 2.0
Presentacion de herramientas web 2.0
 
Know your characters: understand your clients to connect better and sell more...
Know your characters: understand your clients to connect better and sell more...Know your characters: understand your clients to connect better and sell more...
Know your characters: understand your clients to connect better and sell more...
 
Karstens Conference Kit 2016
Karstens Conference Kit 2016Karstens Conference Kit 2016
Karstens Conference Kit 2016
 
4. a torres-las reformas educativas en méxico
4.  a torres-las reformas educativas en méxico4.  a torres-las reformas educativas en méxico
4. a torres-las reformas educativas en méxico
 
2016 membership letter-final
2016 membership letter-final2016 membership letter-final
2016 membership letter-final
 
ЗРАЗКОВА ТВОРЧА МАЙСТЕРНЯ “СВІТ СУВЕНІРІВ”
ЗРАЗКОВА ТВОРЧА  МАЙСТЕРНЯ  “СВІТ СУВЕНІРІВ”ЗРАЗКОВА ТВОРЧА  МАЙСТЕРНЯ  “СВІТ СУВЕНІРІВ”
ЗРАЗКОВА ТВОРЧА МАЙСТЕРНЯ “СВІТ СУВЕНІРІВ”
 
CMF Brochure
CMF BrochureCMF Brochure
CMF Brochure
 
From Eng. to Ent.
From Eng. to Ent.From Eng. to Ent.
From Eng. to Ent.
 
Curriculum Vitae
Curriculum VitaeCurriculum Vitae
Curriculum Vitae
 
CI 350 Power Point
CI 350 Power Point CI 350 Power Point
CI 350 Power Point
 
Via positivas del sena
Via positivas del senaVia positivas del sena
Via positivas del sena
 
גליון ציונים
גליון ציוניםגליון ציונים
גליון ציונים
 
3 Spatial_Macroeconomics_eng
3 Spatial_Macroeconomics_eng3 Spatial_Macroeconomics_eng
3 Spatial_Macroeconomics_eng
 
Presentacion ecosistemas
Presentacion ecosistemasPresentacion ecosistemas
Presentacion ecosistemas
 
Sistema nervioso tarea 2
Sistema nervioso tarea 2Sistema nervioso tarea 2
Sistema nervioso tarea 2
 
Olg int dwnlds_rm
Olg int dwnlds_rmOlg int dwnlds_rm
Olg int dwnlds_rm
 

Similar to java assignment

JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfcalderoncasto9163
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingPathomchon Sriwilairit
 
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdf
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdfThe solution is as belowEmployeeDemo.javaimport java.util.Scann.pdf
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdfaparnatiwari291
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfarihantmum
 
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIAtsushi Tadokoro
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
I have already done the first 2 parts(factorial and fibonacci) also .pdf
I have already done the first 2 parts(factorial and fibonacci) also .pdfI have already done the first 2 parts(factorial and fibonacci) also .pdf
I have already done the first 2 parts(factorial and fibonacci) also .pdfudit652068
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monadJarek Ratajski
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3Dillon Lee
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and IterationsSameer Wadkar
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxpriestmanmable
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayNatasha Murashev
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitVaclav Pech
 

Similar to java assignment (20)

JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdfJAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
JAVA...With N.E.T_B.E.A.N.S___________________________________.pdf
 
JPC#8 Introduction to Java Programming
JPC#8 Introduction to Java ProgrammingJPC#8 Introduction to Java Programming
JPC#8 Introduction to Java Programming
 
Cpds lab
Cpds labCpds lab
Cpds lab
 
Operators
OperatorsOperators
Operators
 
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdf
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdfThe solution is as belowEmployeeDemo.javaimport java.util.Scann.pdf
The solution is as belowEmployeeDemo.javaimport java.util.Scann.pdf
 
help me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdfhelp me Java projectI put problem and my own code in the linkmy .pdf
help me Java projectI put problem and my own code in the linkmy .pdf
 
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートIIopenFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
openFrameworks – パーティクルを動かす、静的配列と動的配列 - 多摩美メディアアートII
 
5 Rmi Print
5  Rmi Print5  Rmi Print
5 Rmi Print
 
Sam wd programs
Sam wd programsSam wd programs
Sam wd programs
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
I have already done the first 2 parts(factorial and fibonacci) also .pdf
I have already done the first 2 parts(factorial and fibonacci) also .pdfI have already done the first 2 parts(factorial and fibonacci) also .pdf
I have already done the first 2 parts(factorial and fibonacci) also .pdf
 
Transaction is a monad
Transaction is a  monadTransaction is a  monad
Transaction is a monad
 
Integration Project Inspection 3
Integration Project Inspection 3Integration Project Inspection 3
Integration Project Inspection 3
 
Flink Batch Processing and Iterations
Flink Batch Processing and IterationsFlink Batch Processing and Iterations
Flink Batch Processing and Iterations
 
BCSL 058 solved assignment
BCSL 058 solved assignmentBCSL 058 solved assignment
BCSL 058 solved assignment
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional Way
 
C Language Lecture 18
C Language Lecture 18C Language Lecture 18
C Language Lecture 18
 
Java Class Design
Java Class DesignJava Class Design
Java Class Design
 
Pick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruitPick up the low-hanging concurrency fruit
Pick up the low-hanging concurrency fruit
 

java assignment

  • 1. 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{
  • 16. Stringchoice; Scannerscan = newScanner(System.in); System.out.print("Press‘F’toreadexpressionsfromafile,or‘K’toenter expressionsfromthe keyboard:"); choice = scan.nextLine().toUpperCase(); while (!choice.equals("F") ||!choice.equals("K")){ if (choice.equals("F")) { fileReader(choice); } else if (choice.equals("K")) { userInput(choice); } else if (choice.length() ==0) { System.out.println("nExitingprogram.Goodbye!"); System.exit(0); break; } else { System.out.print("Invalidchoice.Please enteravalidchoice. nn"); assignment_copy.main(args); } } scan.close(); } }