Java Error Incompatible data types: possible lossy conversion from double to int - incompatibletypeerror

I'm trying to make a class. Part of the class is to calculate the shipping costs to an order. If the order the order is $0 - $50.00 then the shipping charge is 8% of the subtotal cost of the order. Else if the order is over $50.00 shipping is free. So I coded this so far, but I'm getting the error:
public class Order
{
private double salesTaxRate;
private double subTotal;
private double shipCost;
private double salesTax;
private double total;
//Constructor to set sales tax rate
public Order( double taxRate)
{
salesTaxRate = taxRate;
subTotal = 0;
shipCost = 0;
salesTax = 0;
total = 0;
}//End constructor
public int setCost(double subTotal)
{
if(subTotal == 0 || subTotal <= 50.00)
{
shipCost = subTotal * 0.08;
return shipCost;
}
else
{
shipCost = 0;
return shipCost;
}
}//End setCost method
I know what the error is, I just don't understand why I'm getting it. I am still new to programming so I ask for your patience. But any help would be appreciated.

Related

How to use Cadence/Temporal versioning API( workflow.getVersion) in a loop

Imagine this workflow of 10 activities in a loop:
public class LoopWorkflowImpl implements LoopWorkflow{
private final Api api = Workflow.newActivityStub(Api.class, ...)
#override
public int start(){
int sum = 0;
for(int i=0; i<10; i++){
sum += api.getCount();
}
return sum;
}
}
How can I change api.getCount() to api.getCountV2() for existing workflows?
E.g. if there is workflow already completed 5 activities with api.getCount(), how can let let it use api.getCountV2() for the rest 5 activities?
Correct Way to apply new behavior for old and new workflow
This is what you should do -- using the versioning API with changeId for each iteration:
public class LoopWorkflowImpl implements LoopWorkflow{
private final Api api = Workflow.newActivityStub(Api.class, ...)
#override
public int start(){
int sum = 0;
for(int i=0; i<10; i++){
int version = Workflow.getVersion("useV2API"+i, Workflow.DEFAULT_VERSION, 1)
if( version == 1){
sum += api.getCountV2();
}else{
sum += api.getCount();
}
}
return sum;
}
}
Below will only apply for new workflows
Many people will do this instead and it won't work for the existing workflow
public class LoopWorkflowImpl implements LoopWorkflow{
private final Api api = Workflow.newActivityStub(Api.class, ...)
#override
public int start(){
int sum = 0;
for(int i=0; i<10; i++){
int version = Workflow.getVersion("useV2API", Workflow.DEFAULT_VERSION, 1)
if( version == 1){
sum += api.getCountV2();
}else{
sum += api.getCount();
}
}
return sum;
}
}
Why
This is because of an important contract of Workflow.getVersion() API --
The return value from the API for the same changeId is immutable once returned. This is guaranteed with or without the version is being written into history using MarkerRecord event.
So in the 2nd solution , on the first iteration, Workflow.getVersion() will returns Workflow.DEFAULT_VERSION(-1) as there is no version marker during replay. So in the rest iteration, it will always return Workflow.DEFAULT_VERSION.
The best way to fix is to include the iteration Id into the changeId. Using the different changeId will allow the versioning to pick different version for different iteration.
If you are worried about this will create too many version marker events in the history, you can combine this solution with the global versioning pattern to only do this for old workflows:
public class LoopWorkflowImpl implements LoopWorkflow{
private final Api api = Workflow.newActivityStub(Api.class, ...)
private GlovalVersionProvider globalVersionProvider = GlobalVersionProvider.get();
#override
public int start(){
if (globalVersionProvider.isAfterVersionOfUsingGlobalVersion()) {
GlobalVersionProvider.upsertGlobalVersionSearchAttribute();
}
int sum = 0;
for(int i=0; i<10; i++){
if (globalVersionProvider.isAfterVersionOfUsingV2Api()) {
sum += api.getCountV2();
}else{
int version = Workflow.getVersion("useV2API"+i, Workflow.DEFAULT_VERSION, 1)
if( version == 1){
sum += api.getCountV2();
}else{
sum += api.getCount();
}
}
}
return sum;
}
}
So the the versioning marker with iteration index is only applying for existing old workflow executions.

Unity-Press Button to slowly increment number

I'm trying to do something like the old GTA style money system like in Gta vice city or san andreas. So when you add or obtain money, the number doesn't just jump to the result. It slowly increments till the value added is done.
I want to do this by clicking buttons, so one button will add 100 dollars and other will subtract 100 dollars and so on.
The buttons don't seem to be playing nice with update and Time.deltatime.
To slowly increment a number over the time, you can do something like this:
public float money = 100;
public int moneyPerSecond = 25;
public int moneyToReach = 100;
bool addingMoney = false;
private void Update()
{
if (addingMoney)
{
if (money < moneyToReach)
{
money += moneyPerSecond * Time.deltaTime;
}
else { addingMoney = false; money = Mathf.RoundToInt(money); }
}
}
public void addMoney()
{
moneyToReach += 100;
addingMoney = true;
}

Double Values Not Showing Calculated Values

I'm trying to calculate the payment term for the user. I try to crunch the numbers and spit them out, but that's not happening for some reason. However, it displays perfectly fine when I explicitly assign the variables a value while declaring them.
public static void creditCardPaymentCalculator()
{
//User Input Variables
Scanner userInput = new Scanner(System.in);
//User's Input
double purchaseAmount, interestAmount = 0, minimumMonthlyPayment;
//Table Counters
int[] month = new int[12];
double payment = 0;
double monthlyInterest = 0;
double principal = 0;
double remainingBalance = 0;
double yearsOfPayment = 0;
int yearCounter = 1;
int monthCounter = 0;
//Initialize Variables
//-------------------------------------------------------------------------
//Initialize Month Array
for (int i = 0; i < 12; i++)
{
month[i] = (i + 1);
}
//-------------------------------------------------------------------------
//Welcome Message
System.out.println("\n\n\n\nCredit Card Payment Calculator\n\n");
//Get User Input
System.out.println("Enter Your Purchase Amount");
purchaseAmount = userInput.nextDouble();
System.out.println("Enter Interest Amount");
interestAmount = userInput.nextDouble();
System.out.println("Enter Minimum Monthly Payment");
minimumMonthlyPayment = userInput.nextDouble();
//Calculate Input For Chart (Not Working)
payment = minimumMonthlyPayment;
monthlyInterest = (((interestAmount / 100) * remainingBalance / yearsOfPayment) / 12);
principal = payment - monthlyInterest;
remainingBalance = remainingBalance - principal;
//Calculate Number Of Years For Payment
yearsOfPayment = (((interestAmount / 100) * remainingBalance) + remainingBalance) / minimumMonthlyPayment;
//Output
System.out.printf("\n Year: %d/%.0f", yearCounter, yearsOfPayment);
System.out.printf("\nMonth Payment Interest Principal Remaining Balance");
System.out.printf("\n%d %.2f %.2f %.2f %.2f", month[monthCounter], payment, monthlyInterest, principal, remainingBalance);
//Increment Counters
monthCounter++;
if (month[monthCounter] == 12)
{
yearCounter++;
//Reset monthCounter
monthCounter = 0;
}
//Line Spacing
System.out.printf("\n\n\n\n\n");
}

Does one need getters and setters for calculation methods?

import javax.swing.JOptionPane;
public class BeerStoreBP
{
private String name;
private double custAge;
private double numBeers = 0;
private double beerDisc = 0;
private double beerType = 0;
private double theBeerBrand;
private double total = 0;
private double beer = 0;
public void setAge(double theAge)
{
custAge = theAge;
}
public void setName(String theName)
{
name = theName;
}
public void setNumBeers(double theNumBeers)
{
numBeers = theNumBeers;
}
public void setBeerType(double theBeerType)
{
beerType = theBeerType;
}
public double getAge()
{
return custAge;
}
public String getName()
{
return name;
}
public double getNumBeers()
{
return numBeers;
}
public double calcNumBeersValid()
{
String numBeersStr;
while (numBeers < 3 || numBeers > 6)
{
numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 " +
"beers");
numBeers = Double.parseDouble(numBeersStr);
}
return numBeers;
}
public double calcBeerPrice()
{
final double LAGIMRED = 1.90;
final double DESINIPA = 2.00;
final double BELBEBRN = 1.80;
final double SCHOATST = 2.50;
final double BOULFHSAISN = 2.75;
final double GANDANCPRTR = 1.75;
if (theBeerBrand == 1)
beer = LAGIMRED;
else if (theBeerBrand == 2)
beer = DESINIPA;
else if (theBeerBrand == 3)
beer = BELBEBRN;
else if (theBeerBrand == 4)
beer = SCHOATST;
else if (theBeerBrand == 5)
beer = BOULFHSAISN;
else
beer = GANDANCPRTR;
return beer;
public double calcBeerTotal()
{
String beerTypeStr;
double count = 1;
while (count <= numBeers)
{
beerTypeStr = JOptionPane.showInputDialog("Please choose between "
+ "these fine selections:\n1 - Lagunitas Imperial Red - " +
"$1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - " +
"Bell's Best Brown Ale - $1.80\n4 - Schlafly's Oatmeal " +
"Stout - $2.50\n5 - Boulevard's Farmhouse Saison - $2.75"
+ "\n6 - Gandy Dancer Porter - $1.75");
beerType = Double.parseDouble(beerTypeStr);
beerType = theBeerBrand;
total += beer;
count++;
}
return total;
}
public double getBeerTotal()
{
double theTotal;
theTotal = total;
return theTotal;
}
public double calcBeerDisc()
{
if (numBeers == 6)
beerDisc = .10;
else if (numBeers >= 4)
beerDisc = .05;
else
beerDisc = .00;
return beerDisc;
}
public double calcFinalPrice()
{
double finalPrice;
finalPrice = total-(total * beerDisc);
return finalPrice;
}
Noob here, so please shed some mercy. The point of the above program is to gather the amount of beers(must be 3-6), provide the customer with a choice for each beer, calculate the total amount of beers, and apply a discount(depends on # of beers). Pretty simple stuff, yet I've hit a brick wall.
My problem lies with calculating the final price. I can't seem to figure out why nothing from by calcBeerTotal method is getting passed to my calcFinalPrice method. My output displays the amount of beers just not the final price.
So my main question is: do I need some sort of setter and getter method for my calc methods? I've tried some setter and getter methods and I still wasn't getting a final price (method located above calcBeerDisc). I'm of limited programming knowledge so please keep from getting any more complicated than what I've written. If it's something aside from setters and getters please keep away from arrays and the like as I do not fully understand them either. Any help is much appreciated!
Rewritten:
import javax.swing.JOptionPane;
public class BeerStoreBP {
private String name;
private double custAge;
private double numBeers = 0;
private double beerDisc = 0;
private double total = 0;
// This only exists in one method. There is no need for it to be global
//private double beerType = 0;
// This only exists in one method. There is no need for it to be global
//private double theBeerBrand;
// This only exists in one method. There is no need for it to be global
//private double total = 0;
// This only exists in one method. There is no need for it to be global
//private double beer = 0;
public void setAge(double theAge)
{
custAge = theAge;
}
public void setName(String theName)
{
name = theName;
}
public void setNumBeers(double theNumBeers)
{
numBeers = theNumBeers;
}
// Your functionality is parsed by your dialog. There is no need for this.
//public void setBeerType(double theBeerType)
//{
// beerType = theBeerType;
//}
public double getAge()
{
return custAge;
}
public String getName()
{
return name;
}
public double getNumBeers()
{
return numBeers;
}
public double calcNumBeersValid()
{
String numBeersStr;
while (numBeers < 3 || numBeers > 6)
{
numBeersStr = JOptionPane.showInputDialog("You must pick 3-6 " +
"beers");
numBeers = Double.parseDouble(numBeersStr);
}
return numBeers;
}
public double calcBeerPrice(int beerBrand)
{
final double LAGIMRED = 1.90;
final double DESINIPA = 2.00;
final double BELBEBRN = 1.80;
final double SCHOATST = 2.50;
final double BOULFHSAISN = 2.75;
final double GANDANCPRTR = 1.75;
double beerPrice;
if (beerBrand == 1)
beerPrice = LAGIMRED;
else if (beerBrand == 2)
beerPrice = DESINIPA;
else if (beerBrand == 3)
beerPrice = BELBEBRN;
else if (beerBrand == 4)
beerPrice = SCHOATST;
else if (beerBrand == 5)
beerPrice = BOULFHSAISN;
else
beerPrice = GANDANCPRTR;
return beerPrice;
}
public void calcBeerTotal()
{
String beerTypeStr;
double count = 1;
double beerPrice;
// No need to be double
int beerBrand;
while (count <= numBeers)
{
beerTypeStr = JOptionPane.showInputDialog("Please choose between "
+ "these fine selections:\n1 - Lagunitas Imperial Red - " +
"$1.90\n2 - Deschutes Inversion IPA - $2.00\n3 - " +
"Bell's Best Brown Ale - $1.80\n4 - Schlafly's Oatmeal " +
"Stout - $2.50\n5 - Boulevard's Farmhouse Saison - $2.75"
+ "\n6 - Gandy Dancer Porter - $1.75");
beerBrand = Integer.parseInt(beerTypeStr);
beerPrice = calcBeerPrice(beerBrand);
total += beerPrice;
count++;
}
}
public double getBeerTotal()
{
return total;
}
public double calcBeerDisc()
{
if (numBeers == 6)
beerDisc = .10;
else if (numBeers >= 4)
beerDisc = .05;
else
beerDisc = .00;
return beerDisc;
}
public double calcFinalPrice()
{
double finalPrice;
finalPrice = total-(total * beerDisc);
return finalPrice;
}
}
This is in a working state, but may I recommend you take the UI portions out of this class and include them elsewhere.

Java based Neural Network --- how to implement backpropagation

I am building a test neural network and it is definitely not working. My main problem is backpropagation. From my research, I know that it is easy to use the sigmoid function. Therefore, I update each weight by (1-Output)(Output)(target-Output) but the problem with this is what if my Output is 1 but my target is not? If it is one at some point then the weight update will always be 0...For now I am just trying to get the darn thing to add the inputs from 2 input neurons, so the optimal weights should just be 1 as the output neuron simply adds its inputs. I'm sure I have messed this up in lots of places but here is my code:
public class Main {
public static void main(String[] args) {
Double[] inputs = {1.0, 2.0};
ArrayList<Double> answers = new ArrayList<Double>();
answers.add(3.0);
net myNeuralNet = new net(2, 1, answers);
for(int i=0; i<200; i++){
myNeuralNet.setInputs(inputs);
myNeuralNet.start();
myNeuralNet.backpropagation();
myNeuralNet.printOutput();
System.out.println("*****");
for(int j=0; j<myNeuralNet.getOutputs().size(); j++){
myNeuralNet.getOutputs().get(j).resetInput();
myNeuralNet.getOutputs().get(j).resetOutput();
myNeuralNet.getOutputs().get(j).resetNumCalled();
}
}
}
}
package myneuralnet;
import java.util.ArrayList;
public class net {
private ArrayList<neuron> inputLayer;
private ArrayList<neuron> outputLayer;
private ArrayList<Double> answers;
public net(Integer numInput, Integer numOut, ArrayList<Double> answers){
inputLayer = new ArrayList<neuron>();
outputLayer = new ArrayList<neuron>();
this.answers = answers;
for(int i=0; i<numOut; i++){
outputLayer.add(new neuron(true));
}
for(int i=0; i<numInput; i++){
ArrayList<Double> randomWeights = createRandomWeights(numInput);
inputLayer.add(new neuron(outputLayer, randomWeights, -100.00, true));
}
for(int i=0; i<numOut; i++){
outputLayer.get(i).setBackConn(inputLayer);
}
}
public ArrayList<neuron> getOutputs(){
return outputLayer;
}
public void backpropagation(){
for(int i=0; i<answers.size(); i++){
neuron iOut = outputLayer.get(i);
ArrayList<neuron> iOutBack = iOut.getBackConn();
Double iSigDeriv = (1-iOut.getOutput())*iOut.getOutput();
Double iError = (answers.get(i) - iOut.getOutput());
System.out.println("Answer: "+answers.get(i) + " iOut: "+iOut.getOutput()+" Error: "+iError+" Sigmoid: "+iSigDeriv);
for(int j=0; j<iOutBack.size(); j++){
neuron jNeuron = iOutBack.get(j);
Double ijWeight = jNeuron.getWeight(i);
System.out.println("ijWeight: "+ijWeight);
System.out.println("jNeuronOut: "+jNeuron.getOutput());
jNeuron.setWeight(i, ijWeight+(iSigDeriv*iError*jNeuron.getOutput()));
}
}
for(int i=0; i<inputLayer.size(); i++){
inputLayer.get(i).resetInput();
inputLayer.get(i).resetOutput();
}
}
public ArrayList<Double> createRandomWeights(Integer size){
ArrayList<Double> iWeight = new ArrayList<Double>();
for(int i=0; i<size; i++){
Double randNum = (2*Math.random())-1;
iWeight.add(randNum);
}
return iWeight;
}
public void setInputs(Double[] is){
for(int i=0; i<is.length; i++){
inputLayer.get(i).setInput(is[i]);
}
for(int i=0; i<outputLayer.size(); i++){
outputLayer.get(i).resetInput();
}
}
public void start(){
for(int i=0; i<inputLayer.size(); i++){
inputLayer.get(i).fire();
}
}
public void printOutput(){
for(int i=0; i<outputLayer.size(); i++){
System.out.println(outputLayer.get(i).getOutput().toString());
}
}
}
package myneuralnet;
import java.util.ArrayList;
public class neuron {
private ArrayList<neuron> connections;
private ArrayList<neuron> backconns;
private ArrayList<Double> weights;
private Double threshold;
private Double input;
private Boolean isOutput = false;
private Boolean isInput = false;
private Double totalSignal;
private Integer numCalled;
private Double myOutput;
public neuron(ArrayList<neuron> conns, ArrayList<Double> weights, Double threshold){
this.connections = conns;
this.weights = weights;
this.threshold = threshold;
this.totalSignal = 0.00;
this.numCalled = 0;
this.backconns = new ArrayList<neuron>();
this.input = 0.00;
}
public neuron(ArrayList<neuron> conns, ArrayList<Double> weights, Double threshold, Boolean isin){
this.connections = conns;
this.weights = weights;
this.threshold = threshold;
this.totalSignal = 0.00;
this.numCalled = 0;
this.backconns = new ArrayList<neuron>();
this.input = 0.00;
this.isInput = isin;
}
public neuron(Boolean tf){
this.connections = new ArrayList<neuron>();
this.weights = new ArrayList<Double>();
this.threshold = 0.00;
this.totalSignal = 0.00;
this.numCalled = 0;
this.isOutput = tf;
this.backconns = new ArrayList<neuron>();
this.input = 0.00;
}
public void setInput(Double input){
this.input = input;
}
public void setOut(Boolean tf){
this.isOutput = tf;
}
public void resetNumCalled(){
numCalled = 0;
}
public void setBackConn(ArrayList<neuron> backs){
this.backconns = backs;
}
public Double getOutput(){
return myOutput;
}
public Double getInput(){
return totalSignal;
}
public Double getRealInput(){
return input;
}
public ArrayList<Double> getWeights(){
return weights;
}
public ArrayList<neuron> getBackConn(){
return backconns;
}
public Double getWeight(Integer i){
return weights.get(i);
}
public void setWeight(Integer i, Double d){
weights.set(i, d);
}
public void setOutput(Double d){
myOutput = d;
}
public void activation(Double myInput){
numCalled++;
totalSignal += myInput;
if(numCalled==backconns.size() && isOutput){
System.out.println("Total Sig: "+totalSignal);
setInput(totalSignal);
setOutput(totalSignal);
}
}
public void activation(){
Double activationValue = 1 / (1 + Math.exp(input));
setInput(activationValue);
fire();
}
public void fire(){
for(int i=0; i<connections.size(); i++){
Double iWeight = weights.get(i);
neuron iConn = connections.get(i);
myOutput = (1/(1+(Math.exp(-input))))*iWeight;
iConn.activation(myOutput);
}
}
public void resetInput(){
input = 0.00;
totalSignal = 0.00;
}
public void resetOutput(){
myOutput = 0.00;
}
}
OK so that is a lot of code so allow me to explain. The net is simple for now, just an input layer and an output layer --- I want to add a hidden layer later but I'm taking baby steps for now. Each layer is an arraylist of neurons. Input neurons are loaded with inputs, a 1 and a 2 in this example. These neurons fire, which calculates the sigmoid of the inputs and outputs that to the output neurons, which adds them and stores the value. Then the net backpropagates by taking the (answer-output)(output)(1-output)(output of the specific input neuron) and updates the weights accordingly. A lot of times, it cycles through and I get infinity, which seems to correlate with negative weights or sigmoid. When that doesn't happen it converges to 1 and since (1-output of 1) is 0, my weights stop updating.
The numCalled and totalSignal values are just so the algorithm waits for all neuron inputs before continuing. I know I'm doing this an odd way, but the neuron class has an arraylist of neurons called connections to hold the neurons that it is forward connected to. Another arraylist called backconns holds the backward connections. I should be updating the correct weights as well since I am getting all back connections between neurons i and j but of all neurons j (the layer above i) I am only pulling weight i. I apologize for the messiness --- I've been trying lots of things for hours upon hours now and still cannot figure it out. Any help is greatly appreciated!
Some of the best textbooks on neural networks in general are Chris Bishop's and Simon Haykin's. Try reading through the chapter on backprop and understand why the terms in the weight update rule are the way they are.The reason why I am asking you to do that is that backprop is more subtle than it seems at first. Things change a bit if you use a linear activation function for the output layer (think about why you might want to do that. Hint: post-processing), or if you add a hidden layer. It got clearer for me when I actually read the book.
You might want to compare your code to this single layer perceptron.
I think you have a bug in your backprop algo. Also, try replacing the sigmoid with a squarewave.
http://web.archive.org/web/20101228185321/http://en.literateprograms.org/Perceptron_%28Java%29
what if my Output is 1 but my target is not?
The sigmoid function 1/(1 + Math.exp(-x)) never equates to 1. The lim as x approaches infinity is equal to 0, but this is a horizontal asymptote, so the function never actually touches 1. Therefore, if this expression is used to compute all of your output values, then your output will never be 1. So (1 - output) shouldn't ever equal 0.
I think your issue is during the calculation of the output. For a neural network, the output for each neuron is typically sigmoid(dot product of inputs and weights). In other words, value = input1 * weight1 + input2 * weight2 + ... (for each weight of neuron) + biasWeight. Then that neuron's output = 1 / (1 + Math.exp(-value). If it's calculated in this way, the output won't ever be equal to 1.