Okay to make this clearer this is what i need done to my entire program. I need main to restore any calculators that are in the file "calc.bak" before presenting the user with a menu and main should save all calculators that exist in that same file (overwrite as appropriate) just before exiting. I also need to give the user the option to create a brand new calculator, name it, and add a function to it from an already existing collection (which are my Add, multiply, and divide). I also need the user to create their own function by designing and naming a combination of any pair of functions. The ouput of the first function would necessarily be input to the second function. For example, the user can create a new function called "addmult" that calls the add function (which prompts for two numbers and adds them) and establishes the sum as one of the operands for the multiply function (which would have to prompt for its second operand).
The sample out put should look like this:
Welcome to the Calculator Configurator
restore a calculator from a file
create a calculator from scratch
let me create a calculator you can use
2
OK. so you want to create one yourself.
What is the name of your calculator? Fred
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add(1)
Multiply(2)
Divide(3)
Pair of functions(4)
input (2)
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
1
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
4
Provide a name for this pair:
BothAddAndMult
Provide a description for this pair:
multiplies and then adds
Which function should be first?
Multiply(0)
Add(1)
0
Which function should be first?
Multiply
Add
1
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
4
Provide a name for this pair:
MultAfter
Provide a description for this pair: multiplies last after a multiply and add
Which function should be first?
Multiply
Add
BothAddAndMult
2
Which function should be first?
Multiply
Add
BothAddAndMult
Indicate which functions from our stock you'd like to add to your calculator (enter 0 to quit this menu):
Add
Multiply
Divide
Pair of functions
0
I am a calculator named Fred
quit
clear memory
multiply two numbers
add two numbers
multiplies and then adds
multiplies last after a multiply and add
Can someone help me reach this output?
Here is my code so far
CalcConfig.java
import java.util.Scanner;
// program to model a configurable calculator
public class CalcConfig {
public static void main(String [] args)
{
System.out.println("Welcome to the Calculator Configurator");
Scanner kbd = new Scanner(System.in);
CalcFunction [] funs = {
new Add(kbd, "add two numbers"),
new Multiply(kbd, "Multiply two numbers"),
new Divide(kbd, "divide two numbers")};
Calculator calc = new Calculator(funs);
calc.go(kbd);
}
}
Calculator.java
//my Calculator class
import java.util.Scanner;
// models a configurable calcuator
public class Calculator {
private CalcFunction [] functions;
private double memory = 0;
private boolean clear = true;
public Calculator(CalcFunction [] functions)
{
this.functions = functions;
}
public void go(Scanner kbd)
{
int choice = 0;
do
{
System.out.println(this);
choice = kbd.nextInt();
if (choice == 0) return; // choice is to quit
if (choice == 1)
{
clear = true;
continue;
}
if (choice < 0 || choice >= 5)
{
System.out.println("error");
continue;
}
if (!clear)
{
System.out.print("use memory [" + memory + "] (y or n)? ");
String ans = kbd.next();
if (ans.equals("n")) clear = true;
}
if (clear)
memory = functions[choice-2].doit();
else
memory = functions[choice-2].doit(memory);
clear = false;
System.out.println(memory);
} while(choice != 0);
}
public String toString()
{
String out = "0. quit\n1. clear memory\n";
for (int i=0; i<functions.length; i++)
out += (i+2) + ". " + functions[i] + "\n";
return out;
}
}
CalcFunction.java
//my CalcFunction class
import java.util.Scanner;
// generic class to model a function in a calculator
public abstract class CalcFunction {
private Scanner kbd;
private String description;
public CalcFunction(Scanner kbd, String description)
{
this.kbd = kbd;
this.description = description;
}
public abstract double doit();
public abstract double doit(double memory);
// get a string from the user
protected String getString(String prompt)
{
System.out.print(prompt);
return kbd.next();
}
// get a number from the user
protected double getNum(String prompt)
{
System.out.print(prompt);
while(!kbd.hasNextDouble())
{
System.out.print("Invalid: need a number: ");
kbd.next(); // discard invalid input
}
return kbd.nextDouble();
}
public String toString()
{
return description;
}
}
Add.java
//just one of my functions(Add)
import java.util.Scanner;
// class to encapsulate adding two numbers
public class Add extends CalcFunction {
public Add(Scanner kbd, String description)
{
super(kbd, description);
}
public double doit()
{
double n1 = this.getNum("Enter a number: ");
return this.doit(n1);
}
public double doit(double first)
{
double n2 = this.getNum("Enter a second number: ");
double answer = first + n2;
return answer;
}
}
Please help if you can. Thanks!
Pseudo-code:
// 1 maps to add, 2 to subtract, etc
while(cur_func = scanner.read != sentinal value) {
switch(cur_func) {
1:
//toss add into the functions set
break
.
.
.
}
}
toArray your set and build the calc
If you want the user to be able to dynamically add calculator functions to a calculator, then you will need something like this:
public void addCalcFunction(CalcFunction newCalcFunction) {
this.functions.add(newCalcFunction);
}
...but that will require this.functions to be modified to a Collection<CalcFunction>
If you want the user to refer to these functions by name, then you'll need to map them:
private Map<String, CalcFunction> functions;
...
public void addCalcFunction(String functionName, CalcFunction newCalcFunction) {
this.functions.put(functionName, newCalcFunction);
}
Using a Map will require you to make further changes, but I'm sure you can figure those out.
Related
So I created Saving class, created also setters and getters. Now I need u method, which will calculate the total amount of deposits.
public class Saving {
private double deposits;
private double totalAmountOfDeposits;
public double getDeposits()
{
return deposits;
}
public void setDeposits(double deposits)
{
this.deposits = deposits + deposits;
}
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
}
When I use this class in the program I got a wrong calculation. The program just add first value of deposit to the first value.
import java.util.Scanner;
public class SavingDemo {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Saving save = new Saving();
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
}
}
And here is the output:
Deposit amount
12
Deposit amount
34
Deposit amount
56
The total amount has been deposited is 24.0
As you can see its just added 12 to 12. Just want to mention that I'm totally new in programming. Les than a month.
I see two problems in your code. Take a look at the commented line. The reason you are seeing 12 + 12 is because that is exactly what you are instructing the JVM to do.
System.out.println("Deposit amount");
double depositeAmount = input.nextDouble();
save.setDeposits(depositeAmount);
System.out.println("Deposit amount");
double depositeAmount2 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("Deposit amount");
double depositeAmount3 = input.nextDouble();
save.setDeposits(depositeAmount); // <= adds the wrong variable
System.out.println("The total amount has been deposited is " + save.getTotalAmountOfDeposits());
Secondly, it looks like you may have a design flaw in your implementation of the Saving class.
You'll want to brush up on variable scope
If you take a look at your implementation on your total:
public double getTotalAmountOfDeposits()
{
double total = 0;
return total = total + deposits;
}
You have the total starting at 0 every time this method getTotalAmountOfDeposits() is called. the total variable in this method is local to it's method. So what you currently have is a method variable
You'll want to do some research into class variable. This will maintain that the instance of the object will have this variable assigned through the life cycle of the instantiated object.
When you have variables of the same name, you can get the instance variable with this keyword.
So when dealing with your setter
public void setSomething(double something) {
this.something // class variable
something // method variable
}
If you want your object to maintain state, you can set it on your object itself, and have your set deposit modify that state. Some pseudo code to get you moving forward.
public class Saving {
private double totalAmountOfDeposits; // you can modify this value with public methods
public void setDeposit(_) {
// Setter implementation
// increment totalAmountOfDeposits;
public double getTotalAmountOfDeposits(_)
// return totalAmountOfDeposits;
}
You should write a method
public void addDeposits(double deposits)
{
this.deposits = this.deposits + deposits;
}
and change setDeposits to
public void setDeposits(double deposits)
{
this.deposits = deposits;
}
after this call addDeposits to add deposits
To eliminate confusion within the Saving Class change the argument name for the setDeposits() method to double newDeposit instead of double deposits which is also a class field name. Although the construct is legal it does make it a wee bit confusing. Inside the setDeposits() method use:
this.deposit+= newDeposit;
As a matter of fact, you can get rid of the deposits field altogether since you also have the field named totalAmountOfDeposits. Use that instead:
this.totalAmountOfDeposits+= newDeposit;
You might also want a clearDeposits() method in your Saving Class:
public void clearDeposits() {
this.totalAmountOfDeposits = 0.0;
}
Your getTotalAmountOfDeposits() method within the Saving Class doesn't really make any sense either. Since you are always summing deposits anyways you can just return what is held within the totalAmountOfDeposits field:
public double getTotalAmountOfDeposits() {
return totalAmountOfDeposits;
}
The above method is would now of course be very mush the same as the getDeposits() method which could be changed to getTotalDeposits(). You can then change the getTotalAmountOfDeposits() method name to getTotalNumberOfDeposits() and add a additional class field named numberOfDeposits:
private double totalAmountOfDeposits;
private int numberOfDeposits = 0;
public double getTotalDeposits() {
return totalAmountOfDeposits;
}
public int getTotalNumberOfDeposits() {
return numberOfDeposits;
}
and in your setDeposits() method add the code line:
numberOfDeposits++;
So that it would look something like:
public void setDeposits(double newDeposit) {
totalAmountOfDeposits+= newDeposit;
numberOfDeposits++;
}
If you do add a clearDeposits() method to your Saving Class then don't forget to add the code line: numberOfDeposits = 0; into that method as well. It might now look something like:
public void clearDeposits() {
totalAmountOfDeposits = 0.0;
numberOfDeposits = 0;
}
You also have some issues within your main() method of your SavingDemo Class. Take a real close look at each call you make to the setDeposits() method for each value the User supplies. Each User supplied value goes into a specific double type variable name. Is that what you are passing to the setDeposits() method? ;)
Once you've got all that taken care of you can display to console:
System.out.println("The total amount has been deposited is " +
save.getTotalDeposits() + " by making " +
save.getTotalNumberOfDeposits() + " deposits.");
I'm trying to recursively call a method until I obtain the desired output. However, I want to call a method from another class and get information from that method in order to use it in my recursive method. For example, suppose I have a parent class called Cake that contains information about a cake such as its batter(i.e. amount the batter), an extended class with a specific type of cake containing a unique instance of the batter, and I have another class called Bakery where I want to actually make cakes that are being ordered. I have a method in Bakery called createCake, and I want to recursively call this method until enough batter is in the pan to create a cake. If the amount of batter is randomly generated in the extended class, how do I call the getBatter method from that class and capture the information about the batter amount in order to use it in my recursive method for creating the cakes? Can anyone help me out with this? I'm doing something similar to this, but I don't quite understand how I would go about actually getting the information in order to get the recursion to work. I have an example of the code below, so that you can have an idea of what I'm trying to do (I know it's not very accurate). Any help would be greatly appreciated.
import java.util.Random;
public abstract class Cake
{
static Random gen = new Random(System.currentTimeMillis());
public int type; //type of cake
public static int batter = gen.nextInt() * 3; //random amount of batter
public int getType()
{
return type;
}
public int getBatter()
{
return batter;
}
}
public class RedVelvet extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 1;
}
public int getBatter()
{
return batter;
}
}
public class Chocolate extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6; //generates between 6-8 cups of batter inclusive
public int getType()
{
return 2;
}
public int getBatter()
{
return batter;
}
}
public class Pound extends Cake
{
public int type;
public int batter = gen.nextInt(3)+6;
public int getType()
{
return 3;
}
public int getBatter()
{
return batter;
}
}
public class Bakery
{
import java.util.Scanner;
System.out.print("Enter desired size of cake to be baked (Must be at least 12):");
desiredSize=scan.nextInt();
public static void createCake(int desiredSize, int currentSize) //currentSize is the current amount of batter in the pan
{
if (currentSize == desiredSize)
return;
else if (currentSize < desiredSize)
{
//Recursively call createCake method so that batter continues to be added to the pan until there is enough to make the desired cake size. I want to get the batter information from one of the extended classes in order to add it to the cake.
}
}
Is this for school or a course of sorts because I personally wouldn't go this route but then again that's my opinion. It's like, what the heck do I know about baking and I can safely tell you....absolutely nothing. Some may even say that about my programming/coding skills but then again, I'm not a programmer and I am self taught in almost all programming environments including good old Assembly most of which I have now forgotten. :/
I should think that when it comes to baking cakes (or most things for that matter) some sort of accuracy must be established so as to avoid waste and we all know that waste costs money. I'm not overly convinced that generating random amounts of cake batter is accurate enough for what you're most likely are trying to accomplish but then again, you already know this. I noticed that in your different cake classes they all basically generate a random number from 6 to 8. If they all do the same thing then why have them?
I don't believe you need recursion at all but instead a simple method called from within a loop, for example:
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
}
Here is how I would do this and I apologize now if you find this is all totally meaningless:
import java.util.Random;
import java.util.Scanner;
public class Bakery {
public static void main(String[] args) {
getBaking(); // :)
}
private static void getBaking(){
Scanner scan = new Scanner(System.in);
String cakeType = "";
while (cakeType.equals("")) {
System.out.print("Enter desired cake to be baked (Pound, Chocolate, "
+ "RedVelvet) or\nenter 'exit' to quit: -> ");
cakeType = scan.nextLine();
if (cakeType.isEmpty()) {
System.out.println("\nYou must supply the name of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (cakeType.toLowerCase().equals("exit")) { System.exit(0); }
else if (!cakeType.toLowerCase().matches("(pound|chocolate|redvelvet)")) {
System.out.println("\nYou must supply the name of cake as shown above!\n");
cakeType = "";
}
}
int desiredSize = 0;
String size = "";
while (size.equals("")) {
System.out.print("\nEnter desired size of cake to be baked (must be at "
+ "least 12\"): -> ");
size = scan.nextLine();
if (size.isEmpty()) {
System.out.println("\nYou must supply the size of cake to bake or "
+ "enter 'exit' to quit!\n");
}
else if (size.toLowerCase().equals("exit")) { System.exit(0); }
else if (Integer.valueOf(size.replace("\"","")) < 12 ) {
System.out.println("\nYou must supply a cake size of 12\" or greater!\n");
size = "";
}
}
desiredSize = Integer.valueOf(size.replace("\"",""));
createCake(cakeType, desiredSize, 0);
}
public static void createCake(String cake, int desiredSize, int currentSize) {
//currentSize is the current amount of batter in the pan
while (currentSize < desiredSize) {
currentSize+= getBatter(cake, desiredSize);
System.out.println(currentSize);
}
System.exit(0); // Done! - Quit!
}
public static int getBatter(String cake, int desiredSize) {
Random gen = new Random(System.currentTimeMillis());
// Since the random generation for the batter amount is the
// same for all cake types according to your code we just
// need this:
int batterAmount = gen.nextInt(3)+6;
// But if we want to be more specific for each Cake Type
// then we can do it this way but first create the required
// batter equations for each cake type and remove the /* and
// */ from the code but first comment out (//) the batterAmount
// variable declaration above.
// NOTE: Both cake diameter AND 'Height' should play into the factor
// of how much batter is required unless of course all cakes made are
// of the same height.
/*
int batterAmount = 0;
switch (cake.toLowerCase()) {
case "pound":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "chocolate":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
case "redvelvet":
batterAmount = //batter amount to make 12 inch cake + (this much batter for a 1 inch cake * (desiredSize - 12));
break;
} */
return batterAmount;
}
}
Well, I do hope this has helped you somewhat or at least thrown a little thought into the oven :P
I am trying to bring in some numerical values by way of Scanner(System.in). I am calling a class with my method from main and having a difficult time exiting the method, my questions are looping.
I am sure this is a simple issue but I am having a heck of a time finding a solution.
Here is the method:
public static Object userInput(double nutWidth, double lastFretWidth, double scaleLength, int numFrets) {
boolean dataCheck = true;
try {
while (dataCheck == true) {
System.out.println("What is the width at the nut?");
NutWidth = key.nextDouble();
System.out.println("What is the width at the last fret?");
LastFretWidth = key.nextDouble();
System.out.println("What is the scale length?");
ScaleLength = key.nextDouble();
System.out.println("How many frets will your guitar have?");
NumFrets = key.nextInt();
dataCheck = false;
}
} catch (InputMismatchException e) {
System.out.println("Enter a integer.");
key.nextInt();
}
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
}
Here is my main:
public static void main(String[] args) {
FingerBoard.userInput(0, 0, 0, 0);
FingerBoard.UserData();
}
Any help is greatly appreciated-Mike
You have written an infinite recursion. The line
return userInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
will call the same method again after finishing the previous method. It looks to me like you want to store the values in a data structure and return that, which would require calling a constructor something like this:
return new UserInput(NutWidth, LastFretWidth, ScaleLength, NumFrets);
You would have to write the data structure UserInput yourself. If you haven't gotten to writing classes and data structures yet, you probably want your variables to be static fields. If you are doing that, change the return type to be void and remove the return statement entirely.
Additional comments not related to your problem. You don't need the arguments to your method. They are never used. You probably also want to put the try/catch inside of the while loop. That way an invalid input will prompt for new input, rather than setting things to 0.
Unfortunately, I can't attach my overall program (as it is not finished yet and still remains to be edited), so I will try my best to articulate my question.
Basically, I'm trying to take an integer inputted by the user to be saved and then added to the next integer inputted by the user (in a loop).
So far, I've tried just writing formulas to see how that would work, but that was a dead end. I need something that can "save" the integer entered by the user when it loops around again and that can be used in calculations.
Here is a breakdown of what I'm trying to make happen:
User inputs an integer (e.g. 3)
The integer is saved (I don't know how to do so and with what) (e.g. 3 is saved)
Loop (probably while) loops around again
User inputs an integer (e.g. 5)
The previously saved integer (3) is added to this newly inputted integer (5), giving a total of (3 + 5 =) 8.
And more inputting, saving, and adding...
As you can probably tell, I'm a beginner at Java. However, I do understand how to use scanner well enough and create various types of loops (such as while). I've heard that I can try using "var" to solve my problem, but I'm not sure how to apply "var". I know about numVar, but I think that's another thing entirely. Not to mention, I'd also like to see if there are any simpler solutions to my problem?
Okay So what you want is to store a number.
So consider storing it in a variable, say loopFor.
loopFor = 3
Now we again ask the user for the input.
and we add it to the loopFor variable.
So, we take the input using a scanner maybe, Anything can be used, Scanner is a better option for reading numbers.
Scanner scanner = new Scanner(System.in);//we create a Scanner object
int numToAdd = scanner.nextInt();//We use it's method to read the number.
So Wrapping it up.
int loopFor = 0;
Scanner scanner = new Scanner(System.in);//we create a Scanner object
do {
System.out.println("Enter a Number:");
int numToAdd = scanner.nextInt();//We use it's method to read the number.
loopFor += numToAdd;
} while (loopFor != 0);
You can just have a sum variable and add to it on each iteration:
public static void main(String[] args) {
// Create scanner for input
Scanner userInput = new Scanner(System.in);
int sum = 0;
System.out.println("Please enter a number (< 0 to quit): ");
int curInput = userInput.nextInt();
while (curInput >= 0) {
sum += curInput;
System.out.println("Your total so far is " + sum);
System.out.println("Please enter a number (< 0 to quit): ");
}
}
You will want to implement a model-view-controller (mvc) pattern to handle this. Assuming that you are doing a pure Java application and not a web based application look at the Oracle Java Swing Tutorial to learn how to build your view and controller.
Your model class is very simple. I would suggest just making a property on your controller that is a Java ArrayList of integers eg at the top of your controller
private Array<Integer> numbers = new ArrayList<Integer>();
Then your controller could have a public method to add a number and calculate the total
public void addInteger(Integer i) {
numbers.addObject(i);
}
public Integer computeTotal() {
Integer total = 0;
for (Integer x : numbers) {
total += x;
}
return total;
}
// This will keep track of the sum
int sum = 0;
// This will keep track of when the loop will exit
boolean errorHappened = false;
do
{
try
{
// Created to be able to readLine() from the console.
// import java.io.* required.
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in));
// The new value is read. If it reads an invalid input
// it will throw an Exception
int value = Integer.parseInt(bufferReader.readLine());
// This is equivalent to sum = sum + value
sum += value;
}
// I highly discourage the use Exception but, for this case should suffice.
// As far as I can tell, only IOE and NFE should be caught here.
catch (Exception e)
{
errorHappened = true;
}
} while(!errorHappened);
I'm not trying to do anything too fancy here really, there is something very simple here that i'm not noticing.
a little premise, this is a simple grade converter, run the driver, enter a double numberGrade(88.7, 90, 67.2, etc) and it will then go to the service and check the statements like this that i will have for grades A-F
if (enterGrade >= 90 && enterGrade <= 100)
grade = 'A';
keep getting an error though
import java.util.Scanner;
public class CondTest
{
public static void main(String[] args)
{
System.out.print("Please enter your number grade for a letter grade! >");
Scanner scanObj = new Scanner(System.in);
Conditionals condObj = new Conditionals();
int enterGrade = scanObj.nextInt();
condObj.Conditionals(enterGrade);
}
}
and heres my method in the service class to reference
public class Conditionals
{
public double letterGrade(double enterGrade)
{
char grade = 0;
if (enterGrade >= 90 && enterGrade <= 100)
grade = 'A';
return grade;
}
}
After troubleshooting more i thought maybe changing the
condObj.conditionals(enterGrade);
to
double condObj.conditionals(enterGrade);
but no luck.
I keep recieving this same error
CondTest.java:18:error: cannot find symbol
condObj.conditionals(enterGrade);
As far as I can see, there just is no method called conditionals in your Conditionals class - only a method called letterGrade. Maybe you should call this one instead?
Change it to
condObj.letterGrade(enterGrade);
And: Scanner.nextInt() returns an int, do you have a method that accepts an int param?