I want to create a method, moveQ(), that I will be able to call in method find() in order to change find()'s variables, but in method moveQ() I am getting the error cannot find symbol variable x in this example x, y, and z are the variables I need to change.
edited:
I also have a few restrictions as this is taken from an exercise from Java course:
1. method must be static.
2. global variables are not allowed.
3. time complexity should be less than O(n), I cannot add to memory complexity (meaning can not use another array or objects).
4. the method find() can not accept parameters.
In the actual program, I need to write a static boolean method that will return true if number x is found in an array that is divided into quadrants. To do that, it searches for each quadrant's highest number. If x is larger than the quadrant highest number, then I need to move to the next quadrant.
x, y, and z are the maximum number, middle number and the minimum number of the quadrant of the array and by changing them, I can move quadrants.
I've already written the find() method, but I want to use helper methods to make the code better.
Is what I am trying to do even possible, and if so how do I accomplish it?
public class Test
{
public static boolean find()
{
int x = 10;
int y = 20;
int z = 30;
change(x,y,z); // call helper method to change this method's variables.
System.out.println(x); // should be 20
System.out.println(y); // should be 22
System.out.println(z); // should be 15
}
//helper method to be called from find() method
private static void change(int changeX ,int changeY,int changeZ)
{
//change find() variables.
x = changeX * 2;
y = changeY + 2;
z = changeZ /2;
}
}
The problem comes from your second method. You pass changeX, changeY, and changeZ but try to set the values of x, y, and z. The variables x, y, and z are not within the scope of this method and therefore the program will throw an error.
Moreover, this methodology will not work regardless of these names. Java does not allow you to change the values of primitives when you pass them to a new method. The best solution is probably to put them in an array and change the second method to accept an array. The body of your first method may now look like
int [] intarray = new int[3];
intarray[0] = 10;
intarray[1] = 20;
intarray[2] = 30;
change(intarray);
System.out.println(intarray[0]);
System.out.println(intarray[1]);
System.out.println(intarray[2]);
and the second method would become
private static void change(int [] changeArray) {
changeArray[0] *= 2;
changeArray[1] += 2;
changeArray[2] /= 2;
}
(The *=, +=, and /= operators are shorthand for what you were doing above.
You declared variables inside of method so you don't have access to them, if you want to change them you either make them global(define them outside of method):
public class Test
{
int x;
int y;
int z;
void yourMethod(){
}
}
Or change method find to take x, y and z values as parameters.
You could write a class encapsulating your x, y, z as fields and convert your methods to its instance methods (that is, they should not be static anymore).
public class Calculation {
private int x = 10, y = 20, z = 30;
public boolean find()
{
x = 10;
y = 20;
z = 30;
change(x,y,z); // call helper method to change this method's variables.
System.out.println(x); // should be 20
System.out.println(y); // should be 22
System.out.println(z); // should be 15
}
private void change(int changeX ,int changeY,int changeZ)
and so on.
Then create an instance of it and call your methods on it:
Calculation calculation = new Calculation();
calculation.find();
...
You can achieve that in more organized way :
Create Calculation class then put all your variables and methods on it
File Calculation.java:
public class Calculation {
private int x = 10;
private int y = 20;
private int z = 30;
public void setX(int value){
x = value;
}
public void setY(int value){
y = value;
}
public void setZ(int value){
z = value;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getZ(){
return z;
}
private void change(int changeX, int changeY, int changeZ){
setX(changeX * 2);
setY(changeY + 2);
setZ(changeZ / 2);
}
public void find(){
change(x,y,z);
System.out.println(getX());
System.out.println(getY());
System.out.println(getZ());
}
}
After that just create new object of class Calculation in your main program and call find() method on this object variable
File Main.java:
public class Main {
public static void main(String[] args) {
Calculation c = new Calculation();
c.find();
}
}
Output:
20
22
15
Related
I have this method in one of my classes:
public int[] getCurrentGridPosition()
{
return new int[]{currentGridPosX, currentGridPosY};
}
Does Java allow something in the likes of:
int x, y;
x = getCurrentGridPosition()[0];
y = getCurrentGridPosition()[1];
If yes, how? If no, why?
Does Java allow something in the likes of:
Yes, there is nothing†wrong with this piece of code. Here a full program with your code to prove it works:
class Main{
private int currentGridPosX = 5,
currentGridPosY = 10;
public static void main(String[] a){
Main m = new Main();
m.test();
}
private void test(){
int x, y;
x = getCurrentGridPosition()[0];
y = getCurrentGridPosition()[1];
System.out.print("x: "+x+"; y: "+y);
}
public int[] getCurrentGridPosition()
{
return new int[]{currentGridPosX, currentGridPosY};
}
}
Try it online.
†: Compile/runtime wise there is nothing wrong. In terms of best practice there are of course things to improve.
If yes, how?
x = getCurrentGridPosition()[0]; will call the method and give an array as result, and will then get the element at index 0, saving it in the field x.
y = getCurrentGridPosition()[1]; will call the method again for a second time and give an array as result, and will then get the element at index 1, saving it in the field y.
So in almost all cases it's best to only call the method once and save the result-array in a variable, and only then access its elements at the indices 0 and 1:
int[] gridPositions = getCurrentGridPosition(); // The method is only called once now
int x = gridPositions[0],
y = gridPositions[1];
System.out.print("x: "+x+"; y: "+y);
Why don't you do it with some more lines of code?
For example, you can access the returned array like this:
int x, y;
int[] myArray = getCurrentGridPosition();
x = myArray[0];
y = myArray[1];
System.out.println("x: " + String.valueOf(x) + ", y: " + String.valueOf(y));
I'm trying to create a java method that returns the sum of two values x and y. Currently when I run the code, the output isn't returning anything. Is there any way I can get the value to return the sum WITHOUT modifying the "getSum(x,y);" in line 6 while using the return method???
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
getSum(x,y);
}
public static int getSum(int x, int y){
int sum = x+y;
return (sum);
}
}
Thank you all in advance!!! I'm still in the beginning stage of coding so I appreciate all the help.
Sorry I thought that you are not allowed to modify getSum method. Just add System.out.println(sum); to getSum method.
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y){
//no need to create temprory varibale
return x+y;
}
}
Just print it inside the getSum method, before returning:
public static int getSum(int x, int y){
int sum = x+y;
System.out.println(sum);
return sum;
}
As mentioned by #Stultuske in the comments. if you want to only print the sum, and never get it. Then just remove the return type and aswell name the method differently for clarification:
public static void printSum(int x, int y){
System.out.println(x + y);
}
You might even want to introduce a whole new method. Leaving the old getSum all on itself. The new method then delegates and just prints the result returned:
public static void printSum(int x, int y){
System.out.println(getSum(x, y));
}
Actually, you are compiling a program without any output. You have to use something like
System.out.println(getSum(x, y));
Otherwise you wont get any output.
If you modify the main-method like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println(sum);
}
you will get the output: 52.
In this case you will save the returned Integer in sum and will print a new line to your console.
If you want to add some words, you can modify the main like:
public static void main(String[] args)
{
int x = 7, y = 45;
int sum = getSum(x,y);
System.out.println("The result is" + sum);
}
You should store your result in a variable or display a result.
int c = getSum(x,y);
or
System.out.println("The result of the two numbers are " +getSum(x,y);
Try This:
public class ZawMethods2
{
public static void main(String[] args)
{
int x = 7, y = 45;
System.out.print(getSum(x,y));
}
public static int getSum(int x, int y)
{
int sum = x+y;
return (sum);
}
}
This code will resolve your problem very easily.
I am new to java and just learned a little bit about methods and classes, and I am really confused about this whole chapter. This code comes from our review powerpoint and I really don't know how to do it. And I feel like the last section should be in the class? But this is how the powerpoint says. Can someone please explain how does this code work and how to get the printout result specifically step by step?? I really appreciate it, thanks!
public class MyClass {
public void swap(int x, int y){
int temp = x;
x = y;
y = temp;
}
}
int w = 10,
z = 20;
MyClass m = new MyClass();
m.swap(w,z);
System.out.println(w + " " + z);
In order to execute Java you need a main method somewhere.
public static void main(String[] args) {
// Do stuff
}
So you can rewrite the example like so to get it executing:
public class Main {
public static void main(String[] args) {
int w = 10,
z = 20;
MyClass m = new MyClass();
m.swap(w,z);
System.out.println(w + " " + z);
}
}
public class MyClass {
public void swap(int x, int y) {
int temp = x;
x = y;
y = temp;
}
}
The whole point of this code example is that Java passes primitive types by value and not by reference. Look at the main method. You have two integers, w=10 and z=20. After that you pass w and z to the swap method. Since java passes these primitive types as values, the original w and z are not modified by the swap, which is proven by the println where w is still 10 and z is still 20.
In the following code I have declared 2 user defined constructors, one without parameters and the other one with 3 parameters, in both the constructors I am assigning values to the instance variables and when the main method is executed the output for constructor without parameters is 2 and the o/p for constructor with 3 parameters is 0 in the first way, but when I try the second way the o/p for zero parameters constructor is 2 and for the 3 parameters constructor is 15, where I am passing the arguments while object creation, now I don't understand why in the first way the output is zero.
public class Main {
int x, y, z;
Main() {
x = 2;
y = 2;
z = 2;
}
// first way
Main(int x, int y , int z) {
x = 20;
y = 20;
z = 10;
}
// second way
Main(int x, int y , int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int sub() {
int m;
m = x + y - z;
System.out.println("the value is " + m);
return m;
}
}
Following is the main method:
package demo;
public class Maintest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Main s = new Main();
int s1 = s.sub();
Main s3 = new Main(10,10,5);
int s2 = s3.sub();
System.out.println(s1);
System.out.println(s2);
}
}
When you use x=20 you are assigning a new value to the parameter x passed to the constructor, not assigning that value to instance member. When you write this.x, it clearly binds to the instance member.
If you still confusing about them, change the parameter names to some other and check.
this refers to current object reference on which the method is called. So using this before the variable refers to current object instance variable.
If you dont use this then they are pointing to the variable passed in the argument.
However if you changed function parameter name and then use only x it will refer to current object instance variable.
If instance variable name is similar to argument name, at that time use 'this' explicitly to solve the ambiguity issue for JVM.
Main(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
This is the standard practice.
But if you change argument name then its not mandatory to use 'this'.
Main(int xx, int yy, int zz) {
x = 20;
y = 20;
z = 10;
}
Here it refers to instance variables and will give you proper results.
Cheers!!!
I saw your code. When you use the constructor in //first way
you get the answer as 0 because the values 20, 20, 10 that you are initialising to variable x,y,z respectively gets initialised to constructor variable x,y,z not to the class variable x,y,z.
When you use constructor //second way
values get initialized to the class variables x,y,z because of the use of "this" keyword. this refers to the class variable hence when you use in second way constructors shows the result as 15.
I'm trying to prompt the user to enter 3 numbers. After those numbers are entered, I am to add the highest two numbers. The main method is to handle all print statements and is to call the other method. I'm not allowed to use for loop for this problem. The variables from the main, should be passed down to the other method.
I am not sure why I am unable to call the method from the main. Here is my code:
public class HW {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter three numbers.");
int x = console.nextInt();
int y = console.nextInt();
int z = console.nextInt();
HW.calLargestSum(); //ERROR
HW.calLargestSum(int x, int y, int z); //STILL ERROR
}
public int calLargestSum(int x, int y, int z){
if ( x > y && x > z && y > z )
return x + y;
else if ( y > x && y > z && x > z )
return y + x;
else if ( z > x && z > y && y > x )
return z + y;
return 0;
}
}
You can't call it because you have not instantiated an HW object. Two solutions:
HW hw = new HW();
hw.calLargestSum();
Or make the method static, so that you don't need to instantiate it:
public static int calLargetSum();
Further... ok, so many problems...
HW.calLargestSum(); //ERROR
There is no method calLargestSum(), there is only calLargestSum(int x, int y, int z).
HW.calLargestSum(int x, int y, int z); //STILL ERROR
You need to pass values here. int x is not a value. You need to pass values like:
HW.calLargestSum(1, 2, 3);
Problem
You are making some mistakes when calling the method from main. The non-trivial mistake is that you can't call non-static from static. This happens because if it is not static then it is an instance method. Thus, it requires an instance to access it.
Static Solution
Make your method static. So change your method to:
public static int calLargestSum(int x, int y, int z)
{ ... }
To call the method, you can use:
calLargestSum(1,2,3);
// or in your case.
calLargestSum(x,y,z);
Instance Solution
The other option is to make a new instance of your class (if you don't want it to use static). Like so:
HW hwObj = new HW();
To call use this:
hwObj.calLargestSum(1,2,3);
To See Returned Value/Print
int largest = calLargestSum(x, y, z);
System.out.println(largest);