2010-11-22 3 views
1

내 수업 프로젝트 용 자바 클래스를 작성했으며 모든 메소드가 무효이며 기본적으로 아무 것도하지 않고 내 기본 메소드에서 메소드를 호출합니다.코드를보다 융통성있게 만드는 방법

이 코드는 기본적으로 학생이 월세를 임대료 및 대출 지불과 관련하여 관리하는 데 도움이됩니다.

어떤 사람이 잘못된 방향으로 올바른 방향으로 나를 가리킬 수 있습니까? 일반적으로 코딩 습관에 대한 조언이 있습니까?

클래스 코드 :

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

정확히 Joel. 나는 경험이 많은 사용자로부터 어떻게해야하는지에 대한 의견을 얻고 싶습니다. 하지만이 문제는 책이 클래스와 메소드를 다시 방문하는 현재 장의 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) 작업으로 시작하고 싶습니다.

일반적인 디자인 패턴을 사용하면 유연성을 얻을 수 있습니다. 몇 가지 좋은 예가 "Strategy Pattern"과 Observable Pattern입니다. 모범 사례 및 원칙 (단일 책임 원칙, 최소 지식 원칙, 공개 종결 원칙 등)을 따르기를 원할 수도 있습니다. 그 중 일부는 시작해야하지만 기술 습득에 달려 있습니다 .

관련 문제