为什么我的变量在使用不同的类时返回null和0?

时间:2016-10-17 18:37:47

标签: java class methods null var

我的问题是当我运行代码时,最终print语句访问的变量将它们返回为null和0。

这是我的代码。
SammysContrusct 包程序7;

Array( )

}

SammysRentalsV2 包程序7;

//主要方法〜驱动程序类

公共课SammysRentalsV2 {

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;       
}   

}

1 个答案:

答案 0 :(得分:0)

因为您在函数中将变量重新声明为局部变量

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;
} 

字符串是对象,因此null默认值为static/initialization,默认情况下static int初始化为0所以不要声明它们并解决问题

局部变量只能在声明它们的函数内使用,因此它们的值和引用将在函数执行后丢失。