如何让代码更灵活

发布于 2024-10-03 19:34:25 字数 5429 浏览 0 评论 0原文

我为我的类项目编写了一个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(); } }

<代码>

谢谢

I have written a java class for my class project, and all of my methods are are void, and I basically do nothing but call the methods in my main method.

The code basically helps students manage their monthly income, in terms of rent and loan payments.

Can someone point me in the right direction as to what im doing wrong?
Any advice in general in terms of coding habits?

the class code:

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(); } }

Thank you

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

我不是你的备胎 2024-10-10 19:34:25

首先想到的是你需要分离你的关注点。这意味着您的金融课程应​​该只做与金融相关的事情。它不应该做诸如从命令行读取输入之类的事情。

实现这种分离的一种方法是创建另一个类,例如 FinanceDataReader 之类的类,并让它管理所有用户交互。它将从命令行获取数据并将其提供给您的 Finance 实例。如果您真的想变得更奇特,您可以创建一个用于读取财务数据的接口,然后实现 CommandLineFinanceDataReader。这样您就可以更改将来获取数据的方式,而不必更改您的财务课程。

因此,换句话说,将读取输入的任何功能移至另一个类中,以使 Finance 更小且更易于维护。构建封装所有功能的类,但根据您要解决的问题对它们进行分组。

您可以做的另一件大事是使用像 JUnit 这样的框架来对您的代码进行单元测试。这需要前期投资,但会帮助您节省时间,因为您将在进行过程中测试所有小部分。换句话说,你不会写了 300 行代码,然后必须找出它为什么不起作用;在编写每个方法时进行测试将帮助您确保您的方法/类正在执行您想要的操作。

别担心,这类事情会随着时间的推移而出现——如果这是您的第一个 Java 类,也可能是 OO 类,您将会犯错误并且设计有限。如果你坚持下去,随着时间的推移,情况会有所改善。

The first thing that comes to mind is you need to separate your concerns. This means your Finance class should only do things related to finance. It should not do things like read input from the command line.

A way to achieve this separation would be to create another class, something like FinanceDataReader or something, and have it manage all the user interactions. It would get the data from the command line and feed it to your Finance instances. If you really wanted to get fancy, you create an interface for reading finance data, and then have a CommandLineFinanceDataReader implementation. That way you could change how you get data in the future, and not have to change your Finance class.

So, to say it another way, move any functionality that reads input into another class, to make Finance smaller and more maintainable. Build up classes that encapsulate all your functionality, but group them according to the concerns you are addressing.

Another big thing you can do is use a framework like JUnit to unit test your code. It will take an upfront investment, but it will help you save time, because you will test all the small bits as you go. In other words, you wont write 300 lines of code and then have to figure out why its not working; testing as you write each method will help you ensure your methods/classes are doing what you want.

Don't worry, this sort of things comes with time -- if this is for your first Java and possibly OO class, you will make mistakes and have limited design. That will improve with time if you stick with it.

五里雾 2024-10-10 19:34:25

对于初学者来说,有很多重复的代码。您只有几次遵循相同模式的问题,因此您应该将其抽象化。

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,另一个类处理数据,另一个类控制交互。

For starters, there is a lot of repeated code. You only have a few times of questions that follows the same pattern, so you should abstract it away.

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
}

This also helps partition your code. You can move towards a MVC type design with one class dealing with the IO, other with the data, and another one that controlls the interactions.

り繁华旳梦境 2024-10-10 19:34:25

大多数方法都是在变量中存储值的问题。您也许能够创建一个问题/规则界面,该界面具有一种提示用户输入的方法、一种计算结果的方法以及一种输出方法。然后为每个问题创建一个具有其独特逻辑的实现。您的主要方法只需要循环遍历这些问题的列表以进行询问和报告。

Most of your methods are questions that store a value in a variable. You might be able to create a Question/Rule interface that has a method to prompt the user for input, one to calculate the result, and a method for output. Then create an implementation for each question with its own unique logic. Your main method just would need to loop through a list of these questions for asking and reporting.

苍白女子 2024-10-10 19:34:25

构建灵活的、非刚性的代码是需要随着时间的推移而学习的,并且结合了设计模式和通用设计原则的使用。这里有一些关于从哪里开始的提示。您想要从对抽象的深入理解和使用 DIP(设计反转原则)开始。

使用常见的设计模式是实现灵活性的好方法。几个很好的例子是“策略模式”和可观察模式。
您还需要遵循最佳实践和原则,例如单一职责原则、最少知识原则、开闭原则等。这些应该可以帮助您入门,但这取决于您掌握技术。

Building flexible, non-rigid code is something that is learned over time and incorporates the use of design patterns and common design principles . Here are a few tips on where to start.You want to start off with a solid understanding of abstractions and working with the DIP (Design Inversion Principle).

Using common design patterns is a great ways to achieve flexibility. A couple good examples to start with are the "Strategy Pattern", and Observable Pattern.
You also want to follow best practices and principles, such as the Single Responsibility Principle, Principle of Least Knowledge, Open Close Principle, etc.. Those few should get you started, but it's gotta be up to you to master the technique.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文