2010-11-22 9 views
1

私のクラスプロジェクト用のJavaクラスを作成しましたが、私のメソッドはすべてvoidで、基本的には何もしません。コードをより柔軟にする方法

このコードは、基本的に学生が賃貸料やローンの支払いに関して月収を管理するのに役立ちます。

誰かが間違って何を正しい方向に向けることができますか? コーディングの習慣に関する一般的なアドバイスはありますか?

クラスコード:

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(); } }
が心に来る最初の事はあなたがあなたの懸念を分離する必要があります

+0

'誰かが間違っていることを正しい方向に向けることができますか? 'エラーメッセージ、スタックトレース、またはあなたが何を期待しているかの説明なしに、あなたが間違っていることをどのように知っていると思いますか?あなたは見ていますか? – Falmarri

+0

私はAndreiが、彼のアプローチが、OOのパラダイムやコミュニティで認められたコーディング基準に従って受け入れられるとは考えていないと言います。 – Joel

+0

まったくジョエル。私はちょっとした経験を積んだユーザーから、どうやってやるべきかについて何らかのインプットを得たいと思っています。しかし、私はこの問題が、現在の章の2章で解決されると思います。この章では、クラスとメソッドを再訪していますが、コードをより柔軟にする方法を知りたいと思います。 –

答えて

2

ありがとうございます。これは、あなたのファイナンスクラスが財務に関連することのみを行うべきことを意味します。 ではなく、はコマンドラインからの読み込み入力のようにする必要があります。

この分離を達成する方法は、FinanceDataReaderなどの別のクラスを作成して、すべてのユーザー操作を管理することです。コマンドラインからデータを取得し、それをFinanceインスタンスにフィードします。あなたが本当に欲しいのであれば、財務データを読むためのインターフェイスを作成してから、CommandLineFinanceDataReaderを実装します。そうすれば、将来のデータの取得方法を変更し、Financeクラスを変更する必要がなくなります。

別の言い方をすれば、財務をより小さく維持しやすくするために、入力を読み取る機能を別のクラスに移動します。すべての機能をカプセル化するクラスを構築しますが、あなたが取り組んでいる問題に応じてグループ化します。

もう一つの大きなことは、JUnitのようなフレームワークを使用してコードをテストすることです。それは先行投資を必要としますが、時間の節約に役立ちます。小さなビットをすべてテストするからです。言い換えれば、あなたは300行のコードを書かずに、それがなぜ機能しないのかを理解しなければならない。各メソッドを記述する際にテストすることで、メソッド/クラスが必要なことを確実に実行できるようになります。

この種のことは時間がかかりません。これが初めてのJavaクラスやOOクラスの場合は間違いがあり、デザインが限定されます。それはあなたがそれに固執すると時間とともに改善されます。

+0

財務データを読み取るためのインタフェースを作成することはどういう意味ですか? –

+0

@andrei、これがクラスのためのものなら、あなたはまだそこにいないかもしれません。 http://en.wikipedia.org/wiki/Interface_(Java)を参照してください。 – hvgotcodes

2

はじめに、繰り返しコードがたくさんあります。あなたは同じパターンに従う質問が数回しかないので、それを抽象化してください。

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 
} 

これもまた、コードのパーティション化に役立ちます。 IOを扱うクラスとデータを扱うクラスと相互作用を制御するクラスを持つMVCタイプの設計に移行することができます。

0

ほとんどの方法は、変数に値を格納する質問です。ユーザーに入力を促すメソッド、結果を計算するメソッド、および出力のメソッドを持つ質問/ルールインターフェイスを作成することができます。次に、独自の固有のロジックを使用して各質問の実装を作成します。主な方法は、質問と報告のためにこれらの質問のリストをループするだけです。

0

柔軟な非剛体コードを構築することは、時間の経過とともに学習され、デザインパターンと一般的な設計原則を組み込んだものです。ここでは、始める場所に関するヒントをいくつか紹介します。抽象概念の理解を深め、DIP(Design Inversion Principle)を使用して作業を開始したいと考えています。

共通のデザインパターンを使用すると、柔軟性を実現するのに最適です。いくつかの良い例としては、「戦略パターン」と「観察可能なパターン」があります。 ベストプラクティスと原則に従いたいと思っています。シングル責任原則、最小知識原則、オープンクローズ原則などです。これらのほんの少数は始めるべきですが、テクニックを習得するまではあなた次第です。

関連する問題