SlideShare a Scribd company logo
1 of 6
Improve your App
As you probably have noticed, the code is absolutely
the same in each onClickListener except of the
sign operation between two variables.
The additional challenge in programming is to
decrease complexity and length of the code, and to
make as readable and concise as possible.
Mostly its done by swapping repeatable code with
functions, reusable piece of code.
The following function <calculate>, will:
1. Takes input <sign> (with type String).
2.Takes both calculator's input variables.
3. Through <if statements> defines the sign variable and
calculates result appropriately
4. Prints off result in <answer> TextField
private void calculate(String sign) {
firstVar = Integer.parseInt(firstInput.getText().toString());
secondVar = Integer.parseInt(secondInput.getText().toString());
if (sign == "+") result = firstVar + secondVar;
else if (sign == "-") result = firstVar - secondVar;
else if (sign == "/") result = firstVar / secondVar;
else if (sign == "*") result = firstVar * secondVar;
answer.setText(String.valueOf(result));
}
Now we can remove
previous code inside
onClick method with
function
calculate(<math sign
relatively to the button>)
plus.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
calculate("+");
}
});
minus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
calculate("-");
}
});
mult.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
calculate("*");
}
});
div.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
calculate("/");
}
});
Program is shorter but result is the
same.
Thats what we aim for other apps you
are going to make as well.
Now try to fix bug when you make
calculation without assigning
variables yourself.
(hint: use if statements to illuminate null value of the variables)
Program is shorter but result is the
same.
Thats what we aim for other apps you
are going to make as well.
Now try to fix bug when you make
calculation without assigning
variables yourself.
(hint: use if statements to illuminate null value of the variables)

More Related Content

What's hot

C chap02
C chap02C chap02
C chap02Kamran
 
Effective Java - Always override toString() method
Effective Java - Always override toString() methodEffective Java - Always override toString() method
Effective Java - Always override toString() methodFerdous Mahmud Shaon
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniquesfika sweety
 
05 control structures 2
05 control structures 205 control structures 2
05 control structures 2Jomel Penalba
 
C sharp_basic_ideas
C sharp_basic_ideasC sharp_basic_ideas
C sharp_basic_ideasRalph Weber
 
Data annotation validation (ASP.net)
Data annotation validation (ASP.net)Data annotation validation (ASP.net)
Data annotation validation (ASP.net)Jyotasana Bharti
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#Raghu nath
 
Visual basic asp.net programming introduction
Visual basic asp.net programming introductionVisual basic asp.net programming introduction
Visual basic asp.net programming introductionHock Leng PUAH
 
Bca2030 object oriented programming – c++
Bca2030  object oriented programming – c++Bca2030  object oriented programming – c++
Bca2030 object oriented programming – c++smumbahelp
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchartfika sweety
 
C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2Ammara Javed
 
Ge6161 lab manual
Ge6161 lab manualGe6161 lab manual
Ge6161 lab manualMani Kandan
 
Basic c# cheat sheet
Basic c# cheat sheetBasic c# cheat sheet
Basic c# cheat sheetAhmed Elshal
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesTech
 

What's hot (20)

C chap02
C chap02C chap02
C chap02
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
Effective Java - Always override toString() method
Effective Java - Always override toString() methodEffective Java - Always override toString() method
Effective Java - Always override toString() method
 
Program design techniques
Program design techniquesProgram design techniques
Program design techniques
 
Pseudocode
PseudocodePseudocode
Pseudocode
 
05 control structures 2
05 control structures 205 control structures 2
05 control structures 2
 
C sharp_basic_ideas
C sharp_basic_ideasC sharp_basic_ideas
C sharp_basic_ideas
 
Data annotation validation (ASP.net)
Data annotation validation (ASP.net)Data annotation validation (ASP.net)
Data annotation validation (ASP.net)
 
2.overview of c#
2.overview of c#2.overview of c#
2.overview of c#
 
Visual basic asp.net programming introduction
Visual basic asp.net programming introductionVisual basic asp.net programming introduction
Visual basic asp.net programming introduction
 
Bca2030 object oriented programming – c++
Bca2030  object oriented programming – c++Bca2030  object oriented programming – c++
Bca2030 object oriented programming – c++
 
Unit 7: Built-In Functions
Unit 7: Built-In FunctionsUnit 7: Built-In Functions
Unit 7: Built-In Functions
 
LISP: Errors In Lisp
LISP: Errors In LispLISP: Errors In Lisp
LISP: Errors In Lisp
 
Pseudocode algorithim flowchart
Pseudocode algorithim flowchartPseudocode algorithim flowchart
Pseudocode algorithim flowchart
 
C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2C++ Programming Club-Lecture 2
C++ Programming Club-Lecture 2
 
Ge6161 lab manual
Ge6161 lab manualGe6161 lab manual
Ge6161 lab manual
 
Basic c# cheat sheet
Basic c# cheat sheetBasic c# cheat sheet
Basic c# cheat sheet
 
Best Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing TechniquesBest Techniques To Design Programs - Program Designing Techniques
Best Techniques To Design Programs - Program Designing Techniques
 
Pseudocode By ZAK
Pseudocode By ZAKPseudocode By ZAK
Pseudocode By ZAK
 
New features in C# 6
New features in C# 6New features in C# 6
New features in C# 6
 

Viewers also liked

Android tutorials7 calculator_intro
Android tutorials7 calculator_introAndroid tutorials7 calculator_intro
Android tutorials7 calculator_introVlad Kolesnyk
 
Help your scrum team strike oil!
Help your scrum team strike oil!Help your scrum team strike oil!
Help your scrum team strike oil!Michael O'Reilly
 
Android tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirerAndroid tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirerVlad Kolesnyk
 
видеоэкскурсия в красный берег(полная)
видеоэкскурсия в красный берег(полная)видеоэкскурсия в красный берег(полная)
видеоэкскурсия в красный берег(полная)svetopusha
 
ER hypertensive crisis-respiratory distress
ER hypertensive  crisis-respiratory distressER hypertensive  crisis-respiratory distress
ER hypertensive crisis-respiratory distressGamal ElDin Soliman
 
Услуги стадиона «Динамо»
Услуги стадиона «Динамо»Услуги стадиона «Динамо»
Услуги стадиона «Динамо»Andrey Pantiukhov
 
Android tutorials2 android_tools_on_eclipse
Android tutorials2 android_tools_on_eclipseAndroid tutorials2 android_tools_on_eclipse
Android tutorials2 android_tools_on_eclipseVlad Kolesnyk
 
Ray Kirby: Lectures are STILL Appropriate
Ray Kirby: Lectures are STILL AppropriateRay Kirby: Lectures are STILL Appropriate
Ray Kirby: Lectures are STILL AppropriateChris Evans
 
Android tutorials1 install_ide
Android tutorials1 install_ideAndroid tutorials1 install_ide
Android tutorials1 install_ideVlad Kolesnyk
 
Wasicunwitkotko
WasicunwitkotkoWasicunwitkotko
Wasicunwitkotkoales fiala
 
Preventing the spread of infection
Preventing the spread of infectionPreventing the spread of infection
Preventing the spread of infectionGamal ElDin Soliman
 
уголовная ответственность
уголовная ответственностьуголовная ответственность
уголовная ответственностьsvetopusha
 
электронные физминутки
электронные физминуткиэлектронные физминутки
электронные физминуткиsvetopusha
 

Viewers also liked (20)

Android tutorials7 calculator_intro
Android tutorials7 calculator_introAndroid tutorials7 calculator_intro
Android tutorials7 calculator_intro
 
Help your scrum team strike oil!
Help your scrum team strike oil!Help your scrum team strike oil!
Help your scrum team strike oil!
 
Android tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirerAndroid tutorials7 calculator_packageexploirer
Android tutorials7 calculator_packageexploirer
 
видеоэкскурсия в красный берег(полная)
видеоэкскурсия в красный берег(полная)видеоэкскурсия в красный берег(полная)
видеоэкскурсия в красный берег(полная)
 
ER hypertensive crisis-respiratory distress
ER hypertensive  crisis-respiratory distressER hypertensive  crisis-respiratory distress
ER hypertensive crisis-respiratory distress
 
Услуги стадиона «Динамо»
Услуги стадиона «Динамо»Услуги стадиона «Динамо»
Услуги стадиона «Динамо»
 
Android tutorials2 android_tools_on_eclipse
Android tutorials2 android_tools_on_eclipseAndroid tutorials2 android_tools_on_eclipse
Android tutorials2 android_tools_on_eclipse
 
Patient safety program scd
Patient safety program scdPatient safety program scd
Patient safety program scd
 
Imbracaminte copii
Imbracaminte copiiImbracaminte copii
Imbracaminte copii
 
Ray Kirby: Lectures are STILL Appropriate
Ray Kirby: Lectures are STILL AppropriateRay Kirby: Lectures are STILL Appropriate
Ray Kirby: Lectures are STILL Appropriate
 
Android tutorials1 install_ide
Android tutorials1 install_ideAndroid tutorials1 install_ide
Android tutorials1 install_ide
 
Github tutorial1
Github tutorial1Github tutorial1
Github tutorial1
 
Wasicunwitkotko
WasicunwitkotkoWasicunwitkotko
Wasicunwitkotko
 
Preventing the spread of infection
Preventing the spread of infectionPreventing the spread of infection
Preventing the spread of infection
 
Construction Risk Management ABC's
Construction Risk Management ABC'sConstruction Risk Management ABC's
Construction Risk Management ABC's
 
Year 2015
Year 2015Year 2015
Year 2015
 
HAINUTE BOTEZ
HAINUTE BOTEZHAINUTE BOTEZ
HAINUTE BOTEZ
 
уголовная ответственность
уголовная ответственностьуголовная ответственность
уголовная ответственность
 
электронные физминутки
электронные физминуткиэлектронные физминутки
электронные физминутки
 
Final
FinalFinal
Final
 

Similar to Android tutorials7 calulator_improve

Similar to Android tutorials7 calulator_improve (20)

Maxbox starter
Maxbox starterMaxbox starter
Maxbox starter
 
keyword
keywordkeyword
keyword
 
keyword
keywordkeyword
keyword
 
L03vars
L03varsL03vars
L03vars
 
C++ lecture 01
C++   lecture 01C++   lecture 01
C++ lecture 01
 
C++ functions
C++ functionsC++ functions
C++ functions
 
C++ functions
C++ functionsC++ functions
C++ functions
 
Python Lecture 2
Python Lecture 2Python Lecture 2
Python Lecture 2
 
C++
C++C++
C++
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
 
Ch03
Ch03Ch03
Ch03
 
1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf1588147798Begining_ABUAD1.pdf
1588147798Begining_ABUAD1.pdf
 
Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...Consequences of using the Copy-Paste method in C++ programming and how to dea...
Consequences of using the Copy-Paste method in C++ programming and how to dea...
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Programming For As Comp
Programming For As CompProgramming For As Comp
Programming For As Comp
 
Visual basic 6.0
Visual basic 6.0Visual basic 6.0
Visual basic 6.0
 
C++ Overview
C++ OverviewC++ Overview
C++ Overview
 
Building blocks 2
Building blocks 2Building blocks 2
Building blocks 2
 
SAS Macros part 1
SAS Macros part 1SAS Macros part 1
SAS Macros part 1
 
Intro to programing with java-lecture 3
Intro to programing with java-lecture 3Intro to programing with java-lecture 3
Intro to programing with java-lecture 3
 

More from Vlad Kolesnyk

Mech eng presentation
Mech eng presentationMech eng presentation
Mech eng presentationVlad Kolesnyk
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_listVlad Kolesnyk
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_listVlad Kolesnyk
 
Android tutorials6 run_your_app
Android tutorials6 run_your_appAndroid tutorials6 run_your_app
Android tutorials6 run_your_appVlad Kolesnyk
 
Android tutorials7 calculator
Android tutorials7 calculatorAndroid tutorials7 calculator
Android tutorials7 calculatorVlad Kolesnyk
 
Android tutorials7 calculator_basiclayout
Android tutorials7 calculator_basiclayoutAndroid tutorials7 calculator_basiclayout
Android tutorials7 calculator_basiclayoutVlad Kolesnyk
 
Android tutorials7 calculator_javaprogramming
Android tutorials7 calculator_javaprogrammingAndroid tutorials7 calculator_javaprogramming
Android tutorials7 calculator_javaprogrammingVlad Kolesnyk
 

More from Vlad Kolesnyk (8)

Mobile andwebapps
Mobile andwebappsMobile andwebapps
Mobile andwebapps
 
Mech eng presentation
Mech eng presentationMech eng presentation
Mech eng presentation
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
 
Android tutorials8 todo_list
Android tutorials8 todo_listAndroid tutorials8 todo_list
Android tutorials8 todo_list
 
Android tutorials6 run_your_app
Android tutorials6 run_your_appAndroid tutorials6 run_your_app
Android tutorials6 run_your_app
 
Android tutorials7 calculator
Android tutorials7 calculatorAndroid tutorials7 calculator
Android tutorials7 calculator
 
Android tutorials7 calculator_basiclayout
Android tutorials7 calculator_basiclayoutAndroid tutorials7 calculator_basiclayout
Android tutorials7 calculator_basiclayout
 
Android tutorials7 calculator_javaprogramming
Android tutorials7 calculator_javaprogrammingAndroid tutorials7 calculator_javaprogramming
Android tutorials7 calculator_javaprogramming
 

Recently uploaded

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 

Recently uploaded (20)

Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Android tutorials7 calulator_improve

  • 2. As you probably have noticed, the code is absolutely the same in each onClickListener except of the sign operation between two variables. The additional challenge in programming is to decrease complexity and length of the code, and to make as readable and concise as possible. Mostly its done by swapping repeatable code with functions, reusable piece of code.
  • 3. The following function <calculate>, will: 1. Takes input <sign> (with type String). 2.Takes both calculator's input variables. 3. Through <if statements> defines the sign variable and calculates result appropriately 4. Prints off result in <answer> TextField private void calculate(String sign) { firstVar = Integer.parseInt(firstInput.getText().toString()); secondVar = Integer.parseInt(secondInput.getText().toString()); if (sign == "+") result = firstVar + secondVar; else if (sign == "-") result = firstVar - secondVar; else if (sign == "/") result = firstVar / secondVar; else if (sign == "*") result = firstVar * secondVar; answer.setText(String.valueOf(result)); }
  • 4. Now we can remove previous code inside onClick method with function calculate(<math sign relatively to the button>) plus.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View arg0) { // TODO Auto-generated method stub calculate("+"); } }); minus.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub calculate("-"); } }); mult.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub calculate("*"); } }); div.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub calculate("/"); } });
  • 5. Program is shorter but result is the same. Thats what we aim for other apps you are going to make as well. Now try to fix bug when you make calculation without assigning variables yourself. (hint: use if statements to illuminate null value of the variables)
  • 6. Program is shorter but result is the same. Thats what we aim for other apps you are going to make as well. Now try to fix bug when you make calculation without assigning variables yourself. (hint: use if statements to illuminate null value of the variables)