🔒 Closed Coding good practice 1 of many

Status
Not open for further replies.
Heto yung code kung gusto nyong pag-aralan.
It's not perfect and maraming dapat pang gawin but it's running as it is. The idea to get from is:
Follow Java naming convention lalo na sa methods and variables.....and malinis at madaling basahin na MAIN method.
**********************

import java.util.Scanner;

public class MainApp {

static Scanner input = new Scanner(System.in);

public static void main(String[] args){
boolean running = true;
do{
displayWelcome();
int userInput = getInputFromUser();
performSelectedOperation(userInput);
running = askToRunProgramAgain();
}while(running);
}


private static void displayWelcome(){
System.out.println("Welcome to my System.");
System.out.println("******************");
System.out.println("Please choose an operation");
System.out.println("[ 1 ] Addition");
System.out.println("[ 2 ] Multiplication");
System.out.println("[ 3 ] Exit");
}

private static int getInputFromUser() {
int userInput;
input.reset();
userInput = input.nextInt();
return userInput;
}

private static void performSelectedOperation(int numberSelected){
switch(numberSelected){
case 1: System.out.println("You choosed ADDITION");
break;
case 2: System.out.println("You choosed MULTIPLICATION");
break;
case 3: System.out.println("You choosed EXIT");
System.exit(0);
default: System.out.println("Entry not valid");
System.exit(0);
}
}

private static boolean askToRunProgramAgain() {
System.out.println("Run program again? [ Y ] = Yes, [ N ] = No");
input.reset();
String userInput = input.next().toLowerCase().trim();
if(userInput.equals("y")){
return true;
} else {
return false;
}
}

}
 
esse08
static means, puwede mo gamitin DIRECTLY yung method kahit hindi ka mag INSTANTIATE ng MainApp class first.

halimbawa yung method na "private static void displayWelcome()".
since static siya, puwede mo gamitin kaagad:
displayWelcome();

pero kung HINDI static yan, kailangan mo munang:
//mag-instantiate
1) MainApp app = new MainApp();
//then puwede mo ng gamitin yung method
2) app.displayWelcome();

ganon din sa variable, pag naka static, you can directly use it.
pag hindi static, you need to use getter/setter method kung merong available.
 
Also,set these as principles of software engineer:
1. Use top-down
2. Make your code readable
3. Give methods and variables a descriptive name
4. Only public provide access to those methods that are needed to be publicly accessed
5. Kapag may natutunan pa ako, add ko. Hehe
 
Status
Not open for further replies.

About this Thread

  • 7
    Replies
  • 1K
    Views
  • 4
    Participants
Last reply from:
haxxorisme

Trending Topics

Online now

Members online
1,344
Guests online
5,059
Total visitors
6,403

Forum statistics

Threads
2,301,148
Posts
29,141,021
Members
1,199,817
Latest member
D u x
Back
Top