[英]Why does this Java Switch-Case not work?
因此,條件中的所有變量都是靜態字符串。 type
本身實際上是一個字符串。
switch(type) {
case (INT || TINYINT):
preparedStatement = setInteger(preparedStatement, value, index);
break;
case (BIGINT || LONG):
preparedStatement = setLong(preparedStatement, value, index);
break;
case (DATETIME || TIMESTAMP):
preparedStatement = setTimestamp(preparedStatement, value, index);
break;
case (MEDIUMTEXT || ENUM || TEXT || LONGTEXT || VARCHAR):
preparedStatement = setString(preparedStatement, value, index);
break;
}
首先,在Java 7+中支持在字符串上的switch
語句,但在Java 6及更高版本中不支持。
接下來, ||
運算符(邏輯或運算符)僅適用於boolean
值,而不適用於String
值。 但是,您可以通過列出案例並在不超過相關代碼的情況下中斷代碼,來在多個案例上運行相同的代碼:
switch(type) {
case INT:
case TINYINT:
// This code will run for INT and TINYINT only.
preparedStatement = setInteger(preparedStatement, value, index);
break;
case BIGINT:
case LONG:
// This code will run for BIGINT and LONG only.
preparedStatement = setLong(preparedStatement, value, index);
break;
// etc.
Java 7 示例 :
public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
String typeOfDay;
switch (dayOfWeekArg) {
case "Monday":
typeOfDay = "Start of work week";
break;
case "Tuesday":
case "Wednesday":
case "Thursday":
typeOfDay = "Midweek";
break;
case "Friday":
typeOfDay = "End of work week";
break;
case "Saturday":
case "Sunday":
typeOfDay = "Weekend";
break;
default:
throw new IllegalArgumentException("Invalid day of the week: " + dayOfWeekArg);
}
return typeOfDay;
}
此外,我從未見過像這樣的switch
內部的OR
語句。 我強烈建議您不要這樣做。
假設您使用的是Java SE 7(或更高版本),並且常量是static final String
,則語法不是Java。
case INT: case TINYINT:
此表達式的計算結果是什么?
INT || TINYINT
INT
和TINYINT
的數據類型是什么
我只見過將switch
與某些原語(Java 7中的新功能)和聲明為final
變量一起使用。
如果這沒有引發編譯錯誤,則||
必須為這些數據類型定義運算符。 但是除非以某種方式在編譯時解決該問題,否則將不允許該運算符。 (同樣,這可能是我不知道的Java 7中的新功能。)
如果您嘗試執行“ 或 ”邏輯,則規范模式(至少在Java的7之前版本中)為:
switch(type) {
case INT:
case TINYINT:
preparedStatement = setInteger(preparedStatement, value, index);
break;
case BIGINT:
case LONG:
preparedStatement =
break;
在Java 7及更高版本中受支持
即使在使用String的情況下,也不能在switch語句中使用邏輯運算符。 您一次只能測試一個案例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.