我面临的问题是,我总是在我的查询中得到daysun
,尽管今天对于我的查询也是monday
。在我的代码中,WDay的值是mon-fri
,因此我构建了这样的开关盒结构,所以我今天应该得到值2
而不是mon-fri
?
Calendar calendar = Calendar.getInstance();
int WDay = calendar.get(Calendar.DAY_OF_WEEK); //Here day has the value 2.
// Create a statement
Statement stt = con.createStatement();
DatabaseMetaData dbm = con.getMetaData();
ResultSet stopsExist = dbm.getTables(null, null, "stops", null);
if (stopsExist.next()) {
// the stops and arrrivaltimes tables exist.
PreparedStatement preparedLatLong = con
.prepareStatement("SELECT lat, longi, name from stops");
ResultSet rsLatLong = preparedLatLong.executeQuery();
while (rsLatLong.next()) {
double lat_stop = rsLatLong.getDouble("lat");
double lon_stop = rsLatLong.getDouble("longi");
double distStops = haversineDistance(latD, longD, lat_stop,
lon_stop);
if (distStops <= 10) {
String stop_name = rsLatLong.getString("name");
String day = "";
switch (WDay) {
case 2:
day = "mon-fri";
case 3:
day = "mon-fri";
case 4:
day = "mon-fri";
case 5:
day = "mon-fri";
case 6:
day = "mon-fri";
case 7:
day = "sat";
case 1:
day = "sun";
}
//In the query here, day has the string sun instead of mon-fri
PreparedStatement preparedTime = con
.prepareStatement("SELECT route from arrivaltimes INNER JOIN stops"
+ " ON arrivaltimes.stop_id=stops.stop_id "
+ "WHERE weekday = '" + day + "'"
+ " and time_format(arrivaltime,'%H:%i')= time_format(curtime() ,'%H:%i') and name LIKE '" + stop_name + "'");
最佳答案
您需要在每个块中添加break
语句:
switch (WDay) {
case 2 :
day = "mon-fri";
break;
case 3 :
day = "mon-fri";
break;
case 4 :
day = "mon-fri";
break;
case 5 :
day = "mon-fri";
break;
case 6 :
day = "mon-fri";
break;
case 7 :
day = "sat";
break;
case 1 :
day = "sun";
break;
default :
throw new RuntimeException("Illegal day: " + WDay);
}
我也喜欢总是添加一个默认的案例,在这种情况下,这将是更不符合原则的,但有时这有助于你在一些奇怪的情况下,你从来没有想过。
如果知道的话,您可以使用Java的fall-through机制不间断地完成它。取决于你认为什么更具可读性。至少这使更改变得更容易,因为您只需要编辑一行而不是五行(甚至更多行)。
switch (WDay) {
case 1 :
day = "sun";
break;
case 2 : // fall-through
case 3 : // fall-through
case 4 : // fall-through
case 5 : // fall-through
case 6 :
day = "mon-fri";
break;
case 7 :
day = "sat";
break;
default :
throw new RuntimeException("Illegal day: " + WDay);
}