I have to create an object that uses an "is" method, basically declaring the state of the object. I am not sure how this should work. Right now am writing the method as a boolean but I am wondering if I should use a different approach, here is the code,
public class Cell
{
public int move;
public Cell(int xmove)
{
xmove = 0;
}
public boolean isempty(int x)
{
if(x == 0)
{
return true;
}
else
{
return false;
}
}
}
You are kind of on the right track but there are a bunch of issues.
First, this is much simpler
public boolean isEmpty(){
return move == 0;
}
I assumed that an instance of Cell is empty if its move is 0.
Note that I've camel cased your method name. Also, isEmpty is supposed to say something about the state of an object. It doesn't make sense to pass in x (unless you want to compare x to some property on the object instance).
Second, you constructor takes an argument, then sets it to 0. That's not going to do anything. You probably want
public Cell(int move){
this.move = move;
}
Which takes an argument and sets the field on the current instance that is being constructed to the value passed in (you defined a field move, so you probably want to set it.).
So you could do something like
Cell cell1 = new Cell(1);
Cell cell2 = new Cell(0);
cell1.isEmpty() // false;
cell2.isEmpty() // true;
Related
I have a transient variable that does not exists in the database, it's an interpretation for another variable (integer variable), basically if that int variable equals 2, my transient is True, else it's False. This is my getter and setter:
public Boolean getAceitaPix() {
if(versaoWS.equals(2)){
this.aceitaPix = true;
}else{
this.aceitaPix = false;
}
return aceitaPix;
}
public void setAceitaPix(Boolean aceitaPix) {
if(this.aceitaPix == true){
this.versaoWS = 2;
}else{
this.versaoWS = null;
}
this.aceitaPix = aceitaPix;
}
The issue is, when I try to make the changes at my XHTML, the getter is called again and it changes the boolean no matter what I do at the Form, so when the setter is called the transient variable is always TRUE. How do I proceed? Do I make another Boolean that only changes the setter? I think there's a smarter way of doing this.
Sounds like you don't need a field there. Instead, you could just have a getter that calculates it on the fly:
public boolean getAceitaPix() {
return versaoWS.equals(2);
}
So the original problem is Write the method chechkLeaves(), which should return true if the leaves of the tree are sorted in increasing order and false otherwise. You can assume that data for all internal nodes are null. You will find it useful to define additional recursive helper methods for this problem.
Edit: My code is working now, but how can I modify the code so that I the val is passed in as a parameter rather than global variable?
static int val = 0;
static public boolean checkLeaves(Node root) {
// int val = 0;
if(root.data != 0 ) {
if(root.data > val) {
val = root.data;
return true;
} else {
return false;
}
} else {
return checkLeaves(root.left) && checkLeaves(root.right);
}
}
There isn't really a way for you to be able to do this traversal of the leaves with comparison without a global variable. This is something that can be accomplished with passing-by-reference, but Java doesn't have such a feature. So, you have two options:
Option 1) Stick with this static variable.
Option 2) Make val a parameter as an array, as such:
private static public boolean checkLeaves(Node root, int[] val) {
if (root.data != 0) {
if (root.data > val[0]) {
val[0] = root.data;
return true;
} else {
return false;
}
} else {
return checkLeaves(root.left, val) && checkLeaves(root.right, val);
}
}
And to call it:
checkLeaves(root, new int[] { Integer.MIN_VALUE });
By making it an array, you can emulate that "pass by reference" behavior. That is, updating the original value of the variable by having a reference to the original value. Everything in Java is pass-by-value, so the value of the variable is passed to the parameter, not the reference to it.
Note
I suggest you name your variables a little more descriptive. For example, instead of val, you could name it previousLeafValue or something.
Also, a good practice to follow is making everything as "private" as possible. In option 2 you can see my code have the method with a private access modifier. The same is true for your static variable. Make it a habit to make things private by habit, then expand their modifiers as needed.
I'm working on a basic Java assignment for school. This snippet involves searching for a specific part number in an ArrayList. When I try to compile, the IDE says I have a missing return statement. However, I can't see where it is. Do I need a return statement following the increment of the index? If so, then the return null becomes unreachable. Thank you guys very much.
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
boolean searching = true;
while (index < items.size() && searching){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == (searchPartNumber)){
searching = false;
return inventoryItem;
}
else{
index++;
}
if(searching){
return null;
}
}
}
your code has several problems:
after you compared first item in list and it does not match - you will stop comparing, as searching is true and you will return null
in case of empty list you need to return null too
here is the fixed version:
public InventoryItem findInventoryItem(int searchPartNumber) {
for (InventoryItem inventoryItem : items)
if (inventoryItem.getPartNumber() == searchPartNumber)
return inventoryItem;
return null;
}
The method expected a return value in all cases. This means you have to add a return value in the else-block, too. Or you could add a return value only once at the end of all statements.
you're not handling the case where search will not be true.
That is,
if(searching){
return null;
}
Where is the else part handled here?
No matter what happens in your method, there has to be some value returned (even if it is null).
Right now, if you never get into your while (because that condition isn't fulfilled to begin with -> like when items.size() is 0), your method won't return anything.
In other words: Put a return null; after the closing bracket of your while loop.
Another important note: You do realize that this while will always only look at the first item, right? Because if your first item is not the one you're searching for, your variable searching will still be true, which will then force the method to return null (without looking at any other items)
You are missing a return statement right at the end, after the while loop.
This is needed to handle the case where the while loop guard becomes false, either by items being empty, or searching being set to false.
The compiler has no way of determining whether these will never become false, so you it requires you to return in case they do.
All functions that have a type (aren't void) require that you return something based on the method signature. This means that you must return something in ALL cases. You haven't included the case where searching is not true, and must return something if that is the case.
if(searching){
return null;
} else{
//return something else
}
It is important to note though that in this case the else is implicit, and therefore you don't actually have to provide the else. You could instead just do this:
if(searching){
return null;
}
//return something else
Keep in mind that if searching is true, it will return null and "return something else" will never be called.
Do like this
public InventoryItem findInventoryItem(int searchPartNumber)
{
int index = 0;
//boolean searching = true; comment out this line
InventoryItem inventoryItem = null; //declare null InventoryItem here
while (index < items.size())
{
inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if (fetchedPartNumber == (searchPartNumber))
{
//searching = false; comment out this line
break; //do something to get out from while loop
}
else {
inventoryItem = null;
index++;
}
}
return inventoryItem; //if found then it will have item otherwise null
}
First you need to return if items.size equals zero. Second you need to return if you find nothing. Third I can't see any usefulness of the variable searching.
You could change your searching function a bit. The final form would be something like this:
public InventoryItem findInventoryItem(int searchPartNumber) {
int index = 0;
while (index < items.size()){
InventoryItem inventoryItem = items.get(index);
int fetchedPartNumber = inventoryItem.getPartNumber();
if(fetchedPartNumber == searchPartNumber)
return inventoryItem;
else
index++;
}
return null;
}
The method is not returning the value of the local variable.
Can I use the value of local variable index from the following method
public boolean contains(Object input) {
int index = 0;
while(myAsetIterator.hasNext()) {
index++;
if(input.equals(myAsetIterator.next())) {
return true;
}
}
return false;
}
in this method as the index of the array of the object that I want to remove.
public boolean remove(Object o) {
int count = 0;
if(o == null) {
return false;
}
if(contains(o)) {
genArray[index] == null;
}
if (count > 0) {
System.out.println(count+" same elements were present in Aset. "
+ "Removed all those "+count+" elements from Aset.");
return true;
}
return false;
}
I know the scope of a local variable is limited to the method it's declared in. But there might be a way that I might not now yet to make this happen without using a field/instance variable.
No. The whole point of it being local to a method is that it only exists within that method. The options are:
Use an instance field, i.e. make it part of the state of the object. That's unlikely to be appropriate.
Use a static field, i.e. make it part of the static of the type. That's almost certainly inappropriate.
Change the existing method to return the information you want.
Create a new method to return the information you want.
Duplicate the existing code within remove so that you can get the index. That would be sad :(
As an example of the last two, you could write:
public int indexOf(Object input) {
int index = 0;
while(myAsetIterator.hasNext()) {
index++;
if (input.equals(myAsetIterator.next())) {
return index;
}
}
return -1;
}
public boolean contains(Object input) {
return indexOf(input) == -1;
}
... then in your remove method, you'd use indexOf instead of contains.
So this is a stupid dbeginner's question.
I wrote a function that checks if a specific game move is legal (Reversi). The function must only return a boolean true/false value.
Later, in a different function, I actually make the move (makeMove function). In this function, before making the move I call the isLegal function to make sure the move is legal.
Now, when the isLegal function decides the move is legal, it would help me to save the specific info that lead to the decision, and use it in the makeMove function. I have no ideah ow to do that. I tried writing a function that will store the relevant data, and then send it back, but there's an obvious provlem with scopes here.
So here's the relevant code from isLegal:
else if(board[k][l]==player){relevantDirection=false; isLegal=true; ReversiPlay.saveLegalMove(direction, k, l);}
Then the problematic saving function:
public static int[] saveLegalMove(int direction, int row, int column){
if(direction==0){ //get info from function
return legalMoveData;
}
else{ //save legal move data
int[] legalMoveData = new int[3];
legalMoveData[0]= direction;
legalMoveData[1]= row;
legalMoveData[2]= column;
return null;
}
}
And lastly, I try calling the stored data:
int[] getSavedInfo = ReversiPlay.saveLegalMove(0, 0, 0);
I'm sure there's a very simple way of pulling the variables direction+k+l... anyone?
Thanks!
Edit: Here's a clearer example:
public static boolean A(int a){
...calculations...
int x = [value]
int y = [value]
return false;}
public static void B(int a){
...calculations...
boolean h = A(3);
[here I'd like to know what x,y were]
}
else { //save legal move data
int[] legalMoveData = new int[3];
legalMoveData[0]= direction;
legalMoveData[1]= row;
legalMoveData[2]= column;
return null;
}
This part doesn't save anything. It stores the values to a local variable and returns null.
An approach would be to make a Move object that contains the data you need:
public class Move {
private int direction;
private int row;
private int column;
...
}
Your isLegal method would only tell you if the move is legal. Then you can use that same Move instance to make the move.
if(ReversiPlay.isLegalMove(move)) {
ReversiPlay.makeMove(move);
}
There is no need to explicitly save the move; you already have that information inside the Move object instance.
UPDATE
Based on your edit, perhaps it is better to return an object instead of a boolean from A:
public static boolean A(int a) {
...calculations...
int x = [value]
int y = [value]
return new MyObject(x, y, false);
}
...
MyObject myObject = A(someValue);
Then you can query myObject to see what the value of the flag is.
UPDATE
You mentioned you aren't allowed to use objects. If so, instead of making the same calculations however, you can extract that logic into its own method and then call that. That way you won't have to duplicate logic.