所以我有这个程序读取Java文本文件并打印出数字,这是电费。然后它找出最大值并将其与最大值的月份一起打印出来。我的老师寻找代码的效率,我想知道是否有更简单或可能的方法来计算一年中的几个月,而不是使用if else语句。我读到了它并且我非常确定Java存储了几个月,但我不确定如何实现它。 (我刚开始学习java所以请使用基本术语/代码)
我的代码是:
if (count == 0)
System.out.println("File had no numbers");
else {
String month="";
if (count==1) month="January";
else if (finalcount==2) month="February";
else if (finalcount==3) month="March";
else if (finalcount==4) month="April";
else if (finalcount==5) month="May";
else if (finalcount==6) month="June";
else if (finalcount==7) month="July";
else if (finalcount==8) month="August";
else if (finalcount==9) month="September";
else if (finalcount==10) month="October";
else if (finalcount==11) month="November";
else if (finalcount==12) month="December";
System.out.println("Largest Bill: "+max+ " (" +month+")");
System.out.println("Total Yearly Sum: $"+((int)sum*100)/100.0);
}
谢谢!
答案 0 :(得分:0)
最简单的方法是使用存储月份的数组,创建一个如下数组:
String months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
完成后,您向我们展示的代码可以更改为以下内容:
if (count > 0) {
month = months[count-1];
System.out.println("Largest Bill: "+ max + " (" + month + ")");
System.out.println("Total Yearly Sum: $" + ((int)sum*100)/100.0);
}
else {
System.out.println("File had no numbers");
}
正如其他人所说,你可以使用内置的Calendar
类,但对于初学者来说并不是这么简单。
答案 1 :(得分:0)
我不确定你为什么要将变量从count更改为finalcount。至于另一种解决问题的方法可能是switch语句(如果你想以类似的方式执行它),数组或使用Java的Calendar。一个简单的方法是:
public static String getMonth(int count) { //using the same variable you used
//I'm going to abbreviate for sake of finishing this faster
String answer[] = {"File had no numbers","Jan","Feb","Mar","Apr","May","June","July","Aug","Sep","Oct","Nov","Dec"};
return answer[count];
}// all this will do what you did.
要使用此功能,您只需将其称为任何其他方法,并传递'count'变量。