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.
Related
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;
}
I am developing an app where I am facing the below issue:
Let's say I have the following expression : 5+9x6/6+SIN(8)+TAN(78) in a calculator app:
So, what I am trying to achieve is that if the editText's current cursor was just after the N in TAN or the N in SIN or the S in COS, and given that the user decided to delete SIN, or COS or TAN, I want to delete the whole String at once (without having the user to delete each of the 3 chars one by one.
That, I have managed to achieve using the below snippet:
int cursorPosition = editTxt.getSelectionStart();
try {
if (editTxt.getText().toString().substring(cursorPosition - 4, cursorPosition).equals("SIN") || ///runs if TAN, COS, or SIN were detected during deletion
editTxt.getText().toString().substring(cursorPosition - 4, cursorPosition).equals("COS") ||
editTxt.getText().toString().substring(cursorPosition - 4, cursorPosition).equals("TAN")) {
Toast.makeText(getApplicationContext(), "here", Toast.LENGTH_SHORT).show();
editTxt.setText(editTxt.getText().delete(cursorPosition - 4, cursorPosition));
editTxt.setSelection(cursorPosition - 4);
}else{
///here is the regular char delete process
editTxt.setText(editTxt.getText().delete(cursorPosition-1,cursorPosition));
editTxt.setSelection(cursorPosition-1);
}
}catch (Exception e){
editTxt.setText(editTxt.getText().delete(cursorPosition-1,cursorPosition));
editTxt.setSelection(cursorPosition-1);
}
BUT THE ISSUE HERE IS: If the user decides to delete the "T" from TAN, then I need to find a way, to delete the rest of the "AN", in other words, I want to delete the whole string "TAN" if the user attempts to delete any of its chars, and the same for SIN and COS as well.
Attached is a short GIF showing what I am trying to achieve (taken from Google Calculator). (Basically I want to prevent the user from setting the placing the cursor anywhere in between the "TAN" , The way it works in Google Calculator"COS" and "SIN"
To anyone who encountered the same scenario, below is my own simple workaround:
if(selEnd != this.getText().length()){
String nextCharacter=this.getText().toString().substring(selStart,selStart+1);
try {
switch (nextCharacter) {
case "A":
case "O":
case "I":
MainActivity.currentPosition = selEnd + 3;
this.setSelection(MainActivity.currentPosition);
break;
case "N":
MainActivity.currentPosition = selEnd + 2;
this.setSelection(MainActivity.currentPosition);
break;
case "S":
if (this.getText().toString().charAt(selStart + 1) != 'I') {
MainActivity.currentPosition = selEnd + 2;
this.setSelection(MainActivity.currentPosition);
break;
}
}
}catch(Exception e){
}
}
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":
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.
I'm making a Character Creator for fun and I seem have run into yet another java problem! I tried googling around for a bit but I didn't seem to find a working solution... I'm trying to use a switch statement for the compiler to output certain information depending on what class (Knight, Archer, Mage) the user chose, but when inputting my code I get error messages
My code so far (cleaned up a bit) is :
String name;
String className;
int attPoints;
System.out.println("Welcome to 'GameName's' Character Creator 2.0!\n");
Thread.sleep(500);
System.out.print("First off, what do you want your characters name to be? \n\nName : ");
name = Scan.nextLine();
Thread.sleep(500);
System.out.print("\nYou are now to be known as "+ name + "!");
System.out.print("\n\n" + name + ", what class do you want to be? ");
System.out.print("\n\nClasses available :\nKnight");
Thread.sleep(1500);
System.out.print("\nMage");
Thread.sleep(300);
System.out.print("\nDruid");
Thread.sleep(300);
System.out.print("\nNinja");
Thread.sleep(300);
System.out.print("\nArcher");
Thread.sleep(300);
System.out.print("\nAdventurer");
Thread.sleep(300);
System.out.print("\nBerserker");
Thread.sleep(300);
System.out.print("\n\nClass : ");
className = Scan.next();
Class userClass = Class.valueOf(className);
Thread.sleep(500);
System.out.println("\nCongratulations! Your class is now : "+ className + "!");
Thread.sleep(500);
// This is where I get an error.
// - Syntax error, insert "enum Identifier" to complete EnumHeaderName
// - Syntax error, insert "EnumBody" to complete BlockStatement
// - Syntax error on token "void", # expected
public void setClass()
switch (Class) {
case Knight:
System.out.println(" Various lore about knights ");
break;
}
}
I THINK I may be trying to create a class inside another class - but when I tried putting it outside it got another error...
Also, I have an int called attPoints, and after I choose a class I want to add 10 to it, but unsure how.
You're switching on Class which is a Java type. Take a look at this tutorial: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/switch.html
You probably want to do something like:
switch (userClass) {
case Class.KNIGHT:
System.out.println(" Various lore about knights ");
break;
}