I have that following java code:
public class HelloWorld
{
static Baumhaus bauHaus(int hoehe, int breite)
{
Baumhaus b = new Baumhaus();
b.hoehe = hoehe;
b.breite = breite;
return b;
}
static Baumhaus machBreiter(Baumhaus b)
{
Baumhaus bb = new Baumhaus();
bb.hoehe = b.hoehe;
bb.breite = b.breite + 1;
return bb;
}
static Baumhaus machHoeher(Baumhaus b)
{
b.hoehe++;
return b;
}
public static void main(String[] args)
{
Baumhaus b = bauHaus(2, 3);
Baumhaus c = machBreiter(b);
c.nachbar = b;
Baumhaus d = machHoeher(b);
d.nachbar = b;
++c.hoehe;
Baumhaus e = machHoeher(b);
e.nachbar = c;
e.breite = b.breite - 1; // WHY DOES b.breite GETS DECREASED BY 1 ???
c.hoehe++;
c.breite -= 2;
boolean bUndCBenachbart = (b.nachbar == c || c.nachbar == b);
}
}
class Baumhaus
{
public int hoehe;
public int breite;
public Baumhaus nachbar;
public int nummer = ++naechsteNummer;
static int naechsteNummer = 0;
}
See the commented line ( e.breite = b.breite - 1; )
I can't understand, why the value of the variable b.breite gets changed. I'm reading a documentation about Object Oriented Programming (Java) but I am still scratching my head. Please help me
Note: I don't know how to describe my problem to google, so I couldn't find any solutions about my question. I'm sorry if duplicate
Thanks in advance :)
Because e == b.
e is defined as Baumhaus e = machHoeher(b); and
static Baumhaus machHoeher(Baumhaus b)
{
b.hoehe++;
return b;
}
in java assigning object will not create distinct copies of them.
the method :
static Baumhaus machHoeher(Baumhaus b) {
b.hoehe++;
return b;
}
returns the the same object it recives as a parameter,
so in the code line
Baumhaus e = machHoeher(b);
e object is a reference of b, decreasing e will also decrease b
The issue is that you are returning the same object in the machHoeher function. the function is returning the same object that was passed in. So you have two variables (e and b) pointing to the same object in memory.
In machBreiter, you are creating a new object, incrementing the breite, then returning the new object.
You should do the same in machHoeher:
Create New object
Inrement the hoehe
return the new object.
This will make sure that when you do e.breite = b.breite - 1, e and b are separate objects and b.breite doesn't get changed.
Related
So my issue is that I cannot use my global variables (a,b,c) in my arguments. I need to be able to use them in my boolean function and double function. What am I doing wrong? How can I fix this?
public class triareamain extends javax.swing.JFrame {
double a, b, c;
public void DisplayError() {
side1input.setText("Error");
side2input.setText("Type");
side3input.setText("+ Integers");
}
public double areaCal(double a, double b, double c) {
double s = (a + b + c) / 2;
double area = Math.sqrt(s * (s - a) * (s - b) * (s - c));
return area;
}
public static boolean isValid(double a, double b, double c) {
if (a > b + c || b > a + c || c > a + b) {
return true;
} else {
return false;
}
}
private void calculatebuttonActionPerformed(java.awt.event.ActionEvent evt) {
try {
a = Double.valueOf(side1input.getText());
b = Double.valueOf(side2input.getText());
c = Double.valueOf(side3input.getText());
boolean area = isValid();
if (area == false) {
double finalarea = areaCal();
} else {
DisplayError();
}
} catch (NumberFormatException e) {
side1input.setText("Error");
side2input.setText("Type");
side3input.setText("+ Integers");
}
a, b, and c are not global variables. Java doesn't have that concept. They are fields of class triareamain.
However you also created parameters of the same name, so those names are shadowing the fields.
If you wanted the areaCal() method to use the fields directly, remove the parameters:
public double areaCal() {
If you want the method to use the parameters, then pass values in the call:
double finalarea = areaCal(a, b, c);
If you keep the parameters, I highly recommend that you rename either the fields or the parameters. Shadowing of variable names is very confusing to the programmer, and will in high probability be the cause of bugs.
I have methods in a class
public class ReflectionClass {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
public String concatenate (String a, String b, String c){
return a + b + c;
}
}
I'm trying to call these methods through reflection. All I have in hand are - the method name and the parameters. Is there a way to pass the parameters into the Method.Invoke() method dynamically based on the number/type of parameters I have in hand?
As you can see in the docs public Object invoke(Object obj, Object... args) takes a varargs argument - so you can simply pass an array of arguments there.
You need to create an instance, get the methods, get the parameters, check the parameters by checking the type and how many... then call invoke depending of what
Example:
public static void main(String[] args) throws Exception {
Class<?> cls = Class.forName("com.ReflectionClass");
Object obj = cls.newInstance();
for (Method m : cls.getDeclaredMethods()) {
if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(String.class)) {
String a = "A";
String b = "B";
String c = "C";
Object returnVal = m.invoke(obj, a, b, c);
System.out.println((String) returnVal);
} else if (m.getParameterCount() == 2 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
int a = 5;
int b = 3;
Object returnVal = m.invoke(obj, a, b);
System.out.println(returnVal);
} else if (m.getParameterCount() == 3 && Arrays.asList(m.getParameterTypes()).contains(int.class)) {
int a = 5;
int b = 3;
int c = 3;
Object returnVal = m.invoke(obj, a, b, c);
System.out.println(returnVal);
}
}
}
I was trying to make a program that searches for a random number, but i had problems importing the "a" variable in the other method. I would be happy if i could get some explanation. I have already tried to make the variable static, but that doesn't work
import java.util.Random;
public class verschlüsselung {
private static void nummber(int a) {
Random r = new Random();
a = r.nextInt(999);
System.out.println(a);
}
private static void search(int b) {
b = 0;
if(b =! a) {
for(b = 1; b =! a ; b++) {
if(b == a) {
System.out.println("found the number " + b);
}
}
}
}
public static void main(String args[]){
nummber(0);
search(0);
}
}
There is no such thing as using local variables in other methods.
You can return the variable from one method. Than call this method from other and get there the variable.
Declare the variable 'a' to be static and remove the parameter 'a' passed in the nummber()
function. This function does not need any input as it assigns the value of a random number to the global static variable 'a' which is accessed in the method search().
your declaration and method signature should read :
private static int a;
private static void nummber(){....}
May this help you:
private static int nummber( int a){
Random r = new Random();
a =r.nextInt(999);
System.out.println(a);
return a;
}
private static void search(int b, int a){
b = 0;
if(b =! a){
for(b =1; b =! a ; b++){
if(b == a){
System.out.println("found the number " + b);
}
}
}
}
public static void main(String args[]){
int a = nummber(0);
search(0, a);
}
I have been given a piece of code (the class QuestionTwo).
I am asked to state the values of a, b, and c after method mQ2 is invoked on a newly created object of class Q2.
My main.java file
package openuniversity;
public class Main
{
public static void main(String[] args)
{
QuestionTwo qt = new QuestionTwo();
qt.mQ2();
}
}
My QuestionTwo.java class file:
package openuniversity;
public class QuestionTwo
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
}
a++;
}
}
I arrived at:
a: 1
b: 1
c: 3
Note I can also select 'undefined' as an answer?
So would it be 1, 1, undefined as c does not exist outside of the codeblock?
The question:
Study the following code and then select the options from the drop-down lists below that are correct about the values of a, b and c after the method mQ2 is invoked once on a newly created object of class Q2. Note that the answers you choose for a, b and c may or may not be different from each other.
public class Q2
{
int a;
int b = 1;
public void mQ2()
{
{
int c;
int a = 2;
c = a;
}
{
int c;
int a;
c = 3;
a = 4;
System.out.println("c: " + c); //correct place?
}
a++;
}
System.out.println("a: " + a + "b: " + b); // correct place?
}
Since this is homework, I'll restrict my answer to a couple of pointers.
You can verify your solution by printing out the variables after calling mQ2() (hint: you could use System.println() for that).
This is either a trick question or is partially ill-defined (hint: think about which a, b and especially c you're being asked about).
I'd suggest you first print out all the values using System.out.println() after calling mQ2, then step through the code in your mind to try to work out why the values are what they are. Remember that any variable declared is only visible within the scope ({...}s for simplicity), but these variables can have the same name as other variables so they might look like the same even if they're not.
I'd like to particularly point out that c does not exist outside that method.
Is it possible to make HashSet work with any Object ?? I tried to make the Object implement
Comparable but it didn't help
import java.util.HashSet;
public class TestHashSet {
public static void main(String[] args) {
class Triple {
int a, b, c;
Triple(int aa, int bb, int cc) {
a = aa;
b = bb;
c = cc;
}
}
HashSet<Triple> H = new HashSet<Triple>();
H.add(new Triple(1, 2, 3));
System.out.println(H.contains(new Triple(1, 2, 3)));//Output is false
}
}
you need to implement equals(Object) and hashCode()
ensure that the hashcodes are equal when the objects are equal
in your example:
class Triple {
int a, b, c;
Triple(int aa, int bb, int cc) {
a = aa;
b = bb;
c = cc;
}
public boolean equals(Object arg){
if(this==arg)return true;
if(arg==null)return false;
if(arg instanceof Triple){
Triple other = (Triple)arg;
return this.a==other.a && this.b==other.b && this.c==other.c;
}
return false;
}
public int hashCode(){
int res=5;
res = res*17 + a;
res = res*17 + b;
res = res*17 + c;
//any other combination is valid as long as it includes only constants, a, b and c
return res;
}
}
For it to work properly you'll need to implement equals() and hashcode() and you'll also need to make sure they're implemented properly, following the contract set out in the Javadoc (it's perfectly possible to implement them not following this contract but you'll get bizarre results with potentially hard to track down bugs!)
See here for a description.
It already does work with any object. I suggest you need to read the Javadoc instead of guessing about the requirements.