I have looked through some of the other questions asking about a similar issue, but I am trying to call the double 'thirdPrice' from calculationMethod() to main(). The purpose of this program is to request data in main(), pass some of the info to calculationMethod() and then return that data back to main() for final output. I am using DrJava, here is my code so far.
import java.util.Scanner; //Imports input device
public class CraftPricing
{
public static void main(String[] args)
{
Scanner inputDevice = new Scanner(System.in); //Sets up input device
String productName; //Used for naming product
double costMaterials, hoursWorked; //Gives variables decimal format
System.out.println("Enter the name of the product "); //Enter product name
productName = inputDevice.nextLine(); //Passes variable for calculation
System.out.println("Enter the cost of materials prior to discount "); //Enter cost of materials
costMaterials = inputDevice.nextDouble(); //Passes variable for calculation
System.out.println("Enter the number of hours worked "); //Enter hours worked
hoursWorked = inputDevice.nextDouble(); //Passes variable for calculation
System.out.printf("The cost of " + productName + " is %.2f\n" , thirdPrice);
//Output product name and cost
}
public static void calculationMethod() //Method used to calcualte price
{
double itemDiscount = 0.75; //Gives decimal format to variable
double payRate = 14.00; //Gives decimal format to variable
double shipHandle = 6.00; //Gives decimal format to variable
double firstPrice = payRate * 7; //Calculates fisr portion of equation
double secondPrice = 7 + firstPrice; //Calculates second portion of equation
final double thirdPrice = itemDiscount * secondPrice + shipHandle;
//Calculates final portion of equation
return thirdPrice; //Returns double to main() for output
}
}
The errors I receive when trying to compile are as follows:
2 errors found:
File: C:\Users\unkno\DrJava\Java\CraftPricing.java [line: 18]
Error: cannot find symbol
symbol: variable thirdPrice
location: class CraftPricing
File: C:\Users\unkno\DrJava\Java\CraftPricing.java [line: 28]
Error: incompatible types: unexpected return value
Why do you need a variable at all?
Call the method.
System.out.printf("The cost of %s is %.2f\n" , productName, calculationMethod());
Or learn about variable scope.
And also fix the return type.
public static double calculationMethod()
Related
I'm trying to divide variables from pointsearned and creditsearned method in the pointsaverage method but it gives "Your grade point average isNaN" when i run it , how do i fix this ?(I'm a beginner)
public class JavaApplication40 {
static Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
double credits = 0;
double Points = 0;
double average = 0;
IDnumber();
CreditsEarned(credits);
PointsEarned(Points);
System.out.println("Your grade point average is" + PointAverag(average, Points, credits));
}
public static void IDnumber(){
String docNuMBER;
System.out.println("Enter your student ID number ");
docNuMBER = keyboard.nextLine();
}
public static double CreditsEarned( double credits){
double NumCreditsEarned;
System.out.println("Enter your Credit hours earned");
NumCreditsEarned = keyboard.nextDouble();
return NumCreditsEarned;
}
public static double PointsEarned(double points){
double NumberOpoints;
System.out.println("Enter your credit points");
NumberOpoints = keyboard.nextDouble();
return NumberOpoints;
}
public static double PointAverag(double grade , double NumberOpoints ,
double NumCreditsEarned) {
double average ;
average = NumberOpoints/NumberOpoints;
return average ;
Here's what's happening in your program:
You set 'credits' and 'points' to 0.
These two variables have not been modified when you get to pass them to 'pointAverag'
System.out.println("Your grade point average is" + PointAverag(average, Points, credits));
this line, literally, does this:
System.out.println("Your grade point average is" + PointAverag(0, 0, 0));
And eventually leads to:
average = 0/0
in 'PointAverag' which is NAN when stored in a double.
Watch out for this line:
average = NumberOpoints/NumberOpoints;
it has logical mistake in it. It will always store either 1 or NAN.
As mentionned in the comments, you need to update those variables, 'credits' and 'points', by storing the returned value of your methods 'PointsEarned' and 'CreditsEarned' in them:
CreditsEarned(credits);
PointsEarned(Points);
Becomes
credits = CreditsEarned(credits);
points = PointsEarned(Points);
Hope this helps.
Write:
System.out.println("Your grade point average is" + PointAverag(IDnumber(), PointsEarned(Points), CreditsEarned(credits)));
instead.
If you don't use a returned value, it gets discarded.
I think I did it all correct however im having an error. Very confused.
Error: overtime.java:10: error: variable pay might not have been initialized
displayResults(pay);
Code:
import java.util.Scanner;
public class Overtime {
public static void main(String[] args) {
int hours;
double rate, pay;
Scanner in = new Scanner(System.in);
displayResults(pay);
System.out.println();
System.out.print( "Enter how many hours worked: " );
hours = in.nextInt();
System.out.print( "Enter hourly rate: " );
rate = in.nextDouble();
}
public double calculatePay( int hours, double rate, double pay ) {
if ( hours > 40 ) {
int extraHours = hours - 40;
pay = ( 40 * rate ) + ( extraHours * rate * 1.5);
} else
pay = hours * rate;
return pay;
}
public static void displayResults(double pay) {
System.out.printf( "\nGross Salary: %f", pay);
}
}
The code inside your main has to reordered:
public static void main(String[] args) {
int hours;
double rate, pay;
Scanner in = new Scanner(System.in);
System.out.print( "Enter how many hours worked: " );
hours = in.nextInt();
System.out.print( "Enter hourly rate: " );
rate = in.nextDouble();
pay = ;// call calculatePay here
displayResults(pay);
}
And you have to remove the pay parameter of the calculatePay method. Its declaration should be
public static double calculatePay( int hours, double rate )
The reason you get this error is the fact you didn't assign any value to variable payand you called a method displayResults() which needs this variable as an argument. Firstly you should calculate pay value with calculatePay (but you should delete double pay from list of arguments passed to this method, because there is no need to place it there).
After calculations made with calculatePay() and having its result in pay variable you can call displayResults() without problem.
Another problem is that calculatePay() need to made static and both your methods should be declared outside of the main() method body (the bold part of my answer is no longer relevant, because bad looking indentation made me a bit confused and I thought that methods were declared inside the main() method).
This looks a bit like a homework. So Iam providing only guidance:
Initialize all variables first and set them to values. (eg. double pay=1; ) and drop the Scanner.
Once this is working - add the Scanner and display all variables with System.out.format(...).
Once vars are displayed properly (point2) and (1)works - connect variables set by the Scanner with rest of your code
Good luck! :-)
I am a new Java student and am writing a program that consists of a main method, a class file, two input .txt files, and an output.txt file. The main method should ask the user what the account balance and annual interest is and import deposit and withdrawal information from their respective files, and then to display all calculations from the class file in an output file.
I had originally written this file to ask users for all of this input using the scanner and now I'm trying to get it to work using files as input...which is not going so well.
Main method:
import java.util.Scanner;
import java.io.*;
public class SavingsAccountDemo {
public static void main(String[] args) {
//declare variables
double interest;
double startAmount;
double amountDeposit;
double amountWithdraw;
double d, w;
String filenameInputW, filenameInputD, filenameOutput;
PrintWriter oFile;
File wFile, dFile;
Scanner iFile;
Scanner key = new Scanner(System.in);
//get initial balance
System.out.println("Enter initial account balance: ");
startAmount = key.nextDouble();
//create SavingsAccount class object sending starting amount to constructor
SavingsAccount money = new SavingsAccount(startAmount);
//get annual interest rate
System.out.println("Enter annual interest rate: ");
interest = key.nextDouble();
//send interest rate to class
money.setInterest(interest);
//Retrieve withdrawals from withdrawal.txt
filenameInputW="withdrawal.txt";
wFile = new File (filenameInputW);
iFile = new Scanner (wFile);
while(iFile.hasNext())
{
double num;
num=iFile.nextDouble();
amountWithdraw += num;
if(amountWithdraw >= 0.1)
w++;
}
//send to SavingsAccount class
money.withdraw(amountWithdraw);
//Retrieve deposits from deposit.txt
filenameInputD="deposit.txt";
dFile = new File (filenameInputD);
iFile = new Scanner (dFile);
while(iFile.hasNext())
{
double num;
num=iFile.nextDouble();
amountDeposit += num;
if (amountDeposit >= 0.1)
d++;
}
//send to SavingsAccount class
money.deposit(amountDeposit);
//display retults
filenameInputW="output.txt";
oFile=new PrintWriter (filenameOutput);
oFile.println("The ending balance is: " + money.getBalance());
oFile.println("The total amount of withdrawls are: " + w);
oFile.println("The total amount of deposists are: " + d);
oFile.println("The annual interest rate is: " + money.getInterest());
}
}
My class file
/**
* #(#)SavingsAccount.java
*
*
* #author
* #version 1.00 2013/5/6
*/
public class SavingsAccount {
//variables
private double interest;
private double balance;
//Constructor
public SavingsAccount(double b)
{
balance = b;
interest = 0.0;
}
//Accessors
public void setInterest(double i)
{
interest = i;
}
public void setBalance(double b)
{
balance = b;
}
//Mutators
public double getInterest()
{
return interest;
}
public double getBalance()
{
return balance;
}
//Withdraw method
public void withdraw(double withdraw)
{
balance = balance - withdraw;
}
//Deposit method
public void deposit(double deposit)
{
balance = balance + deposit;
}
//Adding monthly interest to the balance
public void addInterest()
{
double x = ((interest/12) * balance);
balance = balance + x;
}
}
I get these errors:
--------------------Configuration: --------------------
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:43: error: variable amountWithdraw might not have been initialized
amountWithdraw += num;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:46: error: variable w might not have been initialized
w++;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:50: error: variable amountWithdraw might not have been initialized
money.withdraw(amountWithdraw);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:62: error: variable amountDeposit might not have been initialized
amountDeposit += num;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:65: error: variable d might not have been initialized
d++;
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:69: error: variable amountDeposit might not have been initialized
money.deposit(amountDeposit);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:73: error: variable filenameOutput might not have been initialized
oFile=new PrintWriter (filenameOutput);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:75: error: variable w might not have been initialized
oFile.println("The total amount of withdrawls are: " + w);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:76: error: variable d might not have been initialized
oFile.println("The total amount of deposists are: " + d);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:37: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
iFile = new Scanner (wFile);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:55: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
iFile = new Scanner (dFile);
^
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:73: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
oFile=new PrintWriter (filenameOutput);
^
12 errors
Process completed.
I'm not looking for handouts, this is my first post for help here but I know you guys wont solve this for me...I just need to learn how to do this properly. I just have no idea why the initialization is having a problem (all mentioned variables are initialized) and the files are located in the same folder.
I think you are confused about the difference between initialization and declaration. The variables that give errors are indeed declared, but they don't have an initial value.
Take a look at w++. This means: add 1 to w. But what is w? You didn't define that.
The same problem is true for d, amountWithdraw and amountDeposit
Also, new scanners with a file as input need a try-catch statement for a FileNotFoundException.
Finally, I think you meant filenameOutput="output.txt"; in stead of filenameInputW="output.txt";
--------------------Configuration: --------------------
C:\Users\Home\Documents\JCreator Pro\MyProjects\SavingsAccount\src\SavingsAccountDemo.java:43: error: variable amountWithdraw might not have been initialized
amountWithdraw += num;
Well, you declared variable amountWithdraw as double, but compilator don't know what is value of this variable and he can't add num. So after declaration you need to initialize amountWithdraw. It can be like this:
amountWithdraw = 0;
It's so simple.
From your code you write the following at the very top: double amountWithdraw; and that's it. This is not an initialization, but a declaration.
The same applies if your girlfriend starts talking about kids, right? If she declares "I want kids" it's not the same as if she "initializes" (gives birth to) a baby. Both might be equally stressful, but in different ways.
You need to either type double amountWithdraw = 0.0; or add the following before modifying the value: amountWithdraw = 0.0;. That will fix the first of your handful of problems.
Edit: For the wrongs...
You should be giving those variables values when you declare them. i.e. int w = 0 etc.
Dirty quick fix: As for the other exception-related errors, for simplicity you can just put public static void main(String[] args) throws FileNotFoundException to get things working in the interim.
Proper fix: Usually though, you should look to handle a FileNotFoundException in a catch block, as it's not good practice to rethrow exceptions willy-nilly.
I have some code which I find to keep giving me a dividing by 0 error.
It is suppose to calculate the monthly payment amount!
import java.io.*;
public class Bert
{
public static void main(String[] args)throws IOException
{
//Declaring Variables
int price, downpayment, tradeIn, months,loanAmt, interest;
double annualInterest, payment;
String custName, inputPrice,inputDownPayment,inputTradeIn,inputMonths, inputAnnualInterest;
BufferedReader dataIn = new BufferedReader(new InputStreamReader(System.in));
//Get Input from User
System.out.println("What is your name? ");
custName = dataIn.readLine();
System.out.print("What is the price of the car? ");
inputPrice = dataIn.readLine();
System.out.print("What is the downpayment? ");
inputDownPayment = dataIn.readLine();
System.out.print("What is the trade-in value? ");
inputTradeIn = dataIn.readLine();
System.out.print("For how many months is the loan? ");
inputMonths = dataIn.readLine();
System.out.print("What is the decimal interest rate? ");
inputAnnualInterest = dataIn.readLine();
//Conversions
price = Integer.parseInt(inputPrice);
downpayment = Integer.parseInt(inputDownPayment);
tradeIn = Integer.parseInt(inputTradeIn);
months = Integer.parseInt(inputMonths);
annualInterest = Double.parseDouble(inputAnnualInterest);
interest =(int)annualInterest/12;
loanAmt = price-downpayment-tradeIn;
//payment = loanAmt*interest/a-(1+interest)
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
//Output
System.out.print("The monthly payment for " + custName + " is $");
System.out.println(payment);
// figures out monthly payment amount!!!
}
}
the problem occurs when attempting to set the payment variable.
i don't understand why it keeps coming up with dividing by 0 error.
You have declared your variables as Int so 1/interest and 1/(interest*Math.pow(1+interest,-months)) will return 0. Change the type of your variables to float or double.
One suggestion to you, is that you should learn to "backwards slice" your code.
This means that when you see that you're getting a DivideByZeroException you should look at your code, and say, "why could this happen?"
In your case, let's look at this:
payment=(loanAmt/((1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
So, now, Math.pow will never return anything zero (as it's a power), so it must be the case that interestis zero. Let's find out why:
interest =(int)annualInterest/12;
So now, integer division in Java truncates. This means that if you have .5 it will be cut off, and turned into zero. (Similarly, 1.3 will be truncated to 0).
So now:
annualInterest = Double.parseDouble(inputAnnualInterest);
This implies that you are passing in something that gets parsed to a value that is less than 12. If it were greater than 12 then you would get something else.
However, you might just be passing in an invalid string, for example, passing in "hello2.0" won't work!
This will be rounding always to 0. So it is trowing exception.
(1/interest)-(1/(interest*Math.pow(1+interest,-months)))));
Use float type instead of int. Learn how they works.
package computeloan;
import java.util.Scanner;
public class ComputeLoan {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print(" Enter Yearly Interest Rate : ");
double annualIntersetRate = input.nextDouble();
double monthlyIntersetRate = annualIntersetRate / 1200;
System.out.print(" Enter Number of years : ");
int numberOfYears = input.nextInt();
// Enter loan amount
System.out.print(" Enter Loan Amount : ");
double loanAmount = input.nextDouble();
double monthlyPayment = loanAmount * monthlyIntersetRate /(1-1/Math.pow(1+monthlyIntersetRate,numberOfYears*12 ));
double totalPayment = monthlyPayment * numberOfYears * 12;
//Calculate monthlyPaymeent and totalPayment
System.out.println(" The Monthly Payment Is : " +(int)(monthlyPayment*100) /100.0);
System.out.println(" The Total Payment Is : " +(int)(totalPayment*100) /100.0 );
}
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
// Inventory.java part 1
// this program is to calculate the value of the inventory of the Electronics Department's cameras
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Inventory
{
public void main(String[] args)
{
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
while(true){ // infinite loop
// make new Camera object
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
System.out.print("Enter Department name: "); //prompt
String itemDept = input.nextLine(); // read name from user
if(itemDept.equals("stop")) // exit the loop
break;
while(true){
System.out.print("Enter item name: "); // prompt
String name = input.nextLine(); // read first number from user
input.nextLine();
if(name != ("camera"))
System.out.print("Enter valid item name:"); // prompt
name = input.nextLine(); // read first number from user
input.nextLine();
break;
}
System.out.print("Enter number of items on hand: "); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
while( itemStock <= -1){
System.out.print("Enter positive number of items on hand:"); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
System.out.print("Enter item Price: "); // prompt
itemPrice = input.nextDouble(); // read second number from user
input.nextLine();
while( itemPrice <= -1){
System.out.print("Enter positive number for item price:"); // prompt
itemPrice = input.nextDouble(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
totalValue = itemStock * itemPrice; // multiply numbers
System.out.println("Department name:" + itemDept); // display Department name
System.out.println("Item number: " + camera.getItemNumber()); //display Item number
System.out.println("Product name:" + camera.getName()); // display the item
System.out.println("Quantity: " + camera.getItemStock());
System.out.println("Price per unit" + camera.getItemPrice());
System.out.printf("Total value is: $%.2f\n", camera.getTotalValue()); // display product
} // end while method
} // end method main
}/* end class Inventory */
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
private Cam(String name, int itemNumber, int itemStock, double itemPrice, double totalValue) {
this.name = name;
this.itemNumber = itemNumber;
this.itemStock = itemStock;
this.itemPrice = itemPrice;
this.totalValue = totalValue;
}
public String getName(){
return name;
}
public double getTotalValue(){
return itemStock * itemPrice;
}
public int getItemNumber(){
return itemNumber;
}
public int getItemStock(){
return itemStock;
}
public double getItemPrice(){
return itemPrice;
}
}
This is the output when I try to compile this code:
C:\Java>javac Inventory.java
Inventory.java:25: error: cannot find symbol
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
symbol: variable name
location: class Inventory
Inventory.java:98: error: cannot find symbol
this.totalValue = totalValue;
^
symbol: variable totalValue
2 errors
I don't understand why I keep getting these errors. I feel like I am close to finishing the problem, but find that I need help getting over this bit of the problem.
Okay, I have made a few changes, but now I get these errors:
C:\Java>javac Inventory.java
Inventory.java:68: error: variable itemNumber might not have been initialized
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
Inventory.java:68: error: variable totalValue might not have been initialized
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
2 errors
You have declared a variable totalValue inside the main function of the Inventory class. It is not available for class Cam as an instance (this) variable.
Your missing declaration for the variable name in main.
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
String name; //missing declaration
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
Also:
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
private double totalValue; //missing field
private Cam(String name, int itemNumber, int itemStock, double itemPrice, double totalValue) {
The constructor is private.
Your are also missing static in your main method.
The two errors are pretty simple:
First:
Inventory.java:25: error: cannot find symbol
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
symbol: variable name
location: class Inventory
This sais it cannot find the variable called name, which is true. There is no name variable in the scope when you try to construct the Cam. We know you have a name variable a bit further, but that does not work, because the variable isn't in the scope of the newstatement.
Second:
Inventory.java:98: error: cannot find symbol
this.totalValue = totalValue;
^
symbol: variable totalValue
It sais it can't find a value called totalValue in the Cam class, which is true as well. Check out the member list of Cam and you will see that there is no totalValue. I guess you want to remove it from the constructor, because you are calculating total value depending on itemStock and itemPrice.
Notes:
If you solved this, (and probably more compilation errors) you will notice that your application will compile, but not run. This is because of you forget to declare your main-method static.
If you have solved this you will notice that all the Cam objects you constructed, will contain the data you entered for the previous Cam. This is because of you are constructing the Cam before prompting the data. You started good: Declare fields for the data you want to prompt. When the user entered all the data of one Camera, construct the Camera.
There are two classes in your file
Inventory
Cam
You need to define
variable name in Class Inventory
variable totalValue in Class Cam
Also your in Inventory.java the call to Cam constructor seems to be at a wrong place, you might want to make it the last line of While loop