簡體   English   中英

如何使代碼更靈活

[英]How to make code more flexible

我為我的班級項目編寫了一個Java類,並且我的所有方法都是無效的,除了在主方法中調用方法外,我基本上什么也不做。

該代碼基本上可以幫助學生管理租金和貸款付款方面的每月收入。

有人可以指出我做錯了什么正確的方向嗎? 在編碼習慣方面有什么建議嗎?

類代碼:

import java.io.*;
import java.util.*;
public class Finance{
  private double rentExpenses, tuition, totalCost, totCost, rent;
  private double payInput;
  private boolean status, liveWithParent;
  private int pay;
  //totalCost=Final cost per month
  //totCost=cost of tuition and rent per month


//Living with parents?
  public void liveWithParents(){
    Scanner in=new Scanner(System.in);
    System.out.println("Are you living with your parents?");
    String parents= in.nextLine();
    if(parents.charAt(0)=='y' || parents.charAt(0)=='Y'){
      status=true;}
    else{
      status=false;}}

//If yes, do you pay them rent?, if yes how much? else -, else How much is your monthly rent anyway?
  public void amountRent(){
    double rent;
    char valid;
    String validIn;
    Scanner in=new Scanner(System.in);
    if(status){
      System.out.println("Do you need to pay them rent?");
      validIn=in.nextLine();
      valid= validIn.charAt(0);
      if(valid=='y' || valid=='Y'){
        System.out.println("How much is your rent?");
        rent=in.nextDouble();}}
    else{
     System.out.println("How much is your monthly rent?");
     rent=in.nextDouble();}}

//What is your college tuition, $/term
  public void collegeTuition(){
    System.out.println("What what is your college tuition in $ per term?");
    Scanner in=new Scanner(System.in);
    tuition= in.nextDouble();}

//Total cost of tuition and rent per month
  public void getMonthlyCost(){
    totCost= rentExpenses + tuition/3.75;
    System.out.println("Your rent expenses and college tuition are: $"+totCost+" per month");}

//Method of paying for expenses

  public void payMethod(){
    Scanner in=new Scanner(System.in);
    System.out.println("How will you pay for your expenses?"
                      + "\n 1 -Savings\n 2 -Loans\n 3 -Freelance Work");
    pay=in.nextInt();
    while(pay<=0 || pay>3){
      System.out.println("You need to enter a number coresponding to the three choiches.\n\t Try again:");
      System.out.println("How will you pay for your expenses?"
                      + "\n 1 -Savings\n 2 -Loans\n 3 -Freelance Work");
      pay=in.nextInt();}}

//Gets the amount of savings the user has and converts
//that value to a monthly value
public void inputPayMethod(){
  Scanner in=new Scanner(System.in);
  if(pay==1){
    System.out.println("What amount of savings do you have in total for the school year?");
    payInput=in.nextDouble();
    payInput=payInput/9;}
  else if(pay==2){
    System.out.println("What amount of loans did you acquire for this school year?");
    payInput=in.nextDouble();
    payInput=payInput/9;}
  else if(pay==3){
    System.out.println("How much revenue does your Freelane business get per month?");
    payInput=in.nextDouble();}}

//Calculates the total cost that the user needs
//for renting and tuition solely
public void getTotalCost(){
 totalCost=(payInput/3.75)-(rentExpenses + tuition/4.348);}

//Outputs the total cost
public void outputCost(){
  System.out.println("Your balance per month after expenses is: $"
                       +totalCost);
  if(totalCost<0){
           System.out.println("You still need $"+(-totalCost)+" per months");}
  if(totalCost>0){
           System.out.println("In other words you should be A-O-KAY");}  
              //Balance calculation for an entire school year
           System.out.println("For an entire school year, your expenses would be: "+ 
                                (totalCost*2));}

//Create a file with the information entered 
//and the information processed
public void outputFile() throws IOException{
 String payFileOutput=null;
 Scanner in=new Scanner(System.in);
 System.out.println("Enter the name of the file you wish to store this"+
                     "information in: ");
    String fileName= in.nextLine();

     PrintWriter file= new PrintWriter(fileName);
     file.println("Your rent expenses are                      :"+rentExpenses);
     file.println("Your college tuition in dollars per month is:"+tuition);
     file.println("                                             -----");
     file.println("Your rent expenses and college tuition are  :"+(rentExpenses + tuition));
     if(pay==1)
      payFileOutput="Savings";
     else if(pay==2)
      payFileOutput="Loans";
     else if(pay==3)
      payFileOutput="Freelance Work";
     else
      ;
     file.println("\n\nYou choose "+payFileOutput+"as your income source");
     file.println("Your balance per month after expenses is: $"+totalCost);
     if(totalCost<0){
      file.println("You still need $"+(-totalCost)+"per month");}
     if(totalCost>0){
      file.println("\n\n\nYour budget seems good");}
     file.close();
     System.exit(0);}


}

//The main method: import java.io.*; public class UseClass { /** * @param args */ public static void main(String[] args) throws IOException{ Finance fin=new Finance(); fin.liveWithParents(); fin.amountRent(); fin.collegeTuition(); fin.getMonthlyCost(); fin.payMethod(); fin.inputPayMethod(); fin.getTotalCost(); fin.outputCost(); fin.outputFile(); } }

謝謝

首先想到的是您需要分開關注點。 這意味着您的財務課只能做與財務有關的事情。 應該做這樣的事情在命令行中讀取輸入。

實現這種分離的一種方法是創建另一個類,例如FinanceDataReader之類,並讓它管理所有用戶交互。 它將從命令行獲取數據並將其提供給您的Finance實例。 如果您真的想花哨的話,可以創建一個讀取財務數據的接口,然后使用CommandLineFinanceDataReader實現。 這樣,您可以更改將來獲取數據的方式,而不必更改財務類。

因此,換句話說,將讀取輸入的所有功能移到另一個類中,以使Finance變得更小且更易於維護。 建立封裝所有功能的類,但根據要解決的問題將它們分組。

您可以做的另一件事是使用JUnit之類的框架對代碼進行單元測試。 這將需要一筆前期投資,但是它將幫助您節省時間,因為您將在進行過程中測試所有小細節。 換句話說,您將不會編寫300行代碼,然后必須弄清楚為什么它不起作用。 在編寫每種方法時進行測試將有助於您確保方法/類正在執行您想要的操作。

不用擔心,這種事情是隨時間而來的-如果這是針對您的第一個Java以及可能的OO類的,那么您將犯錯並且設計有限。 如果堅持下去,那會隨着時間的推移而改善。

對於初學者來說,有很多重復的代碼。 您只有幾次遵循相同模式的問題,因此應該將其抽象掉。

class QuestionIO {
  private Scanner in = new Scanner(System.in);

  public boolean boolQuestion(String question) {
    System.out.println(question);
    String result= in.nextLine();
    return (result.charAt(0)=='y' || result.charAt(0)=='Y');
  }

  //other types for doubles or ints
}

這也有助於對代碼進行分區。 您可以邁向MVC類型設計,一類處理IO,另一類處理數據,而另一類控制交互。

隨着時間的推移,構建靈活的,非剛性的代碼是需要學習的,並且結合了設計模式和通用設計原則的使用。 這里有一些關於從哪里開始的技巧。您首先需要對抽象有扎實的了解,並使用DIP(設計反轉原理)。

使用常見的設計模式是獲得靈活性的好方法。 首先,有兩個很好的例子:“策略模式”和“可觀察模式”。 您還希望遵循最佳實踐和原則 ,例如“單一責任原則”,“最少知識原則”,“公開關閉原則”等。這幾個應該讓您入門,但是必須由您來掌握這項技術。

您的大多數方法都是將值存儲在變量中的問題。 您可能能夠創建一個Question / Rule界面,該界面具有一種提示用戶輸入的方法,一種計算結果的方法以及一種輸出的方法。 然后使用自己的獨特邏輯為每個問題創建一個實現。 您的主要方法只是需要遍歷這些問題的列表以進行詢問和報告。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM