0

I'm trying to create this payroll system which has a login class and a salary-calculator class. I'm trying to use the username string entered by the user in the login class in the salary calculator class to determine the basic salary, but the username string is treated as null in the salary-calculator class hence I'm getting a lot of errors. I'm quite new to java programming so I would highly appreciate your help. Here is my code.

  public class loginpage {
   Scanner x;   // declares scanner
 static String name;
  static String username; 
       public void username(){
       String filepath = "/home/ogweno/NetBeansProjects/Payroll System/src/payroll/system/employees.txt"; // Declaring the filepath
      // Declaring a string for the username
       String password;  // Declaring a string for the password
       String username;
     
      username = JOptionPane.showInputDialog("Please enter your username: ", "username");
     
       
     
      password=JOptionPane.showInputDialog("Please enter your Password: ");
       VerifyLoginA(username, password, filepath);
       }
       
public void VerifyLoginA(String username, String password, String filepath) {
       boolean flag = false;     // boolean variable set to false for later use
       String tempUsername = "";  // variable used for extracting the username from txt file and storing in this
       String tempPassword = "";  // variable used for extracting the password from txt file and storing in this
       try {
             x = new Scanner(new File(filepath)); //opens the file "/home/ogweno/Students.txt"
             x.useDelimiter("[,\n]");    // use of delimiter to specify the seperation of username & password by ","
            
             boolean passed = false;     // boolean variable set to false and later use
           while (x.hasNext()&& !flag){  // use of while to check if the file has any contents 
               
               tempUsername = x.next(); // extracts the username and stores it 
               tempPassword = x.next();// extracts the password and stores it 
               if (tempUsername.trim().equals(username.trim()) && tempPassword.trim().equals(password.trim())) {
                   passed = true; // use of trim to remove any unwanted space in user input or in txt file
                   break; // boolean passedA becomes true if the username and passwords entered by user match the ones in file
               }
           }
           if(passed) { // if passedA is true then prints Welcome + the username
               // System.out.println("Welcome " + username);
               //System.out.println(""); // space
               JOptionPane.showMessageDialog(null,"Welcome " + username);
                 boolean check = true;
                 
                 setName(username);
               
           }
          
           else { // if passedA is false then prints a error message
              // System.out.println("********WARNING**Incorrect Username or Password*********");
                 JOptionPane.showMessageDialog(null,"********WARNING**Incorrect Username or Password*********");
                 boolean check = false;
               System.exit(0); // Terminates program if username and/or password is incorrect
           }
          
           
           
       }
       catch (FileNotFoundException e){ // prints error if there is an error in opening the file
           System.out.println("Error");
       }
     
   }

   public static void setName(String usernamename) {
       name=username;
      //To change body of generated methods, choose Tools | Templates.
   }
   public static String getName(){
       return name;
   }
}

Here's the salary-calculator class

public class Salary_calculator extends loginpage {
    public void calculator(){
        int HS=10000;
        int TV=5000;
        int NSSF=2000;
        int NHIF=500;

loginpage login=new loginpage();

int grossPay=0;
String post="";
float netSalary;
if (name=="Jane"){
    grossPay=20000;
    post="Finance Officer";
}
else if (name=="Michael"){
    grossPay=30000;
    post="IT technician";
}
else if (name=="Josphine"){
    grossPay=40000;
    post="Marketing Officer";
}
else if (name=="Darshan"){
    grossPay=50000;
    post="Public Relations Officer";
}
else if (name=="Ketan"){
    grossPay=60000;
    post="Operations Manager";
}
 

int salary=grossPay + HS + TV -(NSSF+NHIF);
netSalary=(float) (0.7*salary);

JOptionPane.showMessageDialog(null, name + ": " + post + "\n" + "Your net salary is: " + netSalary + "\n");
    }
}
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
  • 1
    The local variable `String username;` is shadowing the class variable – Scary Wombat Jun 16 '21 at 07:47
  • 3
    name=="Josphine" -> no. this compares references, not values. don't know if it's your issue, since I didn't check it all, but please use the equals method to compare the value of objects instead of == – Stultuske Jun 16 '21 at 07:47
  • `hence I'm getting a lot of errors` - Show us at least one of them !! – John3136 Jun 16 '21 at 07:58
  • `System.out.println("Error");` - extremely useful **NOT** – Scary Wombat Jun 16 '21 at 08:00
  • How do I use the equals method to compare string values? I've tried it but I'm getting an error, "String cannot be converted to boolean" – Ogweno Emmanuel Jun 16 '21 at 08:10
  • @ScaryWombat I've deleted the local variable and I still get the error message – Ogweno Emmanuel Jun 16 '21 at 08:13
  • `if (name.equals("Ketan"))` also *and I still get the error message* - why do you not tell us what the error is? – Scary Wombat Jun 16 '21 at 08:15
  • @ScaryWombat Here is the error message, run: Exception in thread "main" java.lang.NullPointerException at payroll.system.Salary_calculator.calculator(Salary_calculator.java:31) at payroll.system.PayrollSystem.main(PayrollSystem.java:22) /home/ogweno/.cache/netbeans/12.2/executor-snippets/run.xml:111: The following error occurred while executing this line: /home/ogweno/.cache/netbeans/12.2/executor-snippets/run.xml:94: Java returned: 1 BUILD FAILED (total time: 7 seconds) – Ogweno Emmanuel Jun 16 '21 at 08:38
  • Does this answer your question? [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Stultuske Jun 16 '21 at 08:44
  • @Stultuske not entirely. I understood it a bit though not much. I'm just looking for a way to use a String variable entered by the user in one class, and using that variable in another class. – Ogweno Emmanuel Jun 16 '21 at 09:00
  • @OgwenoEmmanuel your problem is a NullPointerException, that link explains how to fix one. You can send the value as param, or use a setter, or, .. – Stultuske Jun 16 '21 at 09:01
  • @OgwenoEmmanuel your entire design is ... somewhat odd. public class Salary_calculator extends loginpage { public void calculator(){ int HS=10000; int TV=5000; int NSSF=2000; int NHIF=500; loginpage login=new loginpage(); Why do you need a separate loginpage instance here? – Stultuske Jun 16 '21 at 09:03

1 Answers1

1

An example of accessing data in another class.

A minimal example class with one static and one non-static variable.

public class Payroll{
    public static String name1 = "static name1, same for all instances!";
    public String name2 = "name2, each instance has its own!";
}

Access the static name1 in Payroll from other classes:

String name = Payroll.name1;

Access the non-static name2 in Payroll from other classes:

Payroll payroll = new Payroll();
// Later, after the new instance has its data
String name = payroll.name2;

Remember, access to non-static variables requires that you have access to the instance. Every time you create a new instance with new it initially has no data or only standard data for you!

Edit: An example to demonstrate the interaction of two classes:

import java.util.*;
import javax.swing.*;

public class Payroll {
    static final List<Employee> employees = new ArrayList<>();

    public static void main(String[] args) {
        var payroll = new Payroll();

        var employee = payroll.login();
        JOptionPane.showMessageDialog(null, employee == null ? "Invalid Login!" : employee.getSalaryMessage());
    }

    public Payroll(){
        loadEmployees();
    }

    public Employee login(){
        String username = JOptionPane.showInputDialog("Please enter your Username:");
        String password = JOptionPane.showInputDialog("Please enter your Password:");
        for(var employee : employees) if(employee.isEmployee(username, password)) return employee;
        return null;
    }

    private void loadEmployees(){
        employees.add(new Employee("Jane", "jan", "xxx", 20000, "Finance Officer"));
        employees.add(new Employee("Michael", "mic", "yyy", 30000, "IT technician"));
        employees.add(new Employee("Josphine", "jos", "zzz", 40000, "Marketing Officer"));
        employees.add(new Employee("Darshan", "dar", "qqq", 50000, "Public Relations Officer"));
        employees.add(new Employee("Ketan", "ket", "ppp", 60000, "Operations Manager"));
    }
}

For completeness, the Employee class:

public class Employee {
    private String name;
    private String username;
    private String password;
    private double grossPay;
    private String post;

    public Employee(String name, String username, String password, double grossPay, String post){
        this.name = name;
        setUsername(username);
        setPassword(password);
        setGrossPay(grossPay);
        setPost(post);
    }

    public String getSalaryMessage(){
        return name + " (" + post + ") earns " + grossPay;
    }

    public boolean isEmployee(String username, String password){
        return this.username.equals(username) && this.password.equals(password);
    }

    public String getName(){ return name; }

    public void setName(String name){ this.name = name; }

    public String getUsername(){ return username; }

    public void setUsername(String username){ this.username = username; }

    public String getPassword(){ return password; }

    public void setPassword(String password){ this.password = password; }

    public double getGrossPay(){ return grossPay; }

    public void setGrossPay(double salary){ this.grossPay = salary; }

    public String getPost(){ return post; }

    public void setPost(String post){ this.post = post; }
}
  • The first method with the static variable runs but it has a logic error, the second class(or the first) initializes my static variable to null/"" thus giving me a wrong answer. Could you show me how to store the value entered by the user as a public variable so that it can be used by another class. – Ogweno Emmanuel Jun 16 '21 at 16:22
  • If successful, your function `VerifyLoginA` calls the function `setName`. The parameter name in the function has a typo! `usernamename` should be `username`. This does not set the `name`, but the content of the static variable `username`, which is also null, is copied to `name`! –  Jun 16 '21 at 16:37