Forward reference and recursion - java

Why is it possible for a variable to call (initialise itself) a method that calls the same variable (seems a recursion)? I expected to see an endless recursion, but it compiles without errors. Any explanation?
class Forward {
static int test(){
return i;
}
static int i=test();
public static void main(String[] args) {
System.out.println(test()); //sout= 0
System.out.println(i); //sout =0
}
}
Another example. Why does referencing Backwards.j work while referencing j gives an error("illegal forward reference"):
class Backwards{
//static int i=j; //illegal forward reference;
static int i=Backwards.j; //reference through class works
static int j=i;
public static void main(String[] args) {
System.out.println(i);
System.out.println(j);
}
}

If you step through the code in your debugger you will see that i = test(); is only run once ever.
The previous value for i is 0 and that's the value test() returns before i has been initialised.
The java compiler can't detect every possible forward reference, only the simplest ones.

Related

Find the minimum of a set of data input from the keyboard

I have an algorithm in my textbook written in pseudocode which is then supposed to be "implemented to a Java method". It goes like this:
read min;
while not eoln do
read x
if x < min then
min <- x
end if
end while
print min;
Then I'm given this code:
import java.util.Scanner;
int min() {
Scanner input = new Scanner(System.in);
System.out.println("x=? (999 to end)");
int x = input.nextInt();
int min = x;
while (x!=999) {
System.out.println("x=? (999 to end)");
x = input.nextInt();
if (x < min) {
min = x;
}
}
return min;
}
I put everything below import.Scanner inside of the main method and inside of a class like this:
public class MyAlgorithm {
public static void main(String[] args) {
// code here
}
}
But then I get this error message in Terminal:
MyAlgorithm.java:7: error: ';' expected
int min() {
^
1 error
Am I missing something? If I put the semicolon there, the whole thing just won't work.
It seems like you put your min method inside of main, this is defining methods from within other methods which will not work properly and cannot compile. The main method is the commands you want to run as soon as you start your program, any other functions in the class should be declared outside of it, and if you want them to run in main you do a method call.
it should look something like this:
import java.util.Scanner;
public class MyAlgorithm {
int min() {
//(min code)
}
public static void main(String[] args) {
// code here
//corrected according to Uli's comment
MyAlgorithm m = new MyAlgorithm();
int result = m.min();
}
}
I suggest reading up on how java programs are structured. Here's an article on methods.
Don't put your method min() inside the main() method. In Java, you can not define a method inside a method. In Java, you need an object to call its methods (Except you make the methods static). So your final Code looks something like this.
import java.util.Scanner;
public class MyAlgorithm {
public static void main(String[] args) {
MyAlgorithm m = new MyAlgorithm ();
m.min();
}
int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
}
If you are allowed to use static methods, (which I don't think) you can use the following alternative:
static int min(){
//Your min code goes here
return min_value;
// min_value is the same as your min variable. It has another name to
// prevent name collisions
}
public static void main(String[] args) {
int result = MyAlgorithm.min();
}

Return value of og the method is never used

public class prime {
public static String method(int n){
int cnt = 0;
for (int i = 2; i <n-1 ; i++) {
if (n%i==0)
++cnt;
}
if (cnt==0)
return "YES";
else
return "NO";
}
public static void main(String[] args) {
method(10);
}
}
IntelliJ is saying to me when i hover over name of my method that Return value of og the method is never used and when i hover over name of this method in main i get this message Result of 'prime.method()' is ignored and i dont know why. Any help? Also in console i get nothing. Just Process finished with exit code 0
You called method(), and it will return a String(YES or NO), but the return value was ignored. So IntelliJ IDEA reminds you to use it.
For example, print it:
String result = method(10);
System.out.println(result);
You are calling "method". It is returning a String. You do not assign it to a variable, i.e.
String value = method(10);
Methods can return values in Java, meaning they give a value back to the calling method. Your method "method(int)" returns a String to the main method.
However, the main method doesn't use the returned value.
If you want to print the value, you can use the following main method:
public static void main(String[] args) {
System.out.println(method(10));
}

pass array through method (java command line arguments)

I was wondering how I could check args.length within a method.
For example:
public static void commandLineCheck (int first, int second){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second);
}
I get a "cannot find symbol: args" error when I do this. Right now, I'm thinking I need to pass args[] through the method as well. I've tried this but it then gives me an "" error. Is there a beginner-friendly solution to this?
EDIT: Thank you so much for the quick response guys! It worked!
Change your code like this (You need to pass the array's parameter to your check method)
public static void commandLineCheck (int first, int second, String[] args){
if (args.length==0){
//do something with first and second
}
}
public static void main(String[] args) {
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
commandLineCheck(first, second, args);
}
And it will work. However the following test (args.length==0)does not make much sense since you have already assumed that args.length is greater or equal to 2 by extracting two values from it inside the main method. Therefore when you get to your commandLineCheck method, this test will always be false.
You need to pass the String [] args to your commandLineCheck method. This is written the same way as you declare the array for your main method.
public static void commandLineCheck (String[] args){
if (args.length==0){
//do something with first and second
}
}
Also you probably want to change your main method and commandLineCheck method a bit.
public static void commandLineCheck(String [] args) {
/* make sure there are arguments, check that length >= 2*/
if (args.length >= 2){
//do something with first and second
int first = Integer.parseInt(args[0]);
int second = Integer.parseInt(args[1]);
}
}
public static void main(String[] args) {
commandLineCheck(args);
}

Sequence of execution for variable creation and static block

class F
{
static
{
i = 1;
}
static int i = 2;
public static void main(String[] args)
{
System.out.println(i);
}
}
The output of this execution is 2. Can someone explain why not 1? In which sequence variables are getting created and initialized and static block is executed?
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
kindly check java documentation.
then clearly mentioned no matter how may static blocks are there they will be executed as a single block in the order they appear
So,
My understanding here is java is looking your code as
static{
i=1;
i=2;
}
static int i;
that is why you are getting output 2
hope this is helpful

Getting value to display for Java CurrentAccount class

package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.

Categories