Why do I get this compile error in Java? - java

In java why is the following code not allowed by the compiler?
public class Test {
public static void main(String[] args) {
int x;
int x = 4;// the error is generated here
}
}

Because the second
int x = 4;
Is attempting to create a variable names "x" of type int, but this variable already exists ( created in the previous line )
Probably you would like to do:
int x;
x = 4;
( not using int in the second line )
That assigns the value 4 to x.
Or even better:
int x = 4;
That creates the variable x of type int and assign the value of 4.

You have declared two int variables; both named x. This is not allowed.
Try:
public static void main(String[] args) {
int x;
x = 4;
}

Related

Java has (apparently) contradictory scoping

For this code sample the Java compiler is not happy:
public class Test1 {
public static void main(String args[]) {
int x = 99;
{
int x = 10;
System.out.println(x);
}
System.out.println(x);
}
}
The compiler says:
error: variable x is already defined in method main(String[])
However, the Java compiler is completely satisfied with this:
public class Test1 {
public static void main(String args[]) {
{
int x = 10;
System.out.println(x);
}
int x = 99;
System.out.println(x);
}
}
And that is a little piece of insanity in Java. When I look up Java scoping rules, I'm almost always seeing writers describe that variables are scoped within the block level they're in, except for instances of object level variables which retain their values for the instance lifetime.
None of them explain the rules in a way that explains the way the Java compiler deals with the code samples here. But as we can see from these two obvious examples, the scoping rules don't really work the way everyone is describing them.
Will someone explain this correctly, please, so that I am understanding it properly?
int x = 99;
{
int x = 10; // variable x defined before is still available, so you can not define it again
System.out.println(x);
}
System.out.println(x);
And:
{
int x = 10;
System.out.println(x);
}
int x = 99; // variable x defined before is not available, so you can define it again
System.out.println(x);
I can try to explain, but without knowledge of the exact rules.
In the first example, both x would be known in the inner scope. That's not allowed.
In the second example, in the inner scope, the outer x isn't defined yet. So there is no problem.
public class Test1 {
public static void main(String args[]) {
int x = 99;
{
int x = 10; // not allowed because the fist x is visible/known here
System.out.println(x);
}
System.out.println(x);
}
}
The scope of the first x in the first code is within the main method
so x is visible everywhere within the method , that is why it is not allowing
re-declaring it.
where as in the second code the the scope of the first x is within the block {}
so since out of this block x is not visible or not known, declaring the second x is allowed.
public class Test1 {
public static void main(String args[]) {
{
int x = 10;
System.out.println(x);
// x gets out of scope after this closing block
}
int x = 99; // allowed because the first x got out of scope
System.out.println(x);
}
}
It is not a problem with Java. The scoped variable x has gone out of scope when the second x is declared and used.

Java Return is Returning Blank

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.

changing static variables from another method in java

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

How does this code (parameters (of Primitive Type)) work?

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.

How to create an array with a random amount of values

I need to create an array that has a random amount of values from 8 to 12, but it says my variable is incompatible. What do I have to change? Should x not be an int?
Here is the first part of the code that includes the problem:
public class Fish {
int min = 8;
int max = 12;
int x = min + (int)(Math.random() * ((max-min) + 1));
static Fish[] myFish = new Fish[x];
static int Fcount=0;
private float weight;
public Fish(float w) { weight = w;
myFish[Fcount] = this;
Fcount++;
}
public float getWeight( ) { return weight; } }
The second part of my code is:
public class GoFish {
public static void main(String[] args) {
float[] myWeights;
for (int i = 0 ; i < x ; i++){
int min = 1;
int max = 20;
myWeights[i] = min + (int)(Math.random() * ((max-min) + 1));
}
for ( float w : myWeights ) { new Fish(w); }
for ( Fish f : Fish.myFish ) {
System.out.println( f.getWeight() );
} } }
Could you also explain the problem, because I would like to understand what I'm doing wrong. I also have to make the weight a random number between 1 and 20, but I can't get this type of random numbers to work.
Edit: Since we are making the x variable static, how do I use it in the other file? because I need the array values to be random.
x is an instance variable. You're trying to access (javac compiler would say "reference") instance variable (javac would say "non-static variable") from a static context (javac would say the same thing). This won't compile because during the static Fish[] myFish = new Fish[x]; there is no any Fish instance.
You can change your code to:
static int min = 8;
static int max = 12;
static int x = min + (int)(Math.random() * ((max-min) + 1));
This will make non-static variable x static.
Here's the official explanation of static variables (officials prefer to call them class variables).

Categories

Resources