I am having a piece of if-else code to check if a string is displayed, to my surprise the Else part is not getting executed at all.
For eg: If the error string is shown, the IF part works fine. In cases where the error string is not shown, the Else part is not getting executed. Kindly help
if(getErrText.length() > 0) {
System.out.println(getErrText + " For "+ readerIterator);
} else {
System.out.println(" Error is not displayed - Err Cell" + " For "+ readerIterator);
}
When I make a few assumptions,
public static void main(String[] args) {
String getErrText = ""; // <--------------- To trigger else.
String readerIterator = "Yes it is"; // <-- To display a message.
if (getErrText.length() > 0) { // <-------- else means that getErrText **must** be ""
System.out.println(getErrText + " For "
+ readerIterator);
} else {
System.out.println("Error is not displayed "
+ "- Err Cell For " + readerIterator);
}
}
Output is
Error is not displayed - Err Cell For Yes it is
As I would expect.
Edit
As per comment(s), your actual problem is likely to be one of
// trim() the String!
if (getErrText != null && getErrText.trim().length() > 0) {
// as before...
}
or silently swallowing your exception. Please don't do that.
try {
getErrText = toSearch.errorCell.getText();
getErrText = (getErrText != null) ? getErrText.trim() : "";
}catch(Exception e){
e.printStackTrace();
}
You are probably enclosing this within a block where error is set which is why your getErrText length is always greater than zero.
Could you please add your enclosing code for getting the error text please
In case you else is not getting executed, print the if part of your code and debug.
If both your if and else dont get executed, then the flow is not reaching your if-else at all for those scenarios .
To find out your problem, print the error on your else:
System.out.println(" Error is not displayed - Err Cell" + " For "+ readerIterator+" The getErrText is ["+getErrText+"]);
Related
I have a weird problem. Since I'm new in coding, maybe I am dumb and I don't know how can I resolve this issue, so the issue is, I have 2 commands for my discord bot, permanent mute, and temporary mute. I want to make something like a placeholder to be used in config.yml since it will be more configurable, but when I use args[], I have a weird problem, here is it :
[JDA MainWS-ReadThread] ERROR net.dv8tion.jda.api.JDA - One of the EventListeners had an uncaught exception
java.lang.ArrayIndexOutOfBoundsException: Index 2 out of bounds for length 2
at me.trashlord.bot.events.TempMuteCommand.onGuildMessageReceived(TempMuteCommand.java:34)
at net.dv8tion.jda.api.hooks.ListenerAdapter.onEvent(ListenerAdapter.java:396)
at net.dv8tion.jda.api.hooks.InterfacedEventManager.handle(InterfacedEventManager.java:96)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handleInternally(EventManagerProxy.java:82)
at net.dv8tion.jda.internal.hooks.EventManagerProxy.handle(EventManagerProxy.java:69)
at net.dv8tion.jda.internal.JDAImpl.handleEvent(JDAImpl.java:166)
at net.dv8tion.jda.internal.handle.MessageCreateHandler.handleInternally(MessageCreateHandler.java:97)
at net.dv8tion.jda.internal.handle.SocketHandler.handle(SocketHandler.java:36)
at net.dv8tion.jda.internal.requests.WebSocketClient.onDispatch(WebSocketClient.java:921)
at net.dv8tion.jda.internal.requests.WebSocketClient.onEvent(WebSocketClient.java:808)
at net.dv8tion.jda.internal.requests.WebSocketClient.handleEvent(WebSocketClient.java:786)
at net.dv8tion.jda.internal.requests.WebSocketClient.onBinaryMessage(WebSocketClient.java:959)
at com.neovisionaries.ws.client.ListenerManager.callOnBinaryMessage(ListenerManager.java:385)
at com.neovisionaries.ws.client.ReadingThread.callOnBinaryMessage(ReadingThread.java:276)
at com.neovisionaries.ws.client.ReadingThread.handleBinaryFrame(ReadingThread.java:996)
at com.neovisionaries.ws.client.ReadingThread.handleFrame(ReadingThread.java:755)
at com.neovisionaries.ws.client.ReadingThread.main(ReadingThread.java:108)
at com.neovisionaries.ws.client.ReadingThread.runMain(ReadingThread.java:64)
at com.neovisionaries.ws.client.WebSocketThread.run(WebSocketThread.java:45)
ALSO, here is my code at those lines :
String[] args = event.getMessage().getContentRaw().split("\\s+");
String MutedMessage = ConfigManager.INSTANCE.getSetting("MutedMessage")
.replaceAll("%muteduser", args[1]);
String UnMutedMessage = ConfigManager.INSTANCE.getSetting("UnMutedMessage")
.replaceAll("%unmuteduser", args[1]);
String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
.replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\\d]+", ""))))
.replaceAll("%tempmutetime", args[2]);
if (args[0].equalsIgnoreCase(Commands.prefix + "mute")) {
if (Objects.requireNonNull(event.getMember()).hasPermission(Permission.MESSAGE_MANAGE)) {
if (args.length == 2) {
Member member = event.getGuild().getMemberById(args[1].replaceAll("[^\\d]+", ""));
Role role = event.getGuild().getRoleById(MutedRole);
if (!Objects.requireNonNull(member).getRoles().contains(role)) {
// Mute user
event.getChannel().sendMessage(MutedMessage).queue();
event.getGuild().addRoleToMember(member, Objects.requireNonNull(role)).complete();
} else {
// Unmute user
event.getChannel().sendMessage(UnMutedMessage).queue();
event.getGuild().removeRoleFromMember(member, Objects.requireNonNull(role)).complete();
}
} else if (args.length == 3) {
Member member = event.getGuild().getMemberById(args[1].replaceAll("[^\\d]+", ""));
Role role = event.getGuild().getRoleById(MutedRole);
//event.getChannel().sendMessage(TempMuted1 + " " + args[1] + " " + TempMuted2 + " " + args[2] + " " + TempMuted3).queue();
event.getChannel().sendMessage(TempMuted1).queue();
event.getGuild().addRoleToMember(Objects.requireNonNull(member), Objects.requireNonNull(role))
.complete();
// Unmute after a few seconds
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
event.getChannel().sendMessage(TempUnMuted + " " + args[1] + ".").queue();
event.getGuild().removeRoleFromMember(member, role).complete();
}
},
TimeUnit.MINUTES.toMillis(Integer.parseInt(args[2]))
);
} else {
event.getChannel().sendMessage("Incorrect syntax. Use `~mute [user mention] [time {optional}]`")
.queue();
}
}
}
}
}
the problem is you are trying to get an element from args[2], which may the array only contains 2 elements (length 2) in the following code:
String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
.replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\\d]+", ""))))
.replaceAll("%tempmutetime", args[2]);
Note that in java arrays are zero-based and indexes start from 0 to length - 1.
You can take this code inside the if-condition:
else if (args.length == 3) {
String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
.replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\\d]+", ""))))
.replaceAll("%tempmutetime", args[2]);
// your code
}
Are you sure that this line from your code:
String TempMuted1 = ConfigManager.INSTANCE.getSetting("TempMutedMSG")
.replaceAll("%tempmutedusr", String.valueOf(event.getGuild().getMemberById(args[1].replaceAll("[^\\d]+", ""))))
.replaceAll("%tempmutetime", args[2]);
args[1] and args[2] is correct?
If the length is 2, Then args[2] is looking for the 3rd value and you might not have it...
Have a further look on how length and index works for arrays.
I am currently trying to making a custom rules plugin (for minecraft) and I am trying to see if the player has something activated which I stored in the config file. It is in the listener class (which calls the config from the main). Here is my code:
#EventHandler
public void onEvent(AsyncPlayerChatEvent e) {
Player player = e.getPlayer();
if (config.getInt("EditingLine." + player.getName().toLowerCase()) == 1) {
int line = 0;
try {
line = Integer.parseInt(e.getMessage());
} catch (Exception b) {
player.sendMessage(ChatColor.RED + "Invalid Number.");
config.set("EditingLine." + player.getName().toLowerCase(), 0);
}
if (!(line == 0)) {
config.set("EditingLine." + player.getName().toLowerCase(), 0);
config.set("EditingText." + player.getName().toLowerCase(), 1);
e.setCancelled(true);
player.sendMessage(ChatColor.GRAY + "[" + ChatColor.GOLD + "Custom Rules" + ChatColor.GRAY + "]" + ChatColor.GREEN + " Enter the text you would now like on that line.");
}
}
}
The, config.getInt() function in the if then statement currently returns nothing. This may be happening because the config in the Listener Class is actually calling a custom made config, called 'playerdata.yml' and not the actual 'config.yml'. If there is any easier way to write this script, also let me know. I'm trying to make this as simple as I can.
The answer has been solved by merging my two configuration files together.
I am building a parser that recognizes simple commands such as "DOWN.", "UP." and "REP 3.". It must be able to parse the commands rather freely. It should be legal to write
"DOWN % asdf asdf asdf
."
Where % represents a comment and the fullstop signifying end-of-command. This fullstop can be on the next line.
This is all good and well so far, however I'm struggling with the Rep part (represents Repeat.)
I should be able to issue a command as follows:
DOWN .DOWN. REP 3 " DOWN. DOWN.
DOWN . % hello this is a comment
REP 2 " DOWN. ""
This should give me 17 DOWNS. The semantics is as follows for repeat: REP x " commands " where x is the amount of times it shall repeat the commands listed inside the quotation marks. Note that REP can be nested inside of REP. The following code is for handling the DOWN command. The incoming text is read from System.in or a text file.
public void repeat(String workingString) {
if (workingString.matches(tokens)) {
if (workingString.matches("REP")) {
repada();
} else
if (workingString.matches("(DOWN).*")) {
String job = workingString.substring(4);
job = job.trim();
if (job.equals("")) {
String temp= sc.next();
temp= temp.trim();
// Word after DOWN.
if (temp.matches("\\.")) {
leo.down()
// If word after DOWN is a comment %
} else if (temp.matches("%.*")) {
boolean t = comment();
} else {
throw SyntaxError();
}
} else if (job.matches("\\..*")) {
workingString += job;
System.out.println("Confirm DOWN with .");
}
} else if (workingString.matches("\\.")) {
instructions += workingString;
System.out.println("Fullstop");
} else if (workingString.matches("%.*")) {
comment();
} else {
// work = sc.next();
work = work.trim().toUpperCase();
System.out.println(work);
}
} else {
System.out.println("No such token: " + workingString);
}
}
I got a working start on the repeat function:
public String repada(){
String times = sc.next();
times.trim();
if (times.matches("%.*")) {
comment();
times = sc.next();
}
String quote = sc.next();
quote.trim();
if(quote.matches("%.*")){
comment();
quote = sc.next();
}
String repeater = "";
System.out.println("REP " + times + " "+quote);}
However I'm thinking my whole system of doing things might need a rework. Any advice on how I could more easily solve this issue would be greatly appreciated!
I have written following code snippet:-
public Collection<?> constructResponse (...........) throws RemoteException {
while (keyIterator.hasNext())
{
String keyValue = (String) keyIterator.next();
keyString = new StringBuilder(); // since multiple keys will be there in map need to ensure every time keyString and valueString is created
valueString = new StringBuilder();
keyString.append(keyValue + ";" + "name");
List<CustomValuePOJO> customPOJOlist = employeeValuesMap.get(keyValue );
for (CustomValuePOJO customPOJO : customPOJOlist )
{
if (protocol == null || protocol.equals(""))
{
valueString.append(rpNatPOJO.getDcnPort() + ":"+ rpNatPOJO.getProtocol() + ";");
}
else if (customPOJO .getProtocol().equals(protocol))
{
valueString.append(customPOJO .getPort() + ":"+ protocol + ";");
}
else
{ throw new RemoteException("Invalid Argument: Unsupported protocol "+ protocol);
}
}
if (valueString.length() == 0)
{
return generateErrorResponse("No info found");
}
responseMap.put(keyString.toString(), valueString.toString());
}
}
The weird behavior which is happening is that while iterating through the customPOJO its coming inside elseIf and also setting the value in valueString by executing below code:
else if (customPOJO .getProtocol().equals(protocol))
{
valueString.append(customPOJO .getPort() + ":"+ protocol + ";");
}
After this elseif its coming directly on line
throw new RemoteException("Invalid Argument: Unsupported protocol "+ protocol);
There is no error which is coming in append operation and checked in debug perspective the value is getting appended successfully in valueString.
Please tell what i am missing
Figure I should put this as an answer instead of just a comment...
This sort of behavior can occur when your code (what you are stepping through in the debugger) is out of sync with the compiled class files (that are actually running). Since debug information is associated with line numbers, the lines may be different in the class files than in the source code you see.
Try running a clean build and make sure that there are no duplicate jars on your classpath that may be causing this.
I am trying to create a way of retrieving from a hashtable an authorID for the articleName that the user enters. Here is the code that is activated on the client's side when the user presses a button:
public String getAuthorID() // returns a String
{
try
{
articleName = txtArticleName.getText();
argAuthorID = new Vector();// create vector for the args
argAuthorID.addElement(articleName);// name to search for to get AuthorID
// make the call to the server
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
System.out.println(argAuthorID);
}
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
} catch (Exception exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" + exception.toString());
}
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
return StrAuthorID;
}
This is the method on the server side:
public int sendAuthorID(String articleNameRequest) {
// get info from the hashtable
aNumber = (Integer) theHashtable.getAuthorID(articleNameRequest); // was this.
return aNumber;
}
This is the code in the class that contains the hashtable:
public int getAuthorID(String articleName)
{
int intfoundit;
String foundit = (String)hashtab.get(articleName);
System.out.print(foundit);
intfoundit = Integer.parseInt(foundit);
System.out.print(foundit);
System.out.print(intfoundit);
return intfoundit;
}
The program can retrieve the AuthorID but won't input it into the textbox. Via testing I discovered that the exception was thrown by this code:
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" +
Integer.toString(exception.code) + ": " +
exception.getCause() + "" + exception.toString());
This is the error that is given:
'JavaClient: XML-RPC Consumer Fault #0:
nullorg.apache.xmlrpc.XmlRpcException: java.lang.Exception:
java.lang.NumberFormatException: For input string: " 3377"'
UPDATE: removed the space before the ID number in the hashtable and it doesn't throw an error anymore but it still isn't inputting the ID number into the textbox instead it just inputs a '0'
It seems to be failing in cases when you have spaces in your string. As we can see in your exception trace that parseInt failed to parse " 3377" and it threw NumberFormatException while executing:
intfoundit = Integer.parseInt(foundit);
So you may try to trim the string and see whether it solves your problem:
intfoundit = Integer.parseInt(foundit.trim());
Better you should do the trim where you are saving/putting the key/value in the hashtable.
The answer to the first problem was space before ID number on the hashtable because the space couldn't be converted to an Integer.
The answer to the second problem was that the following line was trying to convert the wrong variable
String StrAuthorID = Integer.toString(authorID); // Cast AuthorID to String
because the Integer was in the AuthorID variable
I corrected this by changing
authorIDVector = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);
to
authorID = (Integer)client.execute("GetSize.sendAuthorID", argAuthorID);