Transforming if-else into switch case throws error [Java] - java

I tried to convert my if-else statements into a switch case but I had the following problem.
Old code:
if (properties.get("database").toString().equalsIgnoreCase("SQLSERVER")) {
manager = new CManagingSQLServer();
} else if (properties.get("database").toString().equalsIgnoreCase("ORACLE")){
manager = new CManagingOracle();
} else if (properties.get("database").toString().equalsIgnoreCase("MYSQL")){
manager = new CManagingMySQL();
} else {
System.out.println("Not supported DB: " + properties.get("database").toString() + "\n");
System.out.println("Supported DB:");
System.out.println("- ORACLE");
System.out.println("- SQLSERVER");
System.out.println("- MYSQL");
System.exit(0);
}
New code:
String database = properties.get("database").toString();
switch (database) {
case database.equalsIgnoreCase("SQLSERVER"):
manager = new CManagingSQLServer();
break;
case database.equalsIgnoreCase("ORACLE"):
manager = new CManagingOracle();
break;
case database.equalsIgnoreCase("MYSQL"):
manager = new CManagingMySQL();
break;
default:
System.out.println(database + "is not a supported database.");
System.exit(0);
break;
}
First, the String database threw an error that I have to change setting/property (actually don't know) into version 1.7?! After doing so, my cases are throwing now errors. They say: Type mismatch cannot convert from boolean to String.
I read other SO-thread and they said I have to try (String)something or something.ToString(). But both cases didn't work and I don't understand what changed with the above mentioned change to version 1.7.
And how can I make my cases work again?

Change database variable to
String database = properties.get("database").toString().toUpperCase();
And switch case to
case "SQLSERVER":
Currently, you are getting error because database.equalsIgnoreCase("SQLSERVER") returns boolean but you are switching on database which is a String.
Also, you need to use minimum of Java 7 because Java versions before that don't support switch case on String.

The problem you are facing is that in switch you pass a String typed database.
In case of section you want to work with boolean expression database.equalsIgnoreCase(...).
The easiest way to deal with that is to change the line:
String database = properties.get("database").toString();
to:
String database = properties.get("database").toString().toUpperCase();
and in case section use simple approach (as you have already upper cased database variable):
case "SQLSERVER"
instead of
case database.equalsIgnoreCase("SQLSERVER")
INFORMATION:
Switch expressions that work with strings are available from JDK 7.

you are missing the whole concept of switch case , you don't have to put equal condtion in your switch case.
just put like this it will work fine
String database = properties.get("database").toString().toUpperCase();
switch (database) {
case "SQLSERVER":
manager = new CManagingSQLServer();
break;
case "ORACLE":
manager = new CManagingOracle();
break;
case "MYSQL":
manager = new CManagingMySQL();
break;
default:
System.out.println(database + "is not a supported database.");
System.exit(0);
break;
}

Use the string value in case statements.
Case "SQLSERVER":

Related

Can you refer to case values inside the code block of the switch statement?

So can you do something like this in Java:
Can you get the value being switched on inside a switch expression
I have quite a few cases in my code which look like this (actual logic code removed for clarity reasons):
switch (weatherSystem.getRealClass().getSimpleName())
{
case "SyncWeatherSystem":
logger.info("initializing sync weather system");
…
break;
case "AsyncWeatherSystem":
logger.info("initializing async weather system");
…
break;
case "FixedWeatherSystem":
logger.info("initializing fixed weather system");
…
break;
case "NoWeatherSystem":
logger.info("initializing no weather system");
…
break;
}
And I really would love to do like:
switch (weatherSystem.getRealClass().getSimpleName())
{
case "SyncWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "AsyncWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "FixedWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
case "NoWeatherSystem":
logger.info("initializing {}", case.value);
…
break;
}
Is this possible in Java?
No. It is not. But, weatherSystem.getRealClass().getSimpleName() is. I suggest you save that value to a local variable. And all your case(s) seem to do the same thing. So, as posted, you could simplify it. Like
String sName = weatherSystem.getRealClass().getSimpleName();
switch (sName)
{
case "SyncWeatherSystem":
case "AsyncWeatherSystem":
case "FixedWeatherSystem":
case "NoWeatherSystem":
logger.info("initializing {}", sName);
break;
}

Given an int variable status, write a switch statement that prints out, on a line by itself, the appropriate label from the above list based on status

HTTP is the protocol that governs communications between web servers and web clients (i.e. browsers). Part of the protocol includes a status code returned by the server to tell the browser the status of its most recent page request. Some of the codes and their meanings are listed below:
200, OK (fulfilled)
403, forbidden
404, not found
500, server error
Given an int variable status, write a switch statement that prints out, on a line by itself, the appropriate label from the above list based on status.
This is what I have for my code but it's still not working and I am unsure as to why.
switch ( status ){
case 200: System.out.println("OK(fulfilled)");
break;
case 403: System.out.println("forbidden");
break;
case 404: System.out.println("not found");
break;
case 500: System.out.println("server error");
break;
}
The error I get is "The value of _stdout is incorrect."
Would you be able to post your entire source code?
Have you tried using the default case as shown below?
public void run() {
//enter a test case here to see if your console prints the output:
int status = readInt("Enter case here: ");
switch ( status ){
case 200: System.out.println("OK(fulfilled)");
break;
case 403: System.out.println("forbidden");
break;
case 404: System.out.println("not found");
break;
case 500: System.out.println("server error");
break;
//Try the default case here:
default:
break;
}
}
}
I had the same problem and figured out you're supposed to use System.out.print(""), because it's supposed to be entered on a line by itself.

Scanner Input is Invisible

I have a Problem with the Scanner from Java. My Problem is, that I currently write a CloudSystem for Minecraft, and I code a Master and a Wrapper. On Wrapper the Scanner works perfectly, but on the Master not. The Problem is, that on the Master, the Input I write in the Console is not displayed, and I have to hit Enter twice, so the Scanner get the Input. The Code is on the Wrapper and the Master quite the same, just a few edits on the switch case. Also its a little bit strange, that it works on Windows but not on Debian.
Here is my Code:
public static void startScreen() {
System.out.println(AnsiColor.GREEN + "Was moechtest du tun?");
while (true) {
String action = new Scanner(System.in).nextLine();
switch (action) {
case "close":
WebSocketServer.group.shutdownGracefully();
shutdownServers();
bcprocesse.destroy();
System.exit(0);
break;
case "creategroup":
createGroup();
break;
case "groups":
Group.list();
break;
case "users":
User.list();
break;
case "deletegroup":
deleteGroup();
break;
case "help":
help();
break;
case "createuser":
createUser();
break;
case "deleteuser":
deleteUser();
break;
case "request":
System.out.println(AnsiColor.GREEN + "Welche Gruppe willst du benutzen? Es gibt: " + Group.getGroupsAsList().toArray().toString() + "\n");
requestServer(new Scanner(System.in).nextLine());
}
}
}
I hope someone can help me.
P.S. Sorry when anything is not understandable, I'm from Germany.
Fixed it... My problem was that I had started a Netty Server before and therefore I forgot to start it in a new Thread so it doesn't block the main Thread... Oops! I hope I could help other Devs with that, because sometimes.. you just don't think about situations like that.

How to Add Validations(Numeric,Date) to a Particular Cell using POI

How to add a Integer Validation, Date Validation to a Particular Cell Using POI.
and validate after the user enters data, show an error message if data is wrong
thanks in advance
I once encountered a similar situation for validating an excel file. You can code like this:
if(cell != null){
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
//Validate String as required
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
//Validate Date
} else {
//Validate Number
}
break;
default:
//Handle Default
}
}
I suggest that you write separate validation handlers for each type (string, number and date) and just invoke them from your switch case.

Reading in a text file and comparing text - Java

In my program I am reading in and parsing a file for resources.
I extract a string which represents the resource type, do a simple if then else statement to check if it matches any known types and throw an error if it doesn't:
if(type.toLowerCase() == "spritesheet") {
_type = ResourceType.Spritesheet;
} else if(type.toLowerCase() == "string") {
_type = ResourceType.String;
} else if(type.toLowerCase() == "texture") {
_type = ResourceType.Texture;
} else if(type.toLowerCase() == "num") {
_type = ResourceType.Number;
} else {
throw new Exception("Invalid Resource File - Invalid type: |" + type.toLowerCase() + "|");
}
Ignoring my bad naming and non descript exception, this statement is always going to the final else, even if type IS "spritesheet" as read in from the file, etc.
java.lang.Exception: Invalid Resource File - Invalid type: |spritesheet|
at Resource.Load(Resource.java:55) //Final else.
If I set type to "spritesheet" before this call, it works, so I'm wondering if it's some kind of encoding error or something?
I haven't done much work in java so I might be missing something simple :)
Assuming type is a String, you want to use String.equals() to test for equality. Using the == operator tests to see if the variables are references to the same object.
Also, to make your life easier, I would suggest using String.equalsIgnoreCase() as this will save you from calling toLowerCase().
Starting from Java 7 you can use Strings in switch statements! :)
The following should work:
switch (type.toLowerCase()) {
case "spritesheet": _type = ResourceType.Spritesheet; break;
case "string": _type = ResourceType.String; break;
case "texture": _type = ResourceType.Texture; break;
case "num": _type = ResourceType.Number; break;
default: throw new Exception("Invalid Resource File " +
"- Invalid type: |" + type.toLowerCase() + "|");
}
I haven't tried it yet, let me know how it goes!

Categories

Resources