I am trying to display an arraylist in a gui. However I am getting some troubles. I need to check if my game is legal, if it is not legal then it calls getProblems which displays the arraylist. I tried to call getProblems directly in the GUI class however it will show the array as empty. (Since it's not checking if it's legal). I also tried to call isLegal then getProblems but you cannot do this in a JOptionPane. Any tips on how I can call it accross?
GetProblems class
protected List < String > getProblems() {
return displayOutput;
}
IsLegal Class
public boolean isLegal() {
boolean legality;
if (checkRowConstraints().isEmpty()) {
legality = true;
} else {
getProblems();
legality = false;
}
return legalCheck;
}
GUI:
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
puzzle.getProblems(),
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);
Here is difference between Actual display of GUI result and result i'm trying to get.
Further Problem found:
I need to return the arraylist then empty it. Fixed
Presently, there is an implicit call to the List's toString() method when you call puzzle.getProblems() within the JOptionPane. So rather than get the contents of the List, which is what you want, you're getting whatever toString() is giving you.
You're not going to get the contents of the List unless you iterate over it first.
You could try something like this. (Note, this is untested code. For demo purposes.)
String formattedString = "";
//let's iterate over our List and build a formatted string for output
for(String element : puzzle.getProblems())
{
formattedString += element;
}
Then you can output this formatted String
public void actionPerformed(ActionEvent e) {
if (!(puzzle.isLegal())) {
JOptionPane.showMessageDialog(FutoshikiFrame.this,
formattedString,
"You made a mistake!",
JOptionPane.INFORMATION_MESSAGE);
Related
I have a method (shown below) which works fine. The purpose of this method is to confirm if a specific item is available in a shop, with a return value of true or false.
I have a second method, which returns a description, but I can't see to work out how to get this method to pull through the first method response with 'true' showing as 'Yes' or 'false' showing as 'No'. I'm assuming it is something to do with method calling and string concatenation.
My overall problem pulls through 2 methods, but I wanted to just try and understand how to pull one method first and then I'll hopefully work out the rest!
Method 1
public void isFree()
{
if (sweet.isEmpty()){
System.out.println("True");
}
else {
System.out.println("False");
}
}`
Method 2
public void information()
{
System.out.println (isFree+ " this item is available for purchase.");
}
Return type of your first method is void so you are not returning anything, you are just printing Yes or False in new line. To concatanate "True" or "False" to another String you need to return String from isFree method
You may try something like this
public String isFree(){
return sweet.isEmpty() ? "True" : "False";
}`
public void information(){
System.out.println (isFree() + " this item is available for purchase.");
}
In second method message doesnt make much sense with False but this is up to you to adjust it
You can also reutrn boolean directly
public boolean isFree() {
return sweet.isEmpty();
}
Keep in mind that in this case it will be revolved to "true" or "false" and not "True"/"False"
Of course if "true"/"false" is ok in your case you can remove isFree method completly and just use sweet.isEmpty() directly in information
Is there any specific reason to use two methods, rather isEmpty in the collection will return the boolean (true, false) for you and you can directly use the second method removing the first completely.
public void information() {
String customText=", this item is available for purchase.";
System.out.println (sweet.isEmpty() ? "YES"+customText : "NO"+customText);}
You can achieve this from several ways:
Call first isFree from information, and then print the second string. For this, you would have to edit both methods, since you are using println.
public void isFree() {
sweet.isEmpty() ? System.out.printf("True") : System.out.printf("False");
}
public void information() {
isFree();
System.out.printf(" this item is available for purchase.\n");
}
Make isFree return a String.
public String isFree() {
sweet.isEmpty() ? "True" : "False";
}
public void information() {
System.out.println(isFree() + " this item is available for purchase.");
}
How would I print and specific instance of an object using a toString?
So basically the user is inputing information. based on the input it will either saved in instance A or Instance B. Both instance A and B are subclasses with overriding toString methods. so the input from the user is saved in an array. How can I make it so that all the inputs that was an instance of A will print?
This is the code I currently have and it is not working.
public static void printA(ABC[] inputs)
{
for(int i = 0; i < inputs.length; i++)
{
if(inputs[i] instanceof A)
{
JOptionPane.showMessageDialog(null, inputs.toString());
}
}
}
you just need is
JOptionPane.showMessageDialog(null, inputs[i].toString());
cuz you are trying to show the array.toString() not the value you want to.
You are iterating inputs, but testing clients. This is why I prefer to use a for-each loop and I suggest you use a StringBuilder to build a single message and then display it once. Something like,
public static void printA(ABC[] inputs) {
StringBuilder sb = new StringBuilder();
for (ABC input : inputs) {
if (input instanceof A) {
sb.append(input).append(System.lineSeparator());
}
}
JOptionPane.showMessageDialog(null, sb.toString().trim());
}
Edit
The output you're getting ("LClient;#20d9896e") is because you are displaying inputs.toString(). Array doesn't override toString(), you can use Arrays.toString(Object[]) like
String msg = Arrays.toString(inputs);
But you'll get all of the items in the array. Also, make sure Client overrides toString().
I have recently started experimenting with the return statement, and I have a small doubt relating to it- When I have a method which calls another method, will the return statement of that method which I am calling be displayed?
Let be give an example to make it clearer-
/** Program to test return statment */
public class Test
{
public static void main(int a)
{
EvenOrOdd(a);
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display(As in that window does not pop up with the result.)
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
If I were to simply remove the main method(or even make the second method public and run that directly), my return statement is displayed however if I attempt to call the method and run the program my return statement isn't displayed.
So is this just a problem I am facing or is it a general rule in Java that the return statement doesn't work when you call another method(which has a return statement)?
If it is the latter, then I apologise, I was not aware of this.
Thanks...
***UPDATE***
It seems that nobody has understood what I exactly mean. I will give another example-
Please run this program-:
/** Program to test Return statment;simple program to return sum of two digits */
public class Return_Test
{
public static int main(int a,int b)
{
return a+b;//What I am lloking for is that box in which this is displayed.
}
}
A return statement only returns the value ,does not Display it
If you don’t catch the return value , how can it be displayed? add something like this and try
,
public class Test
{
public static void main(int a)
{
boolean temp=EvenOrOdd(a);
if(temp)
System.out.println("Output is True");
else
System.out.println("Output False(not even )");
//Or you can directly call the method as' System.out.println(EvenOrOdd));'
}
private static boolean EvenOrOdd(int a)
{//I can declare as public and run directly but then what is the point in calling the method?
if(a%2==0)
{
System.out.println("The output is true.");//Displays
return true;//Does not display
}
else
{
System.out.println("The output is false.");//Displays
return false;//Does not display
}
}
}
And Please try learning some good Naming Conventions , Classes are Named like this ,
FirstSecond,TestException(Each Word Starts with a Capital Letter) etc , methods start with a small letter , isPrime() , isEven(),
What a lot of other responders don't know is that when you run a method in BlueJ, it executes the method, and if the the return value of the method is non-void, it is shown in a popup dialog by invoking toString. That's what the questioner means by the value being displayed.
The answer to the user's original question is that by surrounding the method with a void return, it "hides" the result. So this code:
public void callMe1(int a)
{
EvenOrOdd(a);
}
will not display the return. But if you adjust the return type and actually return the value of the inner call:
public int callMe2(int a)
{
return EvenOrOdd(a);
}
Then BlueJ will display the returned value. The display aspect is down to BlueJ, but the rules for whether or not the value gets returned are the same as in Java; void means no return.
Within the body of the method, you use the return statement to return the value. It will not print anything on its own.
Changes done - System.out.println(EvenOrOdd(5));
public class Test {
public static void main(String[] args) {
System.out.println(EvenOrOdd(5));
}
private static boolean EvenOrOdd(int a) {// I can declare as public and run directly but then what is the point in
// calling the method?
if (a % 2 == 0) {
System.out.println("The output is true.");// Displays
return true;// Does not display
} else {
System.out.println("The output is false.");// Displays
return false;// Does not display
}
}
}
Output
The output is false.
false
You never actually display the return result from the method...
The name of the method is consuming EvenOrOdd returning true or false is ambigious, may isEven would be better...
You could try something like...
System.out.println(a + " is even = " + EvenOrOdd(a));
You should also avoid using multiple return statements within a single method, it can quickly become confusing as to how the method actually works, in your case, you can reduce the over complexity at the same time, for example...
private static boolean isEven(int a)
{
boolean isEven = false;
if(a%2==0)
{
System.out.println("The output is true.");//Displays
isEven = true;//Does not display
}
return isEven;
}
first change your main signature from main(int a) to main(String [] args) otherwise you will get following runtime exception :
Error: Main method not found in class yourpackagename.Test, please define the main method as:
public static void main(String[] args)
well you didn't print the value return from function :
in your main do this:
System.out.println(EvenOrOdd(5));
I have Arraylist of objects ArrayList<Product> productDatabase. The object contains a String and a double and then these objects will be added to the productDatabase by addProductToDatabase(); as follows:
public void addProductToDatabase(String productName, double dimensions); {
Product newProduct = new Product(ProductName, dimensions);
productDatabase.add(newProduct);
}
I also want to make an Arraylist<ProductCount> productInventory which counts how many Product are accounted for. Before it can add to ArrayList<ProductCount> productInventory however, it should first check if the object details exist in the productDatabase while running addProductToInventory()
public Product getProduct(String name) {
for(i = 0; i < productDatabase.size(); i++)
if(productDatabase.get(i).contains(name) //Error: cannot find symbol- method contains.(java.lang.String)
return productDatabase.get(i)
}
public void addProductToInventory(String productName, double quantity)
{
Product p = getProduct(name);
productCount.add(new ProductCount(o, quantity));
}
Assume that you always have different objects (so nothing will have the same name), but you're always unsure of the dimensions (so when you input the same producttName + dimensions you edit the dimensions in it).
At the end of the day, you have to put all the items in it a large box and report what you've inventoried, so you also have a getProductQuantityTotal() and you have to getProductDimensionTotal()-- as the name suggests, get the total of number of objects you've counted, and the sum of the dimensions.
What do I have to add/change/remove about this code? Don't consider syntax first (because BlueJ checks for common syntax errors and I just typed this by hand). I'm sure that I'm missing a for statement somewhere, and I'm probably misusing contains() because it won't recognise it (I have import java.util.*; and import java.util.ArrayList;)
To answer the question in your post title: How to find a string in an object, for a list of those objects, here is some sample code that does this:
First, I created a trivial object that has a string field:
class ObjectWithStringField {
private final String s;
public ObjectWithStringField(String s) {
this.s = s;
}
public String getString() {
return s;
}
}
And then a code that populates a list of it, and then searches each for the string. There's no magic here, it just iterates through the list until a match is found.
import java.util.List;
import java.util.Arrays;
/**
<P>{#code java StringInObjectInList}</P>
**/
public class StringInObjectInList {
public static final void main(String[] ignored) {
ObjectWithStringField[] owStrArr = new ObjectWithStringField[] {
new ObjectWithStringField("abc"),
new ObjectWithStringField("def"),
new ObjectWithStringField("ghi")};
//Yes this is a List instead of an ArrayList, but you can easily
//change this to work with an ArrayList. I'll leave that to you :)
List<ObjectWithStringField> objWStrList = Arrays.asList(owStrArr);
System.out.println("abc? " + doesStringInObjExistInList("abc", objWStrList));
System.out.println("abcd? " + doesStringInObjExistInList("abcd", objWStrList));
}
private static final boolean doesStringInObjExistInList(String str_toFind, List<ObjectWithStringField> owStrList_toSearch) {
for(ObjectWithStringField owStr : owStrList_toSearch) {
if(owStr.getString().equals(str_toFind)) {
return true;
}
}
return false;
}
}
Output:
[C:\java_code\]java StringInObjectInList
abc? true
abcd? false
In the real world, instead of a List, I'd use a Map<String,ObjectWithStringField>, where the key is that field. Then it'd be as simple as themap.containsKey("abc");. But here it is implemented as you require. You'll still have quite a bit of work to do, to get this working as specifically required by your assignment, but it should get you off to a good start. Good luck!
private JTable getTRent() {
if (tRent == null) { ...
tRent.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
tDescription.setText(house.getDescripcionMansion(tRent.getSelectedRow()));
image.setIcon(new ImageIcon(BookWindow.class.getResource(
"/images/" + house.getCodeMansion(tRent.getSelectedRow()) + ".png")));
String childrenAllowed = house.getChildrenAllowed(tRent.getSelectedRow());
if (childrenAllowed == "N"){
txKids.setEditable(false);
cbBookHouse.setEnabled(true);
}
}
});
}
return tRent;
}
The problem that I'm having with the previous code is that any condition, apart from the image, is accomplished, seems to be ignored.
I just checked if the value was read correctly and it is, with a println in console, I get a N or Y depending on the row, but if I check that value, nothing happens with the components I want its state to be changed.
Also tried to put those conditions inside the components and the same happens.
The code of the methods getChildrenAllowed() for example, is like this
public String getChildrenAllowed(int index) {
return houseRelation.get(index).getChildren();
}
Don't compare strings with ==, use equals() or equalsIgnoreCase()
if ("N".equalsIgnoreCase(childrenAllowed))
See How do I compare Strings in Java