Leon Kenedy Leon Kenedy - 1 month ago 14
Java Question

Why are my variables returning null and or 0 when using different classes?

My problem is when I run the code, the variables being accessed by the final print statement is returning them as null and or 0's.

Here is my code.

SammysContrusct
package program7;

import java.util.Scanner;
public class SammysContract {
Scanner userInput = new Scanner(System.in);
static String contractID,rental;

static int minutes,hours;

static double totalCost;

public void printWelcome()
{
System.out.println("Welcome back to Sammy's Rentals! Now introducing new prices and contracts!");
}

public String inputContract()
{
System.out.print("Please enter your contract ID: ");
String contractID = userInput.nextLine();
return contractID;
}

public String rentalItem()
{
System.out.print("What would you like to rent? ");
String rentalItem = userInput.nextLine();
return rentalItem;
}

public int hourID()
{
System.out.print("How many hours would you like to rent it for? ");
int hours = userInput.nextInt();
return hours;
}

public int minuteID()
{
System.out.print("How many minutes would you like to rent it for? ");
int minutes = userInput.nextInt();
return minutes;
}

public double calculateRate()
{
if (hours < 3)
{
totalCost = hours * 35;

}
else if (hours >= 3 | hours <=5)
{

totalCost = hours * 30;

}
else if (hours >= 5 | hours <=7)
{

totalCost = hours * 25;

}
else if (hours > 7)
{
totalCost = hours * 20;
}
else
{
System.out.print("Please enter a valid number.");
}

return totalCost;
}

public double calculateCost()
{
totalCost = hours + minutes;
System.out.printf("The contract ID %s has specified %s for %d hours and %d minutes will equate to %.2f", contractID, rental, hours, minutes, totalCost);

return totalCost;
}


}

SammysRentalsV2
package program7;

//Main Method ~ Driver Class

public class SammysRentalsV2 {

public static void main(String[] args)
{

SammysContract contracts = new SammysContract();

contracts.printWelcome();
contracts.inputContract();
contracts.rentalItem();
contracts.hourID();
contracts.minuteID();
contracts.calculateCost();
}


}

Answer

Because you are re-declaring your variables as local variables in your functions

public String inputContract()
{

    System.out.print("Please enter your contract ID: ");
    String contractID = userInput.nextLine(); // wrong one , local variable  
    contractID = userInput.nextLine(); // should be this 
    return contractID;
} 

Strings are objects so default value is null due to static/initialization and by default static int are initialize as 0 so don't re declare them and problem solved

local variables can only be used inside that function in which they are declared so their value and reference will be lost after the function execution.

Comments