Using local-variables in other methods? - java

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);
}

Related

Actual and formal parameters

I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.

How to run a method from a different class - JAVA [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I am trying to call the toh method from my main class(Driver). When I make the call it gives me a null pointer exception. How can I call the toh method in Hanoi from the driver class? When I combine the classes into one it works fine but I need them to be two separate classes. Also, I included the global variables I am using in both classes is that necessary? Any help is welcome. Thanks!
public class Hanoi {
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void toh(int n)
{
for (int d = n; d > 0; d--)
tower[1].push(d);
display();
move(n, 1, 2, 3);
}
/* Recursive Function to move disks */
public static void move(int n, int a, int b, int c)
{
if (n > 0)
{
move(n-1, a, c, b);
int d = tower[a].pop();
tower[c].push(d);
display();
move(n-1, b, a, c);
}
}
/* Function to display */
public static void display()
{
System.out.println("T"+cycle + " Pillar 1 | Pillar 2 | Pillar 3");
System.out.println("-------------------------------------");
for(int i = N - 1; i >= 0; i--)
{
String d1 = " ", d2 = " ", d3 = " ";
try
{
d1 = String.valueOf(tower[1].get(i));
}
catch (Exception e){
}
try
{
d2 = String.valueOf(tower[2].get(i));
}
catch(Exception e){
}
try
{
d3 = String.valueOf(tower[3].get(i));
}
catch (Exception e){
}
System.out.println(" "+d1+" | "+d2+" | "+d3);
}
System.out.println("\n");
cycle++;
}
}
Main class(driver):
public class Driver{
public static int N;
public static int cycle = 0;
/* Creating Stack array */
public static Stack<Integer>[] tower = new Stack[4];
public static void main(String[] args)
{
int num = 0;
Scanner scan = new Scanner(System.in);
tower[1] = new Stack<>();
tower[2] = new Stack<>();
tower[3] = new Stack<>();
/* Accepting number of disks */
while(num <=0){
System.out.println("Enter number of disks(greater than 0):");
num = scan.nextInt();
}
N = num;
Hanoi.toh(num);
}
}
You are initializing your tower array inside your Driver class, however, you have not initialized it in your Hanoi class.
As I said in my comment, please do not write global variables twice, in different classes. This is because the different classes DO NOT share the same global variables. (when we say global variable, we mean that they are global to the Driver class only. To access those variables, use the dot operator)
For example, get rid of the N cycle and tower declarations from your Hanoi class
Then access those variables using the dot operator.
tower would become Driver.tower and N would become Driver.N and so forth.
Note: this only works if your Driver class is static, otherwise you would need to access it as an object attribute.
Try to initialize the tower array, something like this:
public static Stack<Integer>[] tower;
public static void toh( int n )
{
tower = new Stack[n];
for ( int d = 0 ; d < n ; d++ )
{
tower[d]=new Stack<>();
}
delete duplicated static values in a class (either Driver or Hanoi)
then in the class that no longer has the static values and add that class to the beginning of all the missing classes.
Ex:
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public static int MyVar;
public void bMethod(){
++MyVar;
}
}
↓ to ↓
class A{
public static int MyVar;
public int aMethod(){
return MyVar-2;
}
}
class B{
public void bMethod(){
++A.MyVar;
}
}

java constructor: this(.)

Why the output is "021"? Why there are "0" and "1"(since "i" get "2" why it changes to "1")?
public class C {
protected int i;
public C(int i){
this(i,i);
System.out.print(this.i);
this.i=i;
}
public C(int i, int j) {
System.out.print(this.i);
this.i=i+j;
}
public C(){
this(1);
System.out.print(i);
}
public static void main(String[] args) {
C c=new C();
}}
C() calls C(1) which calls C(1,1)
C(1,1) prints 0 (the default value of this.i) and assigns 2 (i+j) to this.i
then C(1) prints 2 and assigns 1 to this.i
then C() prints 1
I think this is better for understanding:
public C(int i) {
this(i, i);
System.out.println("*"+this.i);
this.i = i;
}
public C(int i, int j) {
System.out.println("#"+this.i);
this.i = i + j;
}
public C() {
this(1);
System.out.println("#"+i);
}
Now, you can get the sequence of these methods when you invoke C();
Here the code commented, you will understand your problem now,
public class C {
protected int i;
public C(int i) {
this(i, i); // got to two parameter constructer and after the result print the next line
System.out.print(" + second "+this.i); // print value of i which is come from C(int i, int j) = 2
this.i = i; // set the value of i to 1
}
public C(int i, int j) {
System.out.print("first "+this.i); // print the value of i (in this case 0 the default value)
this.i = i + j; // set i to 2
}
public C() {
this(1); // got to one parameter constructer and after the result print the next line
System.out.print(" + Third is "+i); // print value of i which is come from C(int i) = 1
}
public static void main(String[] args) {
C c = new C();
}
}
I hope that help.

A method which accepts two integer values as input parameters and returns the boolean

This is one of the practice questions of a test:
Write a method which accepts two integer values as input parameters and returns the boolean result true if the sum of the inputs is greater than or equal to 10 (and falseotherwise)
My answer is below but I don't think it looks correct. Can anyone give me a pointer?
public class Bruh{
public static void main (String [] arg){
int a;
int b;
boolean sum = true;
if ( a+b > 10)
System.out.println ("yo");
else{
sum = false;
}
}
}
You only wrote some code in the main method but you did not create one.
In order to do that you need to actually create a method in your Bruh class like:
public static boolean isSumGreaterThan9(int a, int b){
return (a + b) > 9;
}
Than call it from the main method:
public static void main (String [] arg){
int a = 4; // or whatever
int b = 7; // or whatever
System.out.println(isSumGreaterThan9(a, b));
}
You need to put your logic into a method and change your comparison to >= as per the requirement:
public static boolean isSumGreaterThanOrEqualToTen(int a, int b) {
return (a + b) >= 10;
}

Returning method without passing a value in it - Java

I have a method returning an integer. My question is how to get this number
like
int d = returning value of customerperminute methods;
Thanks in advance
public int customerperminute(){
Random R = new Random();
int r = R.nextInt(4-0);
if (r==0||r==1){
return 0;
}
if (r==2){
return 1;
}
else {
return 2;
}
}
Just invoke method like this: int d = customerperminute();
suppose the class in which this method is defined is ABC and let's say customerperminuteStat, which is static method.
class ABC{
public int customerperminute(){
Random R = new Random();
int r = R.nextInt(4-0);
if (r==0||r==1){
return 0;
}
if (r==2){
return 1;
}
else {
return 2;
}
}
public static int customerperminuteStat(){
Random R = new Random();
int r = R.nextInt(4-0);
if (r==0||r==1){
return 0;
}
if (r==2){
return 1;
}
else {
return 2;
}
}
}
this is just class definition with it's methods.
To retrieve value from the function is to call the method.
*Static Method, say customerperminuteStat can be called from any type method(static/instance). But the non-static, say instance eg. customerperminute can be called from only instance methods.*
Calling
from the method of same class
int d = customerperminute();
int e = customerperminuteStat();
from the method of some other class
int d = customerperminute();
int e = customerperminuteStat();
1)Invoke it directly in non-static methods:
int value = customerperminute();
2)Invoke it in static method, add static in the method signature:
public class Test {
public static void main(String[] args) {
System.out.println(customerperminute());
}
public static int customerperminute() {
Random R = new Random();
int r = R.nextInt(4 - 0);
if (r == 0 || r == 1) {
return 0;
}
if (r == 2) {
return 1;
} else {
return 2;
}
}
}
use the following code in main() method
public static void main(String s[]){
ABC inst = new ABC(); //create instance of class which contains called method
int d = customerperminute();
}
or make customerperminute() as static & you can directly call it using class name ABC.customerperminute() if method is in different class or directly as customerperminute() if method is in same class as main() method

Categories

Resources