'mga 'tol,
Again, some kind of refactoring.
To be learned:
- paggawa ng methods/functions
- paggamit ng while loop
- paggamit ng Scanner (for user input)
- preview ng Exception for errors
/******UNREFACTORED ********/
/******REFACTORED using method/function for reusability********/
/******REFACTORED. Medyo dynamic siya. ********/
Again, some kind of refactoring.
To be learned:
- paggawa ng methods/functions
- paggamit ng while loop
- paggamit ng Scanner (for user input)
- preview ng Exception for errors
/******UNREFACTORED ********/
Code:
/**
*
* Refactoring Series
* Author: CodyScott for PHcorner
*
*/
public class Math1 {
public static void main(String[] args) {
//add 5 integers
int num1 = 10;
int num2 = 5;
int num3 = 100;
int num4 = 20;
int num5 = 5;
int total = num1+num2+num3+num4+num5;
System.out.println("The total is: " + total);
}
}
/******REFACTORED using method/function for reusability********/
Code:
/**
*
* Refactoring Series
* using method/function
* Author: CodyScott for PHcorner
*/
public class Math2 {
public static void main(String[] args) {
//add 5 integers
int num1 = 10;
int num2 = 5;
int num3 = 100;
int num4 = 20;
int num5 = 5;
int total = addFiveIntegers(num1,num2,num3,num4,num5);
int total2 = addFiveIntegers(10,20,30,5,5);
int total3 = addFiveIntegers(100,(6+6),(10/2),5,(5*5));
System.out.println("The total is: " + total);
System.out.println("The total2 is: " + total2);
System.out.println("The total3 is: " + total3);
}
//gawa ng method / function
//para reusable
public static int addFiveIntegers(int num1, int num2, int num3, int num4, int num5) {
int total = 0;
total = num1+num2+num3+num4+num5;
return total;
}
}
/******REFACTORED. Medyo dynamic siya. ********/
Code:
/**
*
* Refactoring Series
* user input and while loop
* para mas dynamic siya
* Author: CodyScott for PHcorner
*
*/
import java.util.Scanner;
public class Math3 {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
boolean loopAgain = true;
int total = 0;
System.out.println("Start adding. Type 0 to Exit.");
//start of loop or while loopAgain is true
while(loopAgain) {
try {
int inputNumber = read.nextInt();
total += inputNumber;
if(inputNumber == 0) {
loopAgain = false; //pag 0 na yung in-input, exit na ang app.
}
} catch(Exception e) {
System.out.println("Invalid entry. Try again!");
read.next();
}
}
//end of loop or while loopAgain is false
//display total at the end
System.out.println("-------\nTOTAL: " + total);
}
}