I'm trying to check for a persons age using another object in another class, for some reason the areThey boolean returns false no matter what. The following code that I implemented is_
public class main {
public static void main(String[] args){
Obj object = new Obj();
object.areTheyOldEnough();
if(object.areTheyOldEnough() == true){
System.out.println("They are old enough!");
}else{
System.out.println("They are not old enough!");
}
}
}
public class Obj {
private int age = 15;
private boolean areThey;
public boolean areTheyOldEnough() {
if (age > 12) {
boolean areThey = true;
}
return areThey;
}
}
Your problem is called shadowing; here:
That most inner declaration of :
if (age > 12) {
boolean areThey = true;
Is simply wrong, that should read:
areThey = true;
instead. The point is: you are declaring a new variable of that name, and give that the value true. But that variable vanishes in thin air when that if-block is "left" ... and what is returned is the value of the field areThey within your obj class. And that one still has its initial default value of false.
And beyond that: naming is a real problem in your code. Use names that A) comply to java coding standards; so class names start UpperCase for example; B) mean something.
In other words: the name Object doesn't mean anything (besides creating yet another name clash with the java.lang.Object class name). Better call it "testInstance" or something like that - as said: use names that mean something.
You have two boolean variables of the same name - one is a local variable, which you are setting in your method (inside the if block), and the other is a an instance variable which you are returning.
You don't need any boolean variable, just write :
public boolean areTheyOldEnough() {
return age > 12;
}
you mixed visibilities of field and local variable
public class obj {
public int age = 15;
public boolean areThey; //initialized to false as default value for boolean
public boolean areTheyOldEnough() {
if (age > 12) {
boolean areThey = true; //create new local variable with the same name as field,
// but visible just in scope of if-block
}
return areThey; // return value from field
}
correct your code as follow :
public class main {
public static void main(String[] args){
obj Object = new obj();
if(obj.areTheyOldEnough()){
System.out.println("They are old enough!");
} else{
System.out.println("They are not old enough!");
}
}
and your obj class will be :
public class obj {
public int age = 15;
// it is not required, but if you need for other methods,
// you can define it
public boolean areThey;
public boolean areTheyOldEnough() {
return age > 12;
// or if you need set variable areThey, so use following codes
/*
areThey = age > 12;
return areThey;
*/
}
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);
}
I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer
I have an enum class with values:
enum carBrand{BMW,HONDA,MERC,AUDI};
And there's an array called Sales with Array values:
sales[] = {CHEVVY, BMW , MERC, AUDI};
So how could I check that the sales[] has all the values of enum carBrand?
I'm trying to put it in a for loop as:
for(int i = 0; i<sales.length;i++){
if(carBrand.sales == sales[i]){
return true;
}
return false;
}
Add carBrand values to list
loop sales, remove the carBrand from the list
check if list is empty, if so they have all the values
Note: Class names should be names in PascalCase (CarBrand, Sales)
I would, personally, suggest using a list object rather than an Array where you are using such, however, this should work.
public static boolean checkArray(carBrand[] array) {
for (carBrand c : carBrand.values()) {
boolean found = false;
for (carBrand a : array) {
if (a == c) {
found = true;
break;
}
}
if (!found) {
return false;
}
}
return true;
}
where the "array" parameter would be invoked as the sales object in your code.
This code will return false if not every enum value exists within your array.
Off-topic:
Things like this are actually all over the internet - here, google, even Bing (as garbo as Bing is), so searching before requesting help, probably a viable choice
public class Enumeration {
enum carBrand{BMW,HONDA,MERC,AUDI};
public static void main(String[] args) {
String sales[] = {"CHEVVY", "BMW" , "MERC", "AUDI"};
for(carBrand brand:carBrand.values()) {
boolean bran=false;
for(int i=0;i<sales.length;i++) {
if(brand.toString()==sales[i]) {
bran=true;
break;
}
}
if(!bran==true) {
System.out.println("Sales doesn't have " +brand);
}
}
}
}
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.
if (a != 1 && solone == (int)solone && soltwo == (int)soltwo){
// (lx+o)(mx+p)
int h = (a*c);
List<Integer> factors = new ArrayList<Integer>();
for (int i = 1; i < Math.sqrt(h); i++) {
if (h % i == 0)
factors.add(i);
}
Integer result = null;
for (int ii: factors) {
if (b == ii + h/ii){
result = ii;
// ax^2+hiix+iix+c
}
int hii = h/ii;
int gcd1 = Euclid.getGcd(a, hii);
int gcd2 = Euclid.getGcd(ii, c);
String Factored = FactoredForm.getFF(gcd1, gcd2, a, hii);
}
My String called Factored is one I need to use for printing later in my code. I can't use it because it doesn't recognize the variable outside of the for loop. How do I go about making it public? When i added public in front of the string, it said that only final is permitted? Also, I cannot simply move the extraneous code outside of the for loop because it all depends on the integer "ii" which is part of the loop. Help!
Do you really want this to be part of the state of an instance of the class? If so, declare it outside the method:
private string factored;
public void Whatever(...)
{
factored = FactoredForm.getFF(gcd1, gcd2, a, hii);
}
I would advise you not to make it public. If you need to expose the value, do so via a property.
Think carefully about whether it really is logically part of the state of this class though. Also revisit naming conventions, as mentioned before.
public attribute is not related to a local variable but to an instance variable.
Inside the same function declarations follow two rules:
the order of declaration: if a local variable hasn't been declared yet, then you can't use it.
the scoping: if a variable has been declared inside a scope ({ ... }) then you can't access it from outside the scope.
If you want to access the variable later in the code you should declare it before the loop:
String factored;
if (....) {
....
....
factored = whatever;
}
System.out.println(factored);
or have it as an instance variable (meaningless, since it's a local that you need to print but whatever):
class FooBar
{
String factored;
void method() {
...
...
if (...) {
...
...
factored = whatever;
}
System.out.println(factored);
}
}
or thirdly you can return the variable from the method and use it somewhere else:
class FooBar
{
String method() {
...
...
if (...) {
...
...
return whatever;
}
return null;
}
void otherMethod() {
String factored = method();
System.out.println(factored);
}
}