Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the variable from one class to another

Hello everyone I'm currently creating a simple program. I have 2 classes the first one is SampleReturn and the second one is GetValues. What I want to happen is that when I enter a name in GetValues class the name I entered will be stored in a variable and later on will be used by the SampleReturn class to display the name. Unfortunately, I can't run the program because it has an error. The code is below please help me with regards to this matter. I'm just self studying I really want to learn Java. Thanks! :)

Code in GetValues Class:

import java.util.Scanner;
public class GetValues{
    Scanner inp = new Scanner(System.in);

    public static void wew(){
        System.out.println("Enter name: ");
        String a = inp.nextLine();

        private static String z = a;

        public static String kuhaName(){
            return z;
        }
    }
}

Code in SampleReturn:

import java.util.Scanner;
    public class SampleReturn{
        public static void main(String[]args){

        String nameMo = GetValues.kuhaName();

        System.out.print("Your name is: " +nameMo);
    }
}
like image 277
Angel Casi Montoya Avatar asked Dec 04 '25 05:12

Angel Casi Montoya


2 Answers

Your Code should be something like this:

import java.util.Scanner;

public class GetValues
{
    private static Scanner inp = new Scanner(System.in);
    private static String z = "";
    public static void wew()
    {
        System.out.println("Enter name: ");
        String a = inp.nextLine();
        z = a;
    }
    public static String kuhaName()
    {
        return z;
    }
}

And then SampleRun.java should be like this:

//import java.util.Scanner;//no need to import
public class SampleReturn
{
    public static void main(String[] args)
    {
        GetValues.wew();//First input the name .
        String nameMo = GetValues.kuhaName();//Retrieve the name
        System.out.print("Your name is: " +nameMo);//Display the name
    }
}
like image 58
Vishal K Avatar answered Dec 07 '25 01:12

Vishal K


You have a few problems going on in this code.

First of all, you can't have a method within another method. Second of all, you're never calling wew which will actually read the input. Assuming you meant something like this:

public class GetValues{
    Scanner inp = new Scanner(System.in);
    private static String z;

    public static void wew(){
        System.out.println("Enter name: ");
        String a = inp.nextLine();

        z = a;
    }

    public static String kuhaName(){
        return z;
    }
}

All you have to do now is call your methods in order.

like image 23
StrixVaria Avatar answered Dec 07 '25 00:12

StrixVaria