I am getting these 3 errors after compiling .. Pls help and thnx in advance..
error: variable ac might not have been initialized
tcws= cm+tm+ac+am+ta;
error: variable am might not have been initialized
tcws= cm+tm+ac+am+ta;
error: variable ta might not have been initialized
tcws= cm+tm+ac+am+ta;
My code:
import java.lang.*;
import java.util.Scanner;
class CellPhoneBill {
public static void main(String[]args) {
double cm ,tm ,ac, am, ta, tcws, tax, taxpluscost ;
Scanner s=new Scanner(System.in);
System.out.print("Enter the number of minutes and also enter the number of text messages ");
cm= s.nextDouble();
tm= s.nextDouble();
if(cm<=50&& tm<=50) {
System.out.print("Base charge= $15.00"); }
else if(cm>50 && tm>50) {
System.out.println("Enter no of additional call minutes (if any) and additional messages(if any) ");
ac=s.nextDouble();
am= s.nextDouble();
cm=0.25* ac;
am=0.15*am;
System.out.println("Additional call charges = " +ac);
System.out.println("Additional message charges = " +am);
ta=ac+am;
System.out.println("Total Additional charges = " +ta);
}
else if(cm>=0&& tm>=0) { System.out.println("911 Call charges =$0.44" );
}
else {
tcws= cm+tm+ac+am+ta;
System.out.println("Total cost without Sales Tax ="+tcws);
tax=( 5/100.00*(tcws));
System.out.println(" 5% Sales Tax ="+tax);
taxpluscost=tcws+tax;
System.out.println("Total cost Including 5% Sales Tax ="+taxpluscost);
}
}
}
It means that the variables ac, am and ta have not been assigned any value. You cannot sum variables that haven’t got any value.
For the fix, it depends on what you are trying to obtain. Maybe you need to do ac=s.nextDouble(); as in some of the other cases to read a value from the user. Or maybe you just need to do ac = 1.0; or whatever the appropriate value would be. And the same for the other two variables, of course.
Possibly you intended a different if-else structure where the values assigned to the three variables in one if branch should also be used in the last else part?
For Auto initialization you can declare them in your class as instance variable instead in static method.You can use the same variable in your static method then.
Your scanner only prompts the user for two values initially, neither of which are ac or am. Thusac = s.nextDouble() and am = s.nextDouble () aren't actually assigning values to ac and am
In java references to primitive data types are stored in the same register as the variable.
double a = 12.345;
Initializes a variable a and sets it to the value of 12.345.
You must initialize your variables prior to using them lest you get an error.
edited for corrections
Related
I have called 'setPrice()' mutator method from a class 'Holiday' which holds 'double' as a data type. However, when I add 'holiday.setPrice()', it says "method setPrice in Holiday class cannot be applied to the given types: double". I am confused to why that is.
public void checkOut(Member member, Holiday holiday){
if(member.getBalance() >= holiday.getPrice()){
System.out.println("Transaction complete");
System.out.println("You have been automatically logged off");
member.setLoginStatus(false);
if(checkHitDiscount() == true){
holiday.setPrice() = discount - holiday.getPrice() ;
System.out.println(" Good news! You're eligible for a discount!");
}else{
System.out.println("No discount available, try again next time");
}
} else {
System.out.println("You don't have suffiencient funds");
}
}
You are attempting to use the following line:
holiday.setPrice() = discount - holiday.getPrice();
This should probably be
holiday.setPrice(discount - holiday.getPrice());
instead. The inputs of a function go inside its parentheses.
EDIT: discount and holiday.getPrice() should also probably be reversed, based on their names.
EDIT2: What your existing code is trying to do is assign the value of discount - holiday.getPrice() to the double which is returned by a hypothetical holiday.setPrice() with no inputs. This is not allowed, because that is a value, not a variable (ie: a name referring to a spot in memory storing a value). It's a bit like trying to execute 5 = 3 + 4;.
This program will calculate the amortization table for a user. The problem is my assignment requires use of subroutines. I totally forgot about that, any ideas on how to modify this to include subroutines?
public class Summ {
public static void main(String args[]){
double loanamount, monthlypay, annualinterest, monthlyinterest, loanlength; //initialize variables
Scanner stdin = new Scanner (System.in); //create scanner
System.out.println("Please enter your loan amount.");
loanamount = stdin.nextDouble(); // Stores the total loan amount to be payed off
System.out.println("Please enter your monthly payments towards the loan.");
monthlypay = stdin.nextDouble(); //Stores the amount the user pays towards the loan each month
System.out.println("Please enter your annual interest.");
annualinterest = stdin.nextDouble(); //Stores the annual interest
System.out.println("please enter the length of the loan, in months.");
loanlength = stdin.nextDouble(); //Stores the length of the loan in months
monthlyinterest = annualinterest/1200; //Calculates the monthly interest
System.out.println("Payment Number\t\tInterest\t\tPrincipal\t\tEnding Balance"); //Creates the header
double interest, principal; //initialize variables
int i;
/* for loop prints out the interest, principal, and ending
* balance for each month. Works by calculating each,
* printing out that month, then calculating the next month,
* and so on.
*/
for (i = 1; i <= loanlength; i++) {
interest = monthlyinterest * loanamount;
principal = monthlypay - interest;
loanamount = loanamount - principal;
System.out.println(i + "\t\t" + interest
+ "\t\t" + "$" + principal + "\t\t" + "$" + loanamount);
}
}
}
any ideas on how to modify this to include subroutines?
Well, you are better off doing it the other way around; i.e. working out what the methods need to be before you write the code.
What you are doing is a form or code refactoring. Here's an informal recipe for doing it.
Examine code to find a sections that perform a specific task and produces a single result. If you can think of a simple name that reflects what the task does, that it a good sign. If the task has few dependencies on the local variables where it currently "sits" that is also a good sign.
Write a method declaration with arguments to pass in the variable values, and a result type to return the result.
Copy the existing statements that do the task into the method.
Adjust the new method body so that references to local variables from the old context are replaced with references to the corresponding arguments.
Deal with the returned value.
Rewrite the original statements as a call to your new method.
Repeat.
An IDE like Eclipse can take care of much of the manual work of refactoring.
However, the real skill is in deciding the best way to separate a "lump" of code into discrete tasks; i.e. a way that will make sense to someone who has to read / understand your code. That comes with experience. And an IDE can't make those decisions for you.
(And did I say that it is easier to design / implement the methods from the start?)
I deleted my previous comment as I answered my own question by reading the associated tags :-)
As an example, define a method like this in your class:
public double CalculateInterest(double loanAmount, double interestRate) {
//do the calculation here ...
}
And then call the method by name elsewhere in your class code e.g.
double amount = CalculateInterest(5500, 4.7);
Trying to make a for loop where a user inputs 6 numbers. Then each number is validated to see that it is positive. Then they are all added up for a subtotal.
On my last line count += itemPrice; I'm getting an error on count saying "The local variable may not have been initialized." A buddy of mine can't seem to figure out why as well and wondering what is up with that.
public static double namehere() {
double count;
for (int x = 0; x < 6; x++)
{
Scanner input = new Scanner (System.in);
System.out.println ("Price of Item: ");
double itemPrice = input.nextDouble();
while (itemPrice < 0.01)
{
Scanner input2 = new Scanner (System.in);
System.out.println ("Price of Item: ");
itemPrice = input.nextDouble();
}
count += itemPrice;
}
double count; // not initialized
double count = 0; // initialized
Local primitive variables are not set to 0 by default, so they must be explicitly initialized.
As the error message says, your count variable is not initialized. To solve the error, initialize with a default value, like 0.
Note: the local variables are not initialized implicitly not like class members.
The purpose of local variables is different than the purpose of instance variables. Local variables are there to be used as part of a calculation; instance variables are there to contain state. If you use a local variable without assigning it a value, that's almost certainly a logic error, and hence, compiler complains..
I'm trying to build a basic weight calculator and came across "variable weightOut might not have been initialized" error. Google seems to indicate that this is because I need to initialize "weightOut" rather than just set it " = weightIn * .78 " . Is this true? Here is my code.
Scanner keyboard = new Scanner(System.in);
int weightIn, planetNumber;
double weightOut;
System.out.print("What is your weight? ");
weightIn = keyboard.nextInt();
System.out.println("I have information for the following planets: ");
System.out.println(" 1. Venus ");
...
System.out.print("What planet are you going to? ");
planetNumber = keyboard.nextInt();
if( planetNumber == 1 )
{
weightOut = weightIn * 0.78;
}
...
System.out.println("Your weight would be " + weightOut +
" on that planet.");
Local variables are not initialized with default values.Local variables should be initialized before use .
double weightOut = 0.0;
What if the if statement never really executed at run time ? The compiler is actually worried that in case during run time the local variable fails to get a value and you use it some where else , what value it should have given it doesn't have a default value !
In java method/local variables should be initialized. Uninitialized variables can give unexpected results and hence this is raised. In your code the value of weightOut will never be set if the enclosing if conditions is not met. You need to initialize the following variable with some default value:
int weightIn = 0;
int planetNumber = 0;
double weightOut = 0.0d;
What value will the the variable have if you don't enter the if-branch?
To fix this, add an else-branch at the end:
if (...)
myVar = x;
else if (...)
myVar = z;
else
myVar = y;
Setting the value in an else-branch rather than setting some default initial value not only makes the compiler happy but also prevents you from committing the error that the compiler is complaining about: if at some later point you add code that uses the variable before its correct value is set in the if statement you would still get an error message from the compiler and not an unexpected result when running the program.
You need to initialize "weightOut" to 0, because local variable can not be used without initializing.
As in your case you are assigning value in if condition and that one is not valid because in java value of local variable is decided at run time. That is the reason u are getting error.
What if the planet number is 0?
You should do:
double weightOut = 0;
Now I have read and on this but i am just stuck. Any help appreciated. I am looking for hints. The code compiles and runs fine but I don't think the variables are being stored in the employee class and I am not sure I am understanding my use of the constructor right.
Requirements:
I have completed:
Values are checked to ensure they are
positive numbers.
Entering stop as the
employee name end program.
Having trouble on
Uses a class to store
name
hourly rate
hours worked
Use a constructor to initialize the employee information
and a method within that class to
calculate the weekly pay.
Here are a couple hints:
Use a constructor to initialize the
employee information
Looking at the provided code, there is a single constructor which takes no arguments and will initialize the fields of the object to zero.
Perhaps the "constructor to initialize the employee information" means that the constructor should be able to accept values which the Employee object should initlialize its fields to.
The Java Tutorials has a page on Providing Constructors for Your Classes with examples which should help in creating such constructor.
... and a method within that class to
calculate the weekly pay
This seems to say that there should be a method that is only visible to itself and not available from others in order to calculate the value for the weeklyPay field.
Again, from The Java Tutorials, Controlling Access to Members of a Class discusses show to change the visibility of methods.
Reading the contents of the assignment, it seems like taking a look at the Lesson: Classes and Objects of The Java Tutorials may be of use, as it provides some good examples and explanations on the concepts of object-oriented programming.
In addition to the fact that you haven't used the constructor to set your variables, as mentioned by others. The setter methods are performing no-ops. Which is why you aren't getting the results you expect. You are setting the local var to itself and not to the member var.
You need to either change your local var names, change the member var names, or change the setters to use the 'this' keyword
public void sethoursWorked(float hoursWorked)
{
this.hoursWorked = hoursWorked;
}
You'll notice that you are asked to make a class that stores the name, the hourly rate, and the hours worked, while you are asked to make a method that calculates the weekly pay. In other words, you should not have a weeklyPay instance variable. Whenever the user asks for the weekly pay (by means of your getWeeklyPay() method), you calculate and return it directly, without storing it in an instance variable.
Then, in order to actually use that result, you'll need to change this:
Employee.getweeklyPay();// Calculate weeklyPay ( hoursWorked * hourlyRate )
weeklyPay = ( hoursWorked * hourlyRate );
into something like this:
weeklyPay = employee.getWeeklyPay();
If you don't actually assign the result of your method to some variable, you can't use the result.
The final answer from the OP:
/** Payroll3.java | Due 8/09/09
** IT 2015 Java Programming | lazfsh | Axia College - University of Phoenix */
import java.util.Scanner;// Import and use scanner
public class Payroll3 {// main method begins
public static void main( String args[] ) {
// Initialize
boolean stop = false;// Variable for exit procedure
String endProgram = "";// Variable to explain exit procedures blank 1st time
int version = 3;// Version number
// Welcome message
System.out.printf(
"\nWelcome to the Payroll Program v.%d\n", version );//Welcome message
while ( stop == false) {// Run program until stop equals true
Scanner input = new Scanner( System.in );// new Scanner for CL input
Employee Employee = new Employee(); // new Employee constructor
// Prompt for and input name
System.out.printf( "\nEnter name of the employee%s:", endProgram );
Employee.setempName(input.nextLine());// Accept input & Store
if ( Employee.getempName().equals( "stop" )) {// If = end program w/message
System.out.printf( "\n%s\n%s\n\n", "....", "Thanks for using Payroll Program");
stop = true;}
else{// Continue retrieve hourlyRate, hoursWorked & Calculate
do {// Prompt for and input hourlyRate
System.out.printf( "\n%s", "Enter hourly rate: $" );
Employee.sethourlyRate(input.nextFloat());// Accept input & Store
if ( Employee.gethourlyRate() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethourlyRate() < 1 );// End loop if positive number recieved
do {// Prompt for and input hoursWorked
System.out.printf( "\n%s", "Enter number of hours worked:" );
Employee.sethoursWorked(input.nextFloat());// Accept input & Store
if ( Employee.gethoursWorked() < 1 ) {// Show error for negative #
System.out.printf( "%s", "Enter a positive number.");}
else;{}// Continue
} while ( Employee.gethoursWorked() < 1 );// End loop if positive number recieved
// Display formatted results
System.out.printf( "\n%s's weekly pay is $%,.2f\nHourly rate ($%,.2f) multiplied by hours worked (%.0f)\n\n...Ready for next employee.\n\n",
Employee.getempName(), Employee.getweeklyPay(), Employee.gethourlyRate(), Employee.gethoursWorked() );
// Debug Line Employee.showVariables();
}// end retrieve hourlyRate, hoursWorked & Calculate
endProgram = ( ", \n(Or type \"stop\" to end the program)" );//explain exit procedure on second empName prompt
}// ends program when stop equals true
}// end method main
}//end class Payroll3
Employee class
/** Employee Class | Initializes and storeds data for employee
Also provides method to calculate weekly pay.
*/
// Import statements
import java.util.Scanner;// Import and use scanner
public class Employee {//Begin Employee class
Scanner input = new Scanner( System.in );// new Scanner for CL input
// Declare instance variables
String empName; // Declare name as string
float hourlyRate; // Declare hourlyRate as float
float hoursWorked; // Declare hoursWorked as float
// constructor initializes employee information
public Employee() { // Initialize (clear) instance variables here
empName = "";
hourlyRate = 0;
hoursWorked = 0;
} // end constructor
// Begin methods
public void setempName(String empName) {// public method to set the employee name
this.empName = empName;}// end method setempName
public String getempName() {// public method to get the employee name
return empName;}// end method getempName
public void sethourlyRate(float hourlyRate) {// public method to set the hourly Rate
this.hourlyRate = hourlyRate;}// end method set hourly Rate
public float gethourlyRate() {// public method to retrieve the hourly Rate
return hourlyRate;} // end method get hourly Rate
public void sethoursWorked(float hoursWorked) {// public method to set the hours Worked
this.hoursWorked = hoursWorked;} // end method set hours Worked
public float gethoursWorked() {// public method to retrieve the hours Worked
return hoursWorked;} // end method get hours Worked
public float getweeklyPay() {// public method to retrieve weekly Pay
return ( hoursWorked * hourlyRate );}// end method get weeklyPay
/* Test line
public void showVariables(){
System.out.printf( "empName=%s, hourlyRate=%s, hoursWorked=%s", this.empName, this.hourlyRate, this.hoursWorked );} */
} // end class Employee