JAVA Variable out of scope - java

I am a student, just learning about Class and Methods. I am receiving an error (line 30 - savings = pr * discount / 100) "Cannot find symbol". I understand that my variable discount, is out of scope, but I cannot figure out how to correct this. I have followed the instructions provided to me, but it still is not working. I have already caught a few typos in the textbook, so is there something missing? Or is it my positioning of curly brackets?
import java.util.Scanner; // Allows for user input
public class ParadiseInfo2
{
public static void main(String[] args)
{
double price; // Variable for minimum price for discount
double discount; // Variable for discount rate
double savings; // Scanner object to use for keyboard input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter cutoff price for discount >> ");
price = keyboard.nextDouble();
System.out.print("Enter discount rate as a whole number >> ");
discount = keyboard.nextDouble();
displayInfo();
savings = computeDiscountInfo(price, discount);
System.out.println("Special this week on any service over " + price);
System.out.println("Discount of " + discount + " percent");
System.out.println("That's a savings of at least $" + savings);
}
public static double computeDiscountInfo(double pr, double dscnt)
{
double savings;
savings = pr * discount / 100;
return savings;
}
public static void displayInfo()
{
System.out.println("Paradise Day Spa wants to pamper you.");
System.out.println("We will make you look good.");
}
}

Your code is correct - you just called the out of scope variable discount when you needed the in scope variable dscnt. Try this:
public static double computeDiscountInfo(double pr, double dscnt) {
double savings;
savings = pr * dscnt / 100;
return savings;
}

The problem is caused by, as you mentioned in your question, the variable discount being out of scope. Let's look at why.
In your original code, the method computeDiscountInfo(double pr, double dscnt) is passed to parameters: a double labeled pr, and another double labeled dscnt. your method will only have knowledge of these two parameters, and not of anything going on outside of it. (There are some exceptions to this, such as 'static' variables, or variables passed from a parent. However, these are most likely beyond the scope of your learning at the moment. I'm sure you wil cover them in school soon.)
Since the variable discount is declared in the main() method, there is no way for your computeDiscountInfo(double pr, double dscnt) method to know of it's existence. When you cal on this method, you can pass it the discount variable as a parameter to be used (as you do in your code with savings = computeDiscountInfo(price, discount);) The method will then apply the value of discount to it's own local variable dscnt that you defined in the method's declaration. This is the variable that the method will know and use.
Now, lets look back at your method:
public static double computeDiscountInfo(double pr, double dscnt)
{
double savings;
savings = pr * discount / 100;
return savings;
}
In this method you refer to the variable as discount, not by the local name dscnt as declared in the method's parameters. The method has no understanding of what discount means. It could be passed any double in this place. By changing the word discount to dscnt inside your method, the method will be able to understand what you are reffering to and use the value properly.
public static double computeDiscountInfo(double pr, double dscnt)
{
double savings;
savings = pr * dscnt/ 100;
return savings;
}
I hope that this makes sense to you, please let me know if it does not. The concepts of local variables and variable scope is key parts of the foundation of Object-Oriented Programming.

Related

How do I loop until I get the right answer?

I'm trying to program something that repeats itself until it gets the amount right. My program is basically a loan program that helps you figure out how long it'll take for you to pay off a loan with interest. So far, I managed to get the first month to print out (although not exactly right...), but I need it to keep repeating until the loan amount has been paid off. I hope that makes sense.
import java.util.*;
import java.io.*;
public class Project4{
static Scanner console = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException
{
Scanner keyboard = new Scanner(System.in);
Scanner user_input = new Scanner(System.in);
Scanner scan = new Scanner(System.in);
PrintWriter outFile = new PrintWriter("Project4.out");
double lamnt;
double mpay;
double intrestrate;
double mnthintrest;
double mintrestrate;
System.out.print("Enter the Loan Amount: ");
lamnt = keyboard.nextDouble();
System.out.println();;
System.out.print("Enter the intrest rate (Ex:5.75): ");
intrestrate = keyboard.nextDouble();
System.out.println();
System.out.print("Enter the monthly payment you want to make: ");
mpay = keyboard.nextDouble();
System.out.println();
mintrestrate = intrestrate/12;
mnthintrest = lamnt*mintrestrate;
System.out.println("The first month intrest rate is:" + pay);
}
}
I was suggested using a while loop but I'm not too sure how to make the while loop keep going until the loan amount is paid off. Also yes I know the outcome isn't right, I'm working on that part. I'm not too sure how to space out the titles properly.
I need the output to look like this: (using 1000 in loan payment, 7.2 in interest rate, 25 for monthly pay)
Amount loan after payment #1 is: 981.00 Principle is: 19.00 Interest is: 6.00
Amount loan after payment #2 is: 961.89 Principle is: 19.11 Interest is: 5.89
So, if you want to use a while loop until your loan is paid off, just do something like:
while (lamnt > 0) {
// Do stuff to pay off the loan here.
}
As long as you're updating the lamnt within the loop, that should work.
Hope that helped!
;)
Edit: Also, make sure you're only creating scanners that you actually use. And don't forget to close them at the end of the scope!
Assuming that interest rate would be entered in percentage, the mnthintrest calculation would need an additional multiplication by 1/100 i.e. 0.01
mnthintrest = lamnt*mintrestrate*(0.01);
You also need to edit the variable pay to mpay
System.out.println("The first month intrest rate is:" + pay);
I think your logic for money paid per month should be ( as others suggested) - reducing the loan amount until it reaches zero.
Now coming to implementation, you will be reducing the amount and since we wouldn't want the original data ( variable) to be affected, we could first store it an temporary variable.
For keeping track of #number of payment, we can keep the month count in another variable.
You could think of something like this:
double temp = lamnt;
int monthNumber = 1;
while(temp>0){
mnthintrest = temp*mintrestrate*0.01;
double principlePaidPerMonth= mpay- mnthintrest;
temp = temp - principlePaidPerMonth; // reducing the principle amount paid before printing
System.out.println("\nAmount left after payment "+monthNumber+" is:" + temp);
System.out.println("This month intrest is:" + mnthintrest);
System.out.println("Principle paid is:" + principlePaidPerMonth);
monthNumber++;
}
// text to be printed could be different
It is a good practice to keep variable names as meaningful as possible and to declare the variables as much closer to their first use.
So you could declare the variables for interest and interest rate just at the time of initializing above where the while loop part starts.
double mintrestrate = intrestrate/12;
double mnthintrest = lamnt*mintrestrate;
For formatting, you could use System.out.printf() instead of println - this could help format the number of digits shown after decimal
For getting precision - you could use absolute/ceiling functions available in Math class.

Imperial to kg converter

An exercise on my problem worksheet asks us to write a method public static double imperialToKg(double ton, double once, double drachm, double grain) that converts masses given in the imperial system to kg.
We've been given a conversion table for this but what I don't understand, being completely new to java, is HOW can I get my method to differentiate between these input arguments?
For example if I want the method to return the kg value of 11 stone what's to stop it from returning the value of 11 tons (tons being the first argument)
public class W1_E2{
public static double imperialToKg(double ton, double hundredweight, double quarter, double stone, double pound, double once, double drachm, double grain){
ton = 1016.04691;
hundredweight = 50.8023454;
quarter = 12.7005864;
stone = 6.35029318;
ounce = 0.02834952;
drachm = 0.00177185;
grain = 0.0000648;
}
}
I've listed the conversions as variables but I don't know what to do with them...
For 11 stone, you would have to call that like:
returnedFoo = imperialToKg(0,0,0,11,0,0,0);
If you want to call it with a value of 11 tons, you use:
returnedFoo = imperialToKg(11,0,0,0,0,0,0);
For our stone example, try:
On the implementation end, you would use something like:
public static double imperialToKg(double ton, double hundredweight, double quarter, double stone, double pound, double once, double drachm, double grain){
{
double kg = (ton * 1016.04691) + (hundredweight * 50.8023454) + (quarter * 12.7005864) + (stone * 6.35029318) + (ounce * 0.02834952) + (drachm * 0.00177185) + (grain * 0.0000648);
return kg;
}
This is quick and dirty; there is a multitude of better ways to do this, please confirm that the exercise is actually requesting we call the function like this.
Nowhere does it state that you require one method to make all your conversions, but that you require a main method to test your code.
So, make an individual method for each type of conversion required, as an example:
public static double tonToKg(double val){
return val * 1016.04691;
}
To test:
public static void main(String[] args){
System.out.println(tonToKg(11));
}

Cannont Find Symbol Error, Incompatible Types

Hello I am attempting to write a program that calculates a future investment value using a fixed rate and I am having issues with my variables. Any help would be much appreciated thank-you ahead of time!
/**
* NAME:
* DATE: November 3, 2015
* FILE:
* COMMENTS: This program caculates a future investment value using a fixed rate
*/
import java.util.Scanner;
public class lab12
{
public static void main(String[] args)
{
//declare variables
double yearlyInterstRate;
double monthlyInterestRate;
double monthlyInvestmentAmount;
double years;
double months;
//Create Scanner Object
Scanner keyboard= new Scanner(System.in);
//Get Investment Information
System.out.print("Hello we will be caculating the future of your fixed monthly investment, I will need to collect some information from you.");
System.out.print("What is your monthly investment amount?");
monthlyInvestmentRate=keyboard.nextLine();
System.out.print("How many years wil you be investing for?");
years=keyboard.nextLine();
System.out.print("What is your yearly interest rate?");
yearlyInterestRate=keyboard.nextLine();
//Caculate the future rate
{
months=years*12;
monthlyInterestRate=yearlyInterestRate/12/100;
futureValue= CaculateFuturevalue(monthlyInvestedAmount,monthlyInterestRate,months);
System.out.print("Your future value is $"+futureValue);
}
} //Close Main
} //close lab12
You have a misspelling in variables.
You have declared yearlyInterstRate but you're using yearlyInterestRate, so you need to use the variables as they were declared.
also you need to use monthlyInvestmentAmount not monthlyInterestRate as well.
This code will do:
public class lab12
{
public static void main(String[] args)
{
//declare variables
double yearlyInterstRate;
double monthlyInterestRate;
double monthlyInvestmentAmount=0; // you forgot to initialize this value
double years;
double months;
double futureValue;
//Create Scanner Object
Scanner keyboard= new Scanner(System.in);
//Get Investment Information
System.out.print("Hello we will be caculating the future of your fixed monthly investment, I will need to collect some information from you.");
System.out.print("What is your monthly investment amount?");
monthlyInterestRate=keyboard.nextDouble();
System.out.print("How many years wil you be investing for?");
years=keyboard.nextDouble();
System.out.print("What is your yearly interest rate?");
yearlyInterstRate=keyboard.nextDouble();
//Caculate the future rate
months=years*12;
monthlyInterestRate=yearlyInterstRate/12/100;
futureValue= caculateFuturevalue(monthlyInvestmentAmount,monthlyInterestRate,months);
System.out.print("Your future value is $"+futureValue);
}
}
Now some improvements:
use nextDouble() instead of nextLine(), bacause your variables are double, not String.
name your class from upperCase, so Lab12, and not lab12
argumen validation would be nice (check if given values are grater than zero)

How do I add fines?

I am new to coding and was wondering how would I go about coding this fine? I am pretty sure I am going about it the wrong coding way if anyone could help that would be greatly appreciated.
Below is what is expected:
The fine will be a dollar value, which is a double data type. ParkingTicket will not have a double-typed fine variable. Instead, it calculates the fine on-demand, using the minutesPaid and minutesParked variables.
Impark levies a flat-rate fine of $20 (always), plus $10 aggravated penalties for every whole hour (60 minutes) parked beyond the paid amount. As a Canadian institution, Impark is also obligated to add the 5% Goods and Services Tax surcharge. A surcharge is multiplied after all other sums have been calculated.
You are responsible for producing the result of this calculation in calculateFine().
So far this is what I have, :
public static double calculateFine()
{
double meterMinutesPaidWithTax = 20*0.05;
double meterMinutesPaid = 20;
double pentalty = 10;
double tax = 0.05;
double overParked = (carMinutesParked+=1);
if(carMinutesParked<=carMinutesParked){
return meterMinutesPaidWithTax = meterMinutesPaidWithTax+meterMinutesPaid;
}
else if(carMinutesParked>overParked){
return meterMinutesPaid = (meterMinutesPaid + pentalty)*tax+(meterMinutesPaid + pentalty);
}
else{
return meterMinutesPaidWithTax;
}
}

Java Error: first type: double, second type: String

I just started learning Java programming, and received this error on my first project in the last part, "fee before taxes" I must be messing up my variables, but I am not sure. Any ideas?
This is the error I receieved on the compiler:
error: bad operand types for binary operator
first type: double
second type: String
2 errors
import java.util.Scanner;
public class project1Naja {
public static void main(String[] args) {
String firstName; // To hold first name
String lastName; // To hold last name
String hours; // Child's hours
final String date; // Date of Service
final double RATE; // Hourly rate
final double TAX_RATE; // Tax percentage
int fee; // Cost before tax added
int taxAmount; // Tax total
double totalFee; // Fee including tax
// Scanner created to read input.
Scanner childCare = new Scanner(System.in);
System.out.print("Enter your first name: " );
firstName = childCare.nextLine();
System.out.print("Enter your last name: " );
lastName = childCare.nextLine();
System.out.print("Enter the child's hours here: " );
hours = childCare.nextLine();
System.out.print("Enter date here: " );
date = childCare.next();
System.out.println("Child Care Service Bill For: " + firstName
+ lastName);
System.out.println("Date of Service: " + date);
System.out.println("Number of hours: " + hours);
System.out.println("Fee before taxes: " = RATE * hours);
}
}
You need to initialize local variables before accessing them,
in this case RATE is local variable which is uninitialized at the time it is being accessed
System.out.println("Fee before taxes: " = RATE * hours);
initialize it by
final double RATE = 0.50; // some rate value
and also String cannot be multiplied with double
2 things to note here..
String hours;
hours is string so you cannot multiply any variable with a string
System.out.println("Fee before taxes: " = RATE * hours);
wrong syntax... it should be System.out.println("Fee before taxes: =" + RATE * hours);
also RATE and whatever you multiply with it plz initialize both.
Your code doesn't compile because Firstly the = out of " " is for assignement, so the first thing to do is to keep it inside the "Fee before taxes: ".
Second, you can't use the Multiplication Operator * between String and a double, in order to do that you need to parse the String like that: Double.parseDouble(hours).
Third, you need to initialize all local variables (final or not) before using them as they don't have default values in Java, you can learn mor about local variables from the Java docs.
It's also detailed in the Definite Assignment:
For every access of a local variable or blank final field x, x must be
definitely assigned before the access, or a compile-time error occurs.
So, for your example, the only variable used before assignement is RATE, so you don't have to initialize the others:
final double RATE = 0; // for example
At the end, your code must look something like this:
import java.util.Scanner;
public class project1Naja {
public class project1Naja {
public static void main(String[] args) {
String firstName; // To hold first name
String lastName; // To hold last name
String hours; // Child's hours
final String date; // Date of Service
final double RATE = 0; // Hourly rate
final double TAX_RATE = 0; // Tax percentage
int fee; // Cost before tax added
int taxAmount; // Tax total
double totalFee; // Fee including tax
// Scanner created to read input.
Scanner childCare = new Scanner(System.in);
System.out.print("Enter your first name: ");
firstName = childCare.nextLine();
System.out.print("Enter your last name: ");
lastName = childCare.nextLine();
System.out.print("Enter the child's hours here: ");
hours = childCare.nextLine();
System.out.print("Enter date here: ");
date = childCare.next();
System.out.println("Child Care Service Bill For: " + firstName
+ lastName);
System.out.println("Date of Service: " + date);
System.out.println("Number of hours: " + hours);
System.out.println("Fee before taxes: " + RATE
* Double.parseDouble(hours));
}
}
There are three things here that make it so your code cannot correctly compile.
You defined hours as a String. This would be ok if you were only looking to display the string without manipulating it or combining it with another string. However, this line:
System.out.println("Fee before taxes: " = RATE * hours);
is trying to tell the compiler to multiply a type String with a type double. You cannot do this in java. Hours will have to be defined as either a double to match your RATE, or as a byte, int, short, long or float. Keep in mind that if you want partial hours (such as .5 hours) you will need to use either double or float, since these are the only two primitive data types that can be manipulated with decimals without adding a cast type.
Alternatively, you can parse the String as a double with something that looks like Double.parseDouble(hours), but this is an indirect "work-around" way of dealing with the issue, so I recommend changing the type of hours instead.
Whenever you declare a final of any data type in java, you must assign it a value as well. You cannot simply leave it undefined as you have in your list of variables. It should say something along the lines of
final double RATE = 7.2;
Because of this when you try the line:
System.out.println("Fee before taxes: " = RATE * hours);
the compiler calls the final which has not yet been declared, and therefor a compilation error occurs. Variables on the other hand, can remain uninitiated but they must be assigned a value that matches their data type before they are actually referenced in lines of code. If they are not you will get a compilation error.
In your final print statement you have ("Fee before taxes" = RATE * hours).
This is a simple syntax error. You can never have the operand = in a print statement. The only operand allowed (for this basic case's sake) is + to add more text to the string. This line should read:
System.out.println("Fee before taxes" + (RATE * hours));
IN SHORT :
Change your variable hours to type double, assign your final RATE to a number, and change the syntax error in your final print statement. After that you should have smooth sailing.
P.S.
I also noticed you have two more finals called "date" and "TAX_RATE". These should be declared as well, otherwise you will come across similar errors when implementing them.
Hope this helps!

Categories

Resources