+ 1

hey guys idk why this code didn't work.. can u please help me

public class Employee{ private int empNum; public void setEmpNum(int emp) { empNum = emp; } public int getEmpNum() { return empNum; } } import java.util.Scanner ; public class Company { public static void main (String [] args){ Scanner input = new Scanner (System.in); System.out.println("Enter emp number "); int emp = input.nextInt (); Employee.setEmpNum(emp); System.out.println("Emp num ="+ Employee.getEmpNum()); } }

24th Jul 2021, 12:11 PM
Habo Osman
11 ответов
29th Jul 2021, 7:00 AM
Habo Osman
+ 1
Alaska I'll try that.. though it works every time with them first
24th Jul 2021, 12:46 PM
Habo Osman
+ 1
oh wait.. now i get it
24th Jul 2021, 12:48 PM
Habo Osman
+ 1
nope.. still the same.. it says something about static and nonstatic methods
24th Jul 2021, 12:50 PM
Habo Osman
+ 1
it says that non-static method setEmpNum(int) cannot be referenced to static context Employee.setEmpNum(emp) ;
24th Jul 2021, 12:53 PM
Habo Osman
+ 1
guys i knew what's wrong.. i must create an object of it first then use it to reach the methods.. thx java for being so easy 👍
24th Jul 2021, 1:10 PM
Habo Osman
+ 1
Alaska i did declare them static.. then another problem showed up i don't remember what was it.. anyway thanks 🖤
24th Jul 2021, 1:17 PM
Habo Osman
+ 1
public class Employee{ private int empNum; public void setEmpNum(int emp) { empNum = emp; } public int getEmpNum() { return empNum; } } import java.util.Scanner ; public class Company { public static void main (String [] args){ Scanner input = new Scanner (System.in); System.out.println("Enter emp number "); int emp = input.nextInt (); Employee e = new Employee(); e.setEmpNum(emp); System.out.println("Emp num ="+e.getEmpNum()); } }
25th Jul 2021, 5:31 AM
Shahid Iqbal
Shahid Iqbal - avatar
0
Import statements should be the first thing, after that declare all the classes
24th Jul 2021, 12:13 PM
Alaska
Alaska - avatar
0
Habo Osman Yes, non-static methods should only be accessed through objects. While you can still declare method as static and call it using class's name.
24th Jul 2021, 1:15 PM
Alaska
Alaska - avatar
0
No worries ✌️
24th Jul 2021, 1:21 PM
Alaska
Alaska - avatar