所以我有这个程序,它读取一个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);
}
谢谢!
最简单的方法是使用存储月份的数组,创建一个如下所示的数组:
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
类,但对于初学者来说,它并不像这样简单。
我不确定为什么您将变量从计数更改为最终计数。至于解决问题的另一种方法可能是switch语句(如果你想以类似的方式执行它(,数组或使用Java的日历。一个简单的方法是:
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"变量。