Limit to the number switch/if options? - java

Small disclaimer I am new to Java and this is my first real programme i am trying to write.
I am currently writing a programme with 3 class's. The first is a GUI with a JComboBox, 4 JButtons and 20 JTextFields.
The second takes information from the JComboBox box and uses it to give labels to the 4 JButtons using a set of if statements.
The third populates the JTextFields when one of the the JButtons is clicked depending on the button clicked and the choice in the JComboBox using a set of switch statements.
The first 2 class's work fine and the third works fine until i enter x amount of switches and then i start to get an error.
A small example of my code for the third class is
switch (hiddenText) {
case "Abecean Longfin":
if (command.equals("Weakness to Frost")){
gui.r1.setText("Elves Ear");
gui.r2.setText("Fire Salts");
gui.r3.setText("Ice Wraith Teeth");
gui.r4.setText("White Cap");
gui.r5.setText("");
gui.r6.setText("");
gui.r7.setText("");
gui.r8.setText("");
gui.r9.setText("");
gui.r10.setText("");
gui.r11.setText("");
gui.r12.setText("");
gui.r13.setText("");
gui.r14.setText("");
gui.r15.setText("");
gui.r16.setText("");
gui.r17.setText("");
gui.r18.setText("");
gui.r19.setText("");
gui.r20.setText("");
}
if (command.equals("Fortify Sneak")){
gui.r1.setText("Beehive Husk");
gui.r2.setText("Frost Mirriam");
gui.r3.setText("Hawk Feathers");
gui.r4.setText("Human Flesh");
gui.r5.setText("Powdered Mammoth Tusk");
gui.r6.setText("Purple Mountain Flower");
gui.r7.setText("");
gui.r8.setText("");
gui.r9.setText("");
gui.r10.setText("");
gui.r11.setText("");
gui.r12.setText("");
gui.r13.setText("");
gui.r14.setText("");
gui.r15.setText("");
gui.r16.setText("");
gui.r17.setText("");
gui.r18.setText("");
gui.r19.setText("");
gui.r20.setText("");
}
if (command.equals("Weakness to Poison")){
gui.r1.setText("Bleeding Crown");
gui.r2.setText("Chaurus Eggs");
gui.r3.setText("Deathbell");
gui.r4.setText("Giant Lichen");
gui.r5.setText("Pine Thrush Egg");
gui.r6.setText("Sabre Cat Tooth");
gui.r7.setText("Small Antlers");
gui.r8.setText("");
gui.r9.setText("");
gui.r10.setText("");
gui.r11.setText("");
gui.r12.setText("");
gui.r13.setText("");
gui.r14.setText("");
gui.r15.setText("");
gui.r16.setText("");
gui.r17.setText("");
gui.r18.setText("");
gui.r19.setText("");
gui.r20.setText("");
}
if (command.equals("Fortify Restoration")){
gui.r1.setText("Cyrodilic Spadetail");
gui.r2.setText("Salt Pile");
gui.r3.setText("Small Antlers");
gui.r4.setText("Small Pearl");
gui.r5.setText("");
gui.r6.setText("");
gui.r7.setText("");
gui.r8.setText("");
gui.r9.setText("");
gui.r10.setText("");
gui.r11.setText("");
gui.r12.setText("");
gui.r13.setText("");
gui.r14.setText("");
gui.r15.setText("");
gui.r16.setText("");
gui.r17.setText("");
gui.r18.setText("");
gui.r19.setText("");
gui.r20.setText("");
}
break;
There are a total of 92 cases, each with 4 if statements and the programme works fine until i get to 57 cases and 2 if statements then i get an error symbol in the class tab title in IDE (using NetBeans) but not within the code itself.
When i compile and run the code i get an error box appearing saying "One or more projects compiled with errors" but if i choose to run anyway the programme will run fine as far as i have seen.
I have tried writing the code in various ways.e.g. originally using if statements and originally having class 2 and 3 as the same class and i always get this error at reaching x amount of choices.
In previous versions i would sometimes get the error symbol appear in the class tab title in the IDE and not within the code as usual but when trying to run the programme it wouldn 't run at all and gave some classpath error which i can't seem to reproduce now so can't post the exact code.
From the testing i have done.e.g. removing different sections of code it appears that it happens when x amount of choices are added.i.e. i can add the 52nd case and 3rd if statement and the error appears but if i remove a previous if statement so there are 52 cases and 2 if statements still then everything if fine.
From experimenting it would seem there is a limit to the amount of switches/if statements i can use although from looking around i could in theory have an infinite amount?
So my question is, is there a limit to the amount of switches/if statements i can use or is there something else going on which is causing an error when i enter x number of switches/if statements?

you need to separate your data from your code. stick all that data in a combination of maps and lists and use some simple, common code to update the gui elements.
// setup data code
List<String> elements = Arrays.asList("Elves Ear", "Fire Salts", ...);
Map<String,List<String>> elementMap;
elementMap.put("Weakness to Frost");
// setup ui code
List<String> elements = elementMap.get(command);
initUI(elements);
public void initUI(List<String> elements) {
gui.r1.setText(elements.get(0));
// ...
}
note, you could keep all your text fields in a List, and then the update code is:
public void initUI(List<String> elements) {
for(int i = 0; i< textFields.size(); ++i) {
textFields.get(i).setText(elements.get(i));
}
}
in general, if you find yourself writing a lot of repetitive code, you are probably doing it wrong.
also, as #thatidiotguy pointed out in the comments, as you advance, you could move the data out of code like my example and into some sort of separate config file.

Related

Java Zkoss Frontend Framework - Break line in property label

I invested too much time, now I want to ask you how can I insert a line break at a specific position in the value of a .properties file-property. for example, I have:
the zul:
<zk xmlns:h="native" xmlns:x="xhtml">
<groupbox width="850px">
<caption label="${c:l('not this label')}" />
<h:table >
<h:tr>
<h:td>
<h:label>${c:l('mylabel.linebreakedlabel')}</h:label>
</h:td>
....
the .properties file:
mylabel.linebreakedlabel = Hello this label should be breaked into two lines
I tried many different solutions:
A:
Hello this label should be \ breaked
into two lines
-> second line in label gets thrown away
B:
{
Hello
second line
}
-> The {} gets rendered and second line is thrown away
C:
\n with and without enter either renders the sign or throws away the whole second line
D:
Tried </br>, the element itself gets rendered
Im asking on this platform because ZK Forums won't send me an email to confirm my register.
Anyone knows the problem or atleast know where the problem lies? (Using ZK Version 6)
Thank you!
please read Specify a Value with Multiple Lines, its code example, and properties file example .

Method does nothing if called within an if, if called directly from on event it works

I`m building a discord bot with jda, made a method to use mXparser to get a math operation as an input from the chat e.g: /math 5+1
wrote everything to get the message, separate the arguments from the input on the chat, everything works until I put the code inside an IF statement that checks if it actually starts with "/math", the code inside it uses mXparser to calculate everything and send it back to chat.
Tried just about everything I could think of, taking all variables off the method, rewriting everything, I don`t get any errors either as stack trace or in the code editor, it just doesnt go through, tried just printing everything and it works fine as well, printing all the values on the console, everything seems to be right.
This part is where I check for the message, get the Strings and trim everything
public void onMessageReceived(MessageReceivedEvent event) {
this.messageReceived = event;
this.prefix = Main.prefix;
checkPrefix = messageReceived.getMessage().getContentRaw().split("\\s" + prefix);
mainArg = checkPrefix[0];
checkArgs = messageReceived.getMessage().getContentRaw().split(" ");
callAllCommands();
}
Here is the command to take the actual expression from the chat input calculate it and send it back.
private void mathCommand() {
mathexp = new Expression(checkArgs[1]);
messageReceived.getChannel().sendTyping().queue();
essageReceived.getChannel().sendMessage(Double.toString(mathexp.calculate())).queue();
}
This is inside the callAllCommands() method, that is how it is supposed to work, if the command on the chat is /math then the expression e.g: /math 1+1 it will send the result back, if I take off the IF statement it works just fine but then I can't check for the command. The other commands do work fine with the IF statement
if (mainArg.contentEquals(prefix + "math")) {
mathCommand();
}
I don't really get any errors, it just does not work, sorry if I missed something really simple, i`m not that experienced yet.

showing error in java

I want to create an application that shows a user how many times he opened or used the software. For this I have created the code below. But it is not showing correct output: when I run the application first it is showing 1 and then the second time I run it it is also showing 1.
public Founder() {
initComponents();
int c=0;
c++;
jLabel1.setText(""+c);
return;
}
I’m unsure whether I’m helping you or giving you a load of new problems and unanswered questions. The following will store the count of times the class Founder has been constructed in a file called useCount.txt in the program’s working directory (probably the root binary directory, where your .class files are stored). Next time you run the program, it will read the count from the file, add 1 and write the new value back to the file.
static final Path counterFile = FileSystems.getDefault().getPath("useCount.txt");
public Founder() throws IOException {
initComponents();
// read use count from file
int useCount;
if (Files.exists(counterFile)) {
List<String> line = Files.readAllLines(counterFile);
if (line.size() == 1) { // one line in file as expected
useCount = Integer.parseInt(line.get(0));
} else { // not the right file, ignore lines from it
useCount = 0;
}
} else { // program has never run before
useCount = 0;
}
useCount++;
jLabel1.setText(String.valueOf(useCount));
// write new use count back to file
Files.write(counterFile, Arrays.asList(String.valueOf(useCount)));
}
It’s not the most elegant nor robust solution, but it may get you started. If you run the program on another computer, it will not find the file and will start counting over from 0.
When you are running your code the first time, the data related to it will be stored in your system's RAM. Then when you close your application, all the data related to it will be deleted from the RAM (for simplicity let's just assume it will be deleted, although in reality it is a little different).
Now when you are opening your application second time, new data will be stored in the RAM. This new data contains the starting state of your code. So the value of c is set to 0 (c=0).
If you want to remember the data, you have to store it in the permanent storage (your system hard drive for example). But I think you are a beginner. These concepts are pretty advanced. You should do some basic programming practice before trying such things.
Here you need to store it on permanent basic.
Refer properties class to store data permanently: https://docs.oracle.com/javase/7/docs/api/java/util/Properties.html
You can also use data files ex. *.txt, *.csv
Serialization also provide a way for persistent storage.
You can create a class that implements Serializable with a field for each piece of data you want to store. Then you can write the entire class out to a file, and you can read it back in later.Learn about serialization here:https://www.tutorialspoint.com/java/java_serialization.htm

Selenium sends incomplete text

I'm having a problem with Selenium when it comes to use .sendKeys(text). During the automation process, sometimes selenium is sending incomplete strings to the browser, which causes to create incorrect searchs.
i.e. I want to type "MY DROP", and it will type "Y DROP", or "ROP".
It does not always type the same way, so sometimes 2 letters might be missing, and sometimes the whole word is missing.
This only happens to dropdowns, where I have a specific method that handles the dropdown selection, as we are using angular I can't use the selenium select dropdown method.
I already tried to set Thread.Sleeps and waits on the dropdown selection but nothing seems to work, currently this is what I use to select a value:
public void select(String item) {
waitTillClicable();
WebElement element = getElement();
openDropDown(element);
element.sendKeys(item);
waitResultLoad();
selectResult(element);
}
This code was working perfectly until the last week. I'm thinking it has something to deal with the new Chrome version 45, as before it was not happening. I also tried to use different chromedriver versions, and running on a Linux machine, but nothing seems to have an effect.
Right now I created a workaround where I keep verifying if the string was typed correctly, and re-typing it until it is correct, but this makes the execution time increased, which I wanted to avoid.
Why are you using .sendKeys() to select a value in a SELECT? Use the provided methods for a Select: .selectByIndex(int), .selectByValue(String), or .selectByVisibleText(String). Some examples...
Select test = new Select(driver.findElement(By.id("dropdown")));
test.selectByIndex(1);
test.selectByValue("myValue");
test.selectByVisibleText("VisibleText");
See if the happens on Firefox driver or IE driver
The other thing is the method signature is
public void sendKeys(CharSequence... value)
can you try to send it like this sendKeys( "MY","DROP"); instad and see the result
Hope this may help.
Alan Mehio
London, UK

Issue with running JAR from Desktop, but not from command line or Eclipse

I am running into a peculiar issue (peculiar for me anyways) that seems to happen in a SwingWorker that I use for saving the result of another 'SwingWorker' thread as a tab-delimited file (just a spreadsheet of data).
Here is the worker, that initializes and declares an object which organizes the data and writes each table row to a file (using BufferedWriter):
// Some instance variables outside of the SwingWorker:
// model: holds a matrix of numerical data (double[][])
// view: the GUI class
class SaveWorker extends SwingWorker<Void, Void> {
/* The finished reordered matrix axes */
private String[] reorderedRows;
private String[] reorderedCols;
private String filePath; // the path of the file that will be generated
public SaveWorker(String[] reorderedRows, String[] reorderedCols) {
// variables have been checked for null outside of the worker
this.reorderedRows = reorderedRows;
this.reorderedCols = reorderedCols;
}
#Override
protected Void doInBackground() throws Exception {
if (!isCancelled()) {
LogBuffer.println("Initializing writer.");
final CDTGenerator cdtGen = new CDTGenerator(
model, view, reorderedRows, reorderedCols);
LogBuffer.println("Generating CDT.");
cdtGen.generateCDT();
LogBuffer.println("Setting file path.");
filePath = cdtGen.getFilePath(); // stops inside here, jumps to done()
LogBuffer.println("Path: " + filePath);
}
return null;
}
#Override
protected void done() {
if (!isCancelled()) {
view.setLoadText("Done!");
LogBuffer.println("Done saving. Opening file now.");
// need filePath here to load and then display generated file
visualizeData(filePath);
} else {
view.setReorderOngoing(false);
LogBuffer.println("Reordering has been cancelled.");
}
}
}
When I run the program from Eclipse, this all works perfectly fine. No issues whatsoever. Now I know there have been tons of question on here that are about Eclipse running fine while the runnable JAR fails. It's often due to not including dependencies or referring to them in the wrong way. But what's weird is that the JAR also works completely fine when it's being started from command line (Windows 8.1):
java -jar reorder.jar
Et voilà, everything as expected. The CDTGenerator will finish, write all the matrix rows to a file, and return the filePath. With the filePath I can subsequently open the new file and display the matrix.
In the case of double-clicking the JAR on my desktop, where I placed it when creating it from Eclipse, this is where the program will let me know that stuff happens. I get the error message I created for the case of filePath == null and using some logging I closed in on where the CDTGenerator object stops executing its method generateCDT() (Eclipse debugger also won't reproduce the error and do everything as planned).
What the log shows made me think it's an issue with concurrency, but I am actually leaning against that because Eclipse and command line both run the code fine. The log just tells me that the code suddenly stops executing during a loop which transforms double values from a matrix row (double[]) to Strings to be stored in a String[] for later writing with BufferedWriter.
If I use more logging in that loop, the loop will stop at a different iterator (???).
Furthermore, the code does work for small matrices (130x130) but not for larger ones (1500x3500) but I haven't tested where the limit is. This makes it seem almost time dependent, or memory.
I also used jVisualVM to look at potential memory issues, but even for the larger matrices I am on ~250MB which is nowhere near problematic regarding potential OutOfMemoryExceptions.
And finally, the last potential factor I can think of: Generating the JAR 'fails' due to some classpath issues (clean & rebuild have no effect...) but this has never been an issue before as I have run the code many many times using the 'broken' JAR and execute from Desktop.
I am a real newbie to programming, so please point in some direction if possible. I have tried to find logged exceptions, logged the values of variables, I am checking for null and IndexOutOfBound issues at the array where it stops executing... I am at a complete loss especially because this runs fine from command line.
It looks like the problem had to see with the java versions installed in OP's computer. They checked the file extensions and the programs associated to each one in order to see if it was the same java version as executed from Eclipse and the command line.
Once they cleaned older java versions the jar started to work by double-clicking it :)
Cause I do not have enough points (need 50 to directly answer your question), I need to ask this way:
If you double click a JAR you won't see a console which is often the problem because you can't see stack traces. They get just written to "nowhere". Maybe you get an NPE ore something else.
Try to attach an Exceptionhandler like this Thread.setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler) and let this handler write down a message to a file or such...
Just an idea.

Categories

Resources