Total Java noob, I need to figure out how to capture string entered as an argument for one method in order to reuse it later.
Basically, here I pass String content as a label when creating buttons:
public void start() {
// set up the label for one button
viewer.setButtonLabel(1, "");
viewer.setButtonLabel(2, "");
viewer.setButtonLabel(3, "");
// start the viewer
viewer.open();
}
Then I want to reuse the string I've given as the button label as the keywords for a search in the next method, taking into account which button was pressed:
public void buttonPressed(int n) {
// fetch an image of the Forum from Flickr
Photo photo = finder.find("", 5);
}
I feel I'm making this much harder than it has to be but I'm totally new to Java and can't seem to find what I'm looking for.
Would really appreciate any tips you may have.
String buttonLabel1 = "Blah blah blah";
viewer.setButtonLabel(1, buttonLabel1);
Next Method
blahMethod(buttonLabel1);
This is one way of doing this, but probably the easiest to see. You can get a bit more complicated by storing all your button labels into a list instead (which will make your code look cleaner), but since you are new, I suggest you try it this way. Eventually, to make your code dynamic (ex. If I select the 4th button, get the 4th label), you will have to use some sort of data structure to avoid from getting extremely sloppy/messy.
You also can probably "get" the label of the button in order to retrieve the same string value.
Related
I am using Java to make an Uno game. I have a method called findCard(String cardname) whose function is to find the card in a hand of cards when the user writes in the name of the card (e.g: “Red 6”) and to return null if it can’t find the card. It works fine when I tried something like:
String card = "Red" + " " + "6";
pHand.findCard(card); // return the card Red 6
However, in the game, I will need the user to write a full command such as “deal Red 6”. Thus, I use StringTokenizer to separate the card’s name from the command:
StringTokenizer scan = new StringTokenizer(input);
String cmd = scan.nextToken(); // = "deal"
String color = scan.nextToken(); // = "Red"
String card = color + " " + scan.nextToken(); // = "Red 6"
What is wrong is when I try pHand.findCard(card); in this scenario, it only returns null no matter what was typed in.
All I know about StringTokenizer is that it can split words in a string so I don't see how these are different. Thus, it would be great if anyone can point out the reason and the solution for this.
The comments already have the solutions really... but to wrap some more advice around it:
Your Problem
You're just missing a space between the color and number.
General Advice
Make sure everything is the same case before comparing (e.g. all lower/upper).
Get rid of white space when handling tokens.
Keep variables separate; card value and card color are both unique and useful, putting them back in one string makes them less useful and harder to use and can introduce errors like yours.
Recommendation
Modify findCard() to take 2 strings, one with the card value and one with the color. Also, if you're using "red 6" as a key in a map or something, either:
Make sure you build "red 6" from "red" and "6" using a function that you use everywhere you do this. That way you can unit test the function and you're sure that you don't add a space in one spot and forget it in another spot. Generally anywhere where you duplicate code, you might mess up - so don't duplicate.
Make "card" a class and override equals and hash code to use both of these values when determining equality. Then you can use card as the key in a map fine.
Also, I kind of agree with the person who said that string spit() would be easier (just because you see it more often in code). But both should work if you're comfortable; so do it your way if you're happy :).
I have two dropdowns that I am trying to utilize after they are selected I want another box to pop up based on the selection to display information. When I try to use an if statement and press the okay button it just continues on to the next line. I started with a showmessagedialog but I want to display a warning in some of the dropdown options. It isn't working. I also need to be able to loop back to the main menu so that they can make a different selection.
example of what I have now:
int x = JOptionPane.showOptionDialog(null, "Zookeepers would you like to view animal activities or monitor habitats?",
"Welcome to the Brooklyn Zoo!", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, icon, options, options[0]);
System.out.println(x);
if(x==0){
String[] choices = {"Lions","Tigers","Bears","Giraffes",};
String input = (String) JOptionPane.showInputDialog(null,"Select Animal:","Zoo Animals",
JOptionPane.QUESTION_MESSAGE,null,choices,choices[1]);
if (choices.equals("Lions"));
String [] button = {"OK","Cancel","Warning"};
JOptionPane.showOptionDialog(null, "\"Animal: Lion\\nName: Leo\\nAge: 5 \\nFeeding Schedule: Twice daily\\n\\nALERT: Cut on left front paw",
"Animal",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE, options, options [0]);
I have two dropdowns
There is no such component. Use the proper name, JComboBox, so we don't have to guess what you are talking about.
I really don't understand your question because you haven't posted a proper MCVE, however, the following is an obvious problem:
String[] choices = {"Lions","Tigers","Bears","Giraffes",};
String input = (String) JOptionPane.showInputDialog(...);
...
if (choices.equals("Lions"));
The variable "choices" is an array. You can't compare an Array to a String.
Maybe you want:
if (input.equals("Lions"));
Also take a close look at the code below:
if (choices.equals("Lions"));
String [] button = {"OK","Cancel","Warning"};
JOptionPane.showOptionDialog(...)
You don't use {} to mark the statements of the if statement. So only the first statement is considered part of the if statement. The JOptionPane... statement will then always be executed.
Always use the following structure when you write code so you don't make mistakes:
if (....)
{
// do something
}
The indentation of the code in the if statement also makes it easier to read.
Lets see the below scenario.
On the registration form, there is field called "Hobbies" which has three check boxes "Reading", "Dance" and "Cricket".
I have to select two check boxes "Reading" and "Cricket". I have to pass one string value (e.g. "Reading,Cricket") to one method say "selectMultipleCheckboxes". So, based on passing value, it should split the string and it should select two check boxes.
Note: I don't want to select single check box or all check boxes.
Could you please help me to write test script?
I'm not really an expert on Java, but since someone just answered my question, I thought I would at least try to help you out.
You would do something like this:
String originalText = "Reading,Cricket";
String[] parts = originalText.split(",");
String readingPart = parts[0];
String cricketPart = parts[1];
Then you would pass those strings to Selenium:
driver.findElement(By.id(cricketPart)).click();
That would of course be assuming your checkbox's DOM ID was called "Cricket"
What I need have happen: Take a list of names from a multiline TextArea, put them into an array, modify them a bit, and then print them out in a list.
What I'm having problems with: Actually getting the input from the TextArea and sticking it in an array -- I have the rest down. I read someone's similar question, but the solution for that question isn't working for me; I keep getting a NullPointerException when I reference it, meaning that there's nothing there, and that the input wasn't put into the array.
The coding: The TextArea is called "taClient" and is all activated by a mouse click on a button called "btnProcess"
private void btnProcessMouseClicked(java.awt.event.MouseEvent evt)
{
String[] names = taClient.getText().split("\\n");
Account[] account = new Account[names.length];
for(int x = 0; x<names.length; x++)
{
account[x].Name = names[x];
}
//All the modifications and other code and printout.
}
As far as I'm aware, this should work, but I don't have much experience with textareas or the String.split() method, so I could just be way off. (Plus, as I said before, this design was based off of someone else's question on here, and they said this answer solved their problem...but not mine.)
Thanks in advance!
Did you try to split the string with just one backslash, likes this: .split("\n").
You are probably on Windows and want to read Split Java String by New Line
Also using Guava's new LineReader(new StringReader(taClient.getText())) can do the trick (http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/LineReader.html)
I have assigment to make notepad using NetBeans Java. I already made the whole thing, I just don't know how to implement find/replace dialog, can you help me with this. I'm using jTextArea.
I will assume that you already know about Swing and how to make the appropriate dialog box (since you apparently have already made the JTextArea for the Notepad equivalent), and that you just want to know how to make it work on the back end.
What I would do is have a Scanner object go through your file to perform the find and replace.
String myAlteredText = "";
Scanner scanner = new Scanner(myText);
while(scanner.hasNext()) {
String next = scanner.next();
if(next.equals(userFindInput)) {
myAlteredText += userReplaceInput;
}
else {
myAlteredText += next;
}
myAlteredText += " ";
}
You can use .equalsIgnoreCase() if case doesn't matter. Likewise, you can tweak to adjust to your user parameters (i.e., if it doesn't have to match the whole word, use .contains() instead). There may be some nit-picky other things you need to do to maintain abnormal spacing and line breaks, but this is the general approach I would use.
You could use a JTable although this is rather unconventional. You could load each word into a new cell. This way when you need to replace 1 word you don't need to update the entire jtextarea for just 1 character unless I am mistaken. This would require a lot of work however in order to get this to work