我修复了关于计算声明和输入变量的java代码.
public class JavaApplication1 { /** * @param args the command line arguments */ static Scanner sc = new Scanner(System.in); static double maxLoad = 500; static double currLoad; static double loadInput = 0; public static void main(String[] args) { String cpNumber; System.out.print("Enter Cellphone Number: "); cpNumber = sc.nextLine(); // System.out.println(); System.out.print("Enter load to be bought: "); loadInput = sc.nextDouble(); currLoad = computeLoad(maxLoad, loadInput); System.out.println(loadInput + " was loaded to " + cpNumber); System.out.println("Current Load Wallet is now only : " + currLoad); } public static double computeLoad(double x, double y) { return x - y; } }
我只想征求专业人士的意见,如何改进我的代码编写以及如何添加一个setter getter方法,就像输入值不正确时返回一些东西一样的验证.
那么,让我们分析一下代码的优缺点.
您的方法适当命名
您的变量符合Java命名约定
您的命名表示变量的用途(在大多数情况下).
缺点.
你在滥用静态.
你没有任何评论
您没有将constant(maxLoad
)声明为final
变量.
您的班级名称并未表明该课程的目的.
你已经让你的班级成员暴露了.这些应该是私有的,如果用户需要了解它们,那么应该有一些getters
并setters
检索它们.
你的方法中有参数x
和参数.什么是和?这是晦涩的命名,你应该避免和不惜一切代价(当然,除非你使用的坐标).y
computeLoad
x
y
x
y
因此,经过一番考虑,我将这种思维应用到您的代码中并进行了以下更改:
public class Wallet { // The scanner used to read input data. private Scanner sc; // The maximum load allowed in the wallet. private final double MAX_LOAD = 500; // The current load in the wallet. private double currLoad; // The current input from the user. private double loadInput; /** This is the constructor. **/ public JavaApplication1() { sc = new Scanner(System.in); currLoad = 0.0; loadInput = 0.0; readInput(); } /** * Reads input from the user. * */ public void readInput() { System.out.print("Enter Cellphone Number: "); cpNumber = sc.nextLine(); System.out.print("Enter load to be bought: "); loadInput = sc.nextDouble(); // Perform calculation using input. currLoad = computeLoad(maxLoad, loadInput); System.out.println(loadInput + " was loaded to " + cpNumber); System.out.println("Current Load Wallet is now only : " + currLoad); } /** * Performs computation on the input. * @param maxLoad the first value. * @param loadInput the second value. **/ private double computeLoad(double maxLoad, double loadInput) { return maxLoad - loadInput; } /** The main thread. Used to create a new instance of JavaApplication1. * * This is so we don't need to litter static all over the place. */ public static void main(String[] args) { new Wallet(); } }
吸气剂和二传手
使用闪亮的新代码,可能是时候添加一些getter和setter了.它们有一个非常明确的命名约定,您必须遵循100%.我给你举个例子.假设你想为你的currLoad
价值写一个吸气剂.那么它看起来像这样:
/** * Returns the current load. * @return the current wallet load. */ public double getCurrLoad() { return currLoad; }
看看它是如何预先填写的get
,所有后续的单词都以大写字母开头?下一个是制定者.
/** * Updates the value in currLoad. Sets a new current wallet load. * * @param currLoad the new current wallet load. */ public void setCurrLoad(double currLoad) { this.currLoad = currLoad; }