I want to display inputs from one class in another class but it's not working

Viewed 33

I want to try a simple 3 variable input to pass to another class and display it but it's not working. I have two separate classes.

main.java :

'''

import.java.util.*;

public class Main{
   String firstName, lastName, email;
   Scanner display = new Scanner(System.in);
   System.out.println("Enter first name: ");
   firstName = display.nextLine();
   System.out.println("Enter last name: ");
   lastName = display.nextLine();
   System.out.println("Enter email: ");
   email = display.nextLine();
} 

'''

print.java :

'''

import.java.util.*;

class print{
    public static void main(String[] args) {
         Main myObj = new Main();
         System.out.println(myObj.firstName);
         System.out.println(myObj.lastName);
         System.out.println(myObj.email);
    }
}

'''

1 Answers

With your code as template and the following changes it works. I

  • put the input processing into a constructor
  • added a try-with-resources so that the scanner will be closed
  • just made print a public class to make it executable
  • and made class Main package visible so that there is only one public class
import java.util.*;

class Main {
    String firstName, lastName, email;
    Main() {
        try (Scanner display = new Scanner(System.in)) { 
            System.out.println("Enter first name: ");
            firstName = display.nextLine();
            System.out.println("Enter last name: ");
            lastName = display.nextLine();
            System.out.println("Enter email: ");
            email = display.nextLine();
        }
    }
}

public class print {
    public static void main(String[] args) {
        Main myObj = new Main();
        System.out.println(myObj.firstName);
        System.out.println(myObj.lastName);
        System.out.println(myObj.email);
    }
}
$ javac print.java
$ java print 
Enter first name: 
John
Enter last name: 
Smith
Enter email: 
js@js.com
John
Smith
js@js.com
$ 

Please note that it is not a good idea to put several classes into one file. It is here only done in order to make it easily reproducible.

What you are trying to with classes and a scanner is described in detail on https://hackr.io/blog/best-way-to-learn-java. You might want to take a look there!

Related