我对Java非常陌生,我想尝试制作一个可以告诉用户在一定时间内节省多少的吸烟计算器。如果有人能告诉我他们会在哪里改进我的代码,以及他们会添加哪些其他特性,我会很感激。
在用java编写代码时,即使是这样的基本程序,我也应该始终使用对象吗?
import java.util.Scanner;
public class Calculator {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
//Packets
System.out.println("How many packets do you smoke a week?");
double packets = scan.nextDouble();
//cost
System.out.println("How much is each packet?");
double cost = scan.nextDouble();
//weekly
double weekly;
weekly = (cost*packets);
System.out.println("In one week you would save: €" + weekly);
//monthly
double monthly;
monthly = (weekly*4);
System.out.println("In one month you would save: €" + monthly);
//threeMonths
double threeMonths;
threeMonths = (weekly*12);
System.out.println("In three months you would save: €" + threeMonths);
//sixMonths
double sixMonths;
sixMonths = (weekly*26);
System.out.println("In six months you would save: €" + sixMonths);
//yearly
double yearly;
yearly = (weekly*52);
System.out.println("In one year you would save: €" + yearly);
//user input
System.out.println("Enter a number of years and see how much you will save over that time period...");
double user = scan.nextDouble();
double userInput;
userInput = (yearly*user);
System.out.println("You would save €" + userInput + " in " + user + " years.");
scan.close();
}
}发布于 2017-04-16 17:54:27
在用java编写代码时,即使是这样的基本程序,我也应该始终使用对象吗?
你怎么会不呢?请注意,您现在正在此程序中使用一个对象,即Scanner对象。您还使用了Calculator类。因为这当然是Java的工作方式。在类之外没有任何方法。
现在,您应该创建一个中间类和对象吗?也许吧。也许不是。我想在这里看到更多的方法。例如,考虑
public static void displayForTimePeriod(String message, double amount, double multiplier) {
System.out.println(message, amount * multiplier);
}这将使您可以将大部分代码简化为
double weekly = cost * packets;
displayForTimePeriod("In one week you would save: €", weekly, 1.0);
displayForTimePeriod("In one month you would save: €", weekly, 30/7.0);
displayForTimePeriod("In three months you would save: €", weekly, 13.0);
displayForTimePeriod("In six months you would save: €", weekly, 26.0);
displayForTimePeriod("In one year you would save: €", weekly, 52.0);您可以更进一步,创建一个类,但是它所包含的主要内容将是amount。请注意,在每次调用中都保持不变。
我想补充一下
System.out.println("On average, you'll save €" + (weekly/7) + " every day.");如果您愿意,可以通过包括闰年来使您的年计算更加准确。这将要求您从系统时间获取当前日期。记住要处理跨越几个世纪。2000年是闰年,但1900年不是,2100年也不是。
我让每月的数字更准确。除非月份是二月,否则一个月有超过二十八天(四个星期)。通常的近似是30。
我还修正了季度(三个月)的数字。大多数季度有十三周(例外是二月没有闰日的第一季度)。每季度十二周都太少了。
发布于 2017-04-21 10:24:09
在用java编写代码时,即使是这样的基本程序,我也应该始终使用对象吗?
一般来说,如果你一开始就简单的话,学点东西就更容易了。在一辆小车里学开车比在1000‘s的科尼赛克里学要好。如果你不处于学习阶段,这取决于它是一个“抛弃”应用程序还是一个高效的应用程序。
对于您的代码,我只是重新编写了其中的一小部分,以便给您一个想法。
https://codereview.stackexchange.com/questions/160919
复制相似问题