class Box
{
// Instance Variables
double length ,ipsos ;
double width ,mikos ;
double height ,platos;
// Constructors
public Box ( double side )
{
width = side ;
height = side ;
length = side ;
}
public Box ( double x , double y , double z)
{
platos = y ;
ipsos = z;
mikos = x ;
}
// Methods
double calculate(double praksi)
{
return 2 * ( width * height +
width * length +
height * length ) ;
}
double volume(double emvadon)
{
return platos*ipsos*mikos ;
}
}
In the upper code, how can I make a toString() method, so I can return the values of volume and calculate ???
Im new with java so be as simple as you can please
Not too sure what the parameters of the methods 'calculate', 'volme' are for?
If you're looking to override the default toString method, so when you call System.out.println(new Box(1,2,3)): it prints out the volume, and value calculate returns for the box then the following should work:
Box b = new Box(1,2,3);
System.out.println(b);
Then the following should work:
#Override
public String toString()
{
return "Volume: " + volume(0.0) + ", calculate: " + calculate(0.0);
}
This would print the volume and whatever calculate returns, both clearly labelled.
Add this method to your class (to override the toString() method):
#Override
public String toString() {
return "Volume: " + volume(1) + "\n Calculate: " + calculate(1);
}
Note: #Override is optional: it's just communication and making sure you receive an error if you misspell the overridden method (toString()).
Also, why do you have parameters for volume and calculate if you don't use them? That's why I passed them a random number like 1 because it apparently doesn't matter what they are.
Related
I would like a little help in java from you guys. My idea is to generate two integer variables from the random method and make it a constant string. Something like:
//In Class
Random rand = new Random();
protected int aux1 = rand.nextInt(9999), aux2 = rand.nextInt(10);
public final String x = aux1+"-"+aux2; //is it possible to take just one time?
public String getX() {return x;}
But each time when I use the getX() in main class I got different values for x: 9626-3 4938-0 6500-6
instead of: 4938-0 4938-0 4938-0
How can I do this?
grateful for the attention.
You got three different values ... because you ASKED for three different values.
It sounds like:
You want a string, consisting of two random integers and a dash.
The first integer is initialized once, the second always changes.
Potential solution:
public class MyClass {
protected Random rand = new Random();
protected int aux1 = rand.nextInt(9999)
public String makeIdentifier() {
int aux2 = rand.nextInt(10);
return aux1 + "-" + aux2;
}
...
In other words, you've:
refactored the "common code" into class members
isolated the "unique" code in it's own method
Update 1
As I asked yesterday, it would be helpful if you'd better explain what you're trying to do. NOT "how" you're trying to do it, but WHAT you're trying to accomplish. By showing some output samples.
Let's go back to your initial post:
If you just want a string (e.g. "identifier") , with two random numbers separated by a dash...
... and if you never want it to change over the lifetime of the object...
... then here's how you could do it:
public class MyClass {
protected Random rand = new Random();
protected String identifier =
rand.nextInt(9999) + "-" + rand.nextInt(10);
public String getIdentifier() { return identifier; }
}
...
Note that the member "identifier" is initialized ONCE, when the class is instantiated.
It sounds like that's what you were trying to do in your original post. But - since you didn't show a complete SSCCE, there's no way to tell exactly why it didn't work for you :(
Update 2
Thank you for your update. I can't overemphasize the value of a good SSCCE.
It's now clear that you have TWO classes. Each time you create a new instance of "Test2" ... you get a new value of "x". That's the part you don't like.
SOLUTION:
Don't call it "Test2". Make your class do one thing, and do it well. Let's say you want an "identifier string", like "XXXX-YY". Then call your class "Identifier". Or let's say you want "control information" like "identifier string" and "sequence number". Then call it "ControlInformation".
Let's say you want the SAME value, "XXXX-YY", no matter how many times you invoke the class, or how many instances you invoke it from. Then, as Oleg aready suggested, use static
EXAMPLE SOLUTION:
ControlInformation.java
import java.util.Random;
/**
* SAMPLE OUTPUT:
* Creating two object instances: c1 and c2...
* c1: 0, 1461-2
* c2: 0, 1461-2
* Incrementing c1..
* c1: 1, 1461-2
* c2: 0. 1461-2
*/
public class ControlInformation {
// "identifier" initialized exactly once; will be the same for all instances
protected static Random rand = new Random();
protected static String identifier =
rand.nextInt(9999) + "-" + rand.nextInt(10);
// "Sequence" will vary per object
protected int sequence = 0;
// Public access
public String getIdentifier() { return identifier; }
public int getSequence() { return sequence; }
public int increment() { return ++sequence; }
public static void main (String[] args) {
System.out.println("Creating two object instances: c1 and c2...");
ControlInformation c1 = new ControlInformation();
ControlInformation c2 = new ControlInformation();
System.out.println("c1: " + c1.getSequence() + ", " + c1.getIdentifier());
System.out.println("c2: " + c2.getSequence() + ", " + c2.getIdentifier());
System.out.println("Incrementing c1..");
c1.increment();
System.out.println("c1: " + c1.getSequence() + ", " + c1.getIdentifier());
System.out.println("c2: " + c2.getSequence() + ". " + c2.getIdentifier());
}
}
I have this (in class MyClass):
private static int sequence = 1;
protected String number;
private float limitValue;
Random rand = new Random();
public String x = rand.nextInt(9999)+"-"+rand.nextInt(10);
MyClass () { number = "0000" + sequence++; }
public void showData() {
System.out.printf(" Number: %s - X: %s - Limit value: %.2f.\n", getNumber(), getX(), limitValue);
}
in my main class:
MyClass y1 = new MyClass();
value = 500f;
y1.setLimitValue(value);
y1.showData();
MyClass y2 = new MyClass();
value = 700f;
y2.setLimitValue(value);
y2.showData();
MyClass y3 = new MyClass();
value = 900f;
y3.setLimitValue(value);
y3.showData();
and I got, for example, this output:
Number: 00001 - X: 3383-6 - Limit value: 500,00.
Number: 00002 - X: 2513-4 - Limit value: 700,00.
Number: 00003 - X: 8012-5 - Limit value: 900,00.
and my intention is get the same value of x for all y (y1, y2, y3).
hello Ive been try for days keep getting the same error.
basically Ive a got this error:
VisaCardDemo.java:24: error:
constructor CreditCard in class CreditCard cannot be applied to given types;
new CreditCard(100.0, 0.03, 2.50, 500.0);
required: no arguments
found: double,double,double,double
reason: actual and formal argument lists differ in length
1 error
basically I've no clue why this is happening its something to do with the constructor not interacting
stemming from this code:
public class CreditCard
{
int numberRepayments = 0;
int numberDebits = 0;
double creditCard_Bal;
double Annual_Interest;
double monthlyServiceCharges;
double creditCard_limit;
//double
public CreditCard(double Balance, double interest, double serviceCharge, double limit)
{
//I'm unsure if im doing this correctly
creditCard_Bal = Balance;
Annual_Interest = interest;
monthlyServiceCharges = serviceCharge;
creditCard_limit = limit;
//double
}
public void repayment(double repayments){
creditCard_Bal = creditCard_Bal - repayments;
numberRepayments = numberRepayments + 1;
}
public int debit(double debit){
creditCard_Bal = creditCard_Bal - debit;
numberDebits = numberDebits + 1;
return numberDebits;
}
public void calcInterest(){
//Monthly_Interest_Rate = (Annual_Interest / 12);
//Monthly_Interest = creditCard_Bal * Monthly_Interest;
creditCard_Bal = creditCard_Bal * (1 + (Annual_Interest / 12));
}
public int monthlyProcess(){
creditCard_Bal = creditCard_Bal - monthlyServiceCharges;
calcInterest();
numberRepayments = 0;
numberDebits = 0;
return numberDebits;
}
public double setMonthlyServiceCharges(double placeHolder){
monthlyServiceCharges = placeHolder;
return monthlyServiceCharges;
}
public double getMonthlyServiceCharges(){
return monthlyServiceCharges; // the reason that ive only put the variable
//is because i think the metho will work as
} //in the VisaCardDemo
// fprintf("the monthly service charge = " + cosc120VisaCard.getMonthlyServiceCharges)
//will equal fprintf("the monthly service charge =" monthlyServiceCharges )
// please let me know if this is not the case and i need to do more to it
public double getBalance(){
return creditCard_Bal;
}
public int getNumRepayments(){
return numberRepayments;
}
public int getNumDebits(){
return numberDebits;
}
public double getInterestRate(){
return Annual_Interest;
}
}
import java.text.DecimalFormat;
public class VisaCardDemo
{
public static void main(String[] args)
{
// Create a Decimalformat object for formatting output.
DecimalFormat dollar = new DecimalFormat("#,##0.00");
// Create a VisaCard object with a $100 balance,
// 3% interest rate, a monthly service charge
// of $2.50, and a credit limit of $500.
VisaCard cosc120VisaCard =
new VisaCard(100.0, 0.03, 2.50, 500.0);
//
//
CreditCard cosc120CreditCard =
new CreditCard(100.0, 0.03, 2.50, 500.0);
//
//
// Display what we've got.
System.out.println("Balance: $" +
dollar.format(cosc120VisaCard.getBalance()));
System.out.println("Number of repayments: " +
cosc120VisaCard.getNumRepayments());
System.out.println("Number of debits: " +
cosc120VisaCard.getNumDebits());
System.out.println();
// Make some repayments.
cosc120VisaCard.repayment(25.00);
cosc120VisaCard.repayment(10.00);
cosc120VisaCard.repayment(35.00);
// Display what we've done so far.
System.out.println("Balance: $" +
dollar.format(cosc120VisaCard.getBalance()));
System.out.println("Number of repayments: " +
cosc120VisaCard.getNumRepayments());
System.out.println("Number of debits: " +
cosc120VisaCard.getNumDebits());
System.out.println();
// Make some debits.
cosc120VisaCard.debit(450.00);
cosc120VisaCard.debit(50.00); // credit card account should become inactive
cosc120VisaCard.debit(10.00);
cosc120VisaCard.debit(10.00);
cosc120VisaCard.debit(10.00);
// Display what we've done so far.
System.out.println("Balance: $" +
dollar.format(cosc120VisaCard.getBalance()));
System.out.println("Number of repayments: " +
cosc120VisaCard.getNumRepayments());
System.out.println("Number of debits: " +
cosc120VisaCard.getNumDebits());
System.out.println();
// Do the monthly processing.
cosc120VisaCard.monthlyProcess();
// Display what we've done so far.
System.out.println("Balance: $" +
dollar.format(cosc120VisaCard.getBalance()));
System.out.println("Number of repayments: " +
cosc120VisaCard.getNumRepayments());
System.out.println("Number of debits: " +
cosc120VisaCard.getNumDebits());
}
}
public class VisaCard extends CreditCard
{
// double visaCard_Bal;
// double visaCard_Interest;
//double visaCard_ServiceCharge;
//double visaCard_Limit;
boolean tf = false;
double temporary_storage;
public VisaCard (double V_Balance, double V_interest, double V_serviceCharge, double V_limit)
{
creditCard_Bal = V_Balance; //dose this make the VisaCard class the super?
//end constructor
}
public int debit(double debit)
{
if (creditCard_Bal >= creditCard_Bal)
tf = false;
else{
creditCard_Bal = creditCard_Bal - debit;
numberDebits = numberDebits + 1;
return numberDebits;
}
}
public double repayments(double money)//calls the superclass version
{
super.repayment(money);
if (creditCard_limit >= creditCard_Bal)
tf = true;
}
public int monthlyProcess()
{
if (numberDebits > 10)
temporary_storage = monthlyServiceCharges;
monthlyServiceCharges = monthlyServiceCharges + (10 - numberDebits);
if (creditCard_Bal > creditCard_limit)
tf = false;
creditCard_Bal = creditCard_Bal + monthlyServiceCharges;
super.monthlyProcess();
monthlyServiceCharges = temporary_storage;
}
}
Firstly the error is perfectly correct and it is telling what compiler is looking for. It is looking for no arg constructor and found parameterized constructor.
So here are few basics-
Java creates default constructor in a class only if it doesn't see any constructor. Here you created your own parameterized cons. so java didn't supply her own default cons.
Either you write or don't write, the first call from child class constructor is call to parent class constructor. If you write explicit then you can call either the super() or super (args). If you don't call super cons. on first line of child class cons. then java will automatically put super() call to parent class default cons.
Here in your case, you don't have default cons. in creditcard class and have defined parameterized cons. hence java didn't supply it's default cons.
Now in child class cons. visacard, you didn't call any cons. on very first line
public VisaCard (double V_Balance, double V_interest, double V_serviceCharge, double V_limit)
{
//There is a hidden super(); call here
creditCard_Bal = V_Balance; //dose this make the VisaCard class the super?
//end constructor
}
So even though you didn't put any super call, but java supplied super() by default. Now your parent class is missing something like below
public CreditCard(){
//default cons
}
So it is bound to fail and failing. It will keep failing until you define either the no-argument cons. in parent class or call the parameterized cons. explicitely in your child class cons. very first line.
You would also like to visit below links-
https://stackoverflow.com/a/2054040
Why do this() and super() have to be the first statement in a constructor?
https://stackoverflow.com/a/12798462/6532664
As a best practice, it is good to have default cons. if you are creating parameterized cons. in your class (Until you are sure that someone will never inherit it). You never know who becomes child of your class and doesn't call parameterized cons. of your parent class hence it will fail this error. Java will look for cons. with no arguments but will find something with argument.
Hope it helps.
The assignment is to create a class called Temp that runs against the instructors TestTemp class which he provided to us for free. So far everything seems to test out pretty well except for my out put in the toString that we are supposed to use. It is supposed to format like the commented out section but doesn't seem to be working. I posed the TestTemp class and my code for the Temp class. I feel like I am missing something little but just need a nudge in the right direction and my instructor doesn't have office hours again until after the assignment is due. I also pasted the assignment instructions he added to the assignment.
The class will be called Temp
Add a compareTo method. (returns -1 if the invoking object has a lower
temp, 0 if the same, 1 if larger)
Add a static counter (object id)to keep track of how many Temperature
objects have been created(1,2,3,...)
Add a static method to tell you how many Temperature objects have been
created.
Include a toString method that displays the object as follows(assumes
3rd one created):
Object Id: 3 Temperature in F: 32.0 Temperature in C: 0.0
Note that calling getF or getC returns the value only. They do not
change the native data.
To be clear the only methods are as follows: 4 constructors, getF,
getC, setDegrees, setScale, equals, toString, compareTo and a static
getTempCount that returns the total number of objects that have been
created.
Note that the getters will return the degrees in the requested scale
rounded to a tenth of a degree. Never round the native data.
Note that the equals method will return true if the temperatures are
the same when compared in celsius (that was rounded to a tenth of a
degree).
Be sure to make great use of this() and have only one contructor do
any real work.
Besure to validate the scale and follow the default (C) if a "bad
scale" is sent in
No need to validate the degrees and worry about things such as
absolute zero and so on.
NOTE: Your Temp class must work correctly with the TestTemp class
supplied in UNIT-04-CodeSamples
//32 - 212 180 ticks
//
//0-100 1/10
//
public class TestTemp
{
public static void main(String [] args)
{
// only one constructor does any real work
Temp temp1 = new Temp(); // 0 C
Temp temp2 = new Temp(32); // 32 C
Temp temp3 = new Temp('F'); // 0 F
Temp temp4 = new Temp(32, 'F'); // 32 F
Temp temp5 = new Temp(); // 0 C
temp5.setDegrees(10);
temp5.setScale('F'); // 10 F
System.out.println("C: " + temp1.getC() ); // C: 0.0
System.out.println("F: " + temp1.getF() ); // F: 32.0
System.out.println(temp1.equals(temp4)); // true
System.out.println(temp1.equals(temp2)); // false
System.out.println("You have " + Temp.getTempCount() ); // You have 5
if( temp3.compareTo(temp5)< 0 ) //temp3 is lower than than temp5
{
System.out.println("temp3 is lower than than temp5");
}
else
{
System.out.println("temp3 is same or larger than temp5");
}
System.out.println(temp1);
/*
TEMP OBJECT #1
IN C: 0.0
IN F: 32.0
*/
}
}
public class Temp implements Comparable<Temp>
{
private double degrees;
private char scale;
private static int tempCount = 0;
private int id;
public Temp()
{
this.degrees = 0;
this.scale = 'C';
// this(0.0, 'C');
}
public Temp(double degrees)
{
this.degrees = degrees;
this.scale = 'C';
// this(degrees, 'C');
}
public Temp(char scale)
{
this.degrees = 0;
this.scale = scale;
// this(0.0, scale);
}
public Temp(double degrees, char scale)
{
this.id = ++tempCount;
this.degrees = degrees;
this.scale = scale;
//(degrees, scale);
}
public static int getTempCount()
{
return tempCount;
}
public int getId()
{
return this.id;
}
public void setScale(char scale)
{
if(scale == 'C')
{
this.scale = scale;
}
else
{
this.scale = 'F';
}
}
public void setDegrees(double degrees)
{
this.degrees = degrees;
}
public double getC()
{
if(scale == 'C')
{
return degrees;
}
else
{
return (double)(5.0 * (degrees-32)/9.0);
}
}
public double getF()
{
if(scale == 'F')
{
return (double) degrees;
}
else
{
return (double)(9.0*(degrees)/5.0)+32;
}
}
#Override
public int compareTo(Temp obj)
{
if(this.getC() < obj.getC() )
{
return -1;
}
if(this.getC() > obj.getC() )
{
return 1;
}
return 0;
}
public boolean equals(Object obj)
{
if(!(obj instanceof Temp))
{
return false;
}
Temp other = (Temp)obj;
return this.getC() == other.getC();
}
**public String toString()
{
return String.format("TEMP OBJECT ", this.id) + "\n" +
String.format("IN C: ", this.getC() ) + "\n" +
String.format("IN F: ", this.getF() );
}**
}
You need place holders in the formatter, Your toString method should be like
public String toString()
{
return String.format("TEMP OBJECT %d", this.id) + "\n" +
String.format("IN C: %.2f", this.getC() ) + "\n" +
String.format("IN F: %.2f", this.getF() );
}
Here %d for integers and %f for decimals. and the .2f limits the number of decimal places to 2. See some more examples here
Your use of String.format shouldn't require multiple creations. Just use one.
return String.format("TEMP OBJECT: $d, %nIN C: %.2f, %nIN F: %.2f", this.id, this.getC(), this.getF());
Modify the precision of the floating points by altering the value after the decimal point %.2f to %.5f will print 0.00000 instead of 0.00 for example.
If you have anymore questions on the use of format, I recommend reading the documentation for it as well to see what else it can do. Link
Edit: Added newline breaks. Forgot to mention just put %n for a newline. Do not space, after them, unless you want your newline to start with a space.
( I'm beginner )
double x = 0.5;
double y = 0.3;
String[]normal = {"x","y","cos","sin","avg"};
String[]complex = {"cos","sin","avg"};
char coordinate = (char) (new Random().nextInt(2) + 'x');
String result = "";
if(levels == 1){
String value1 = (normal[new Random().nextInt(normal.length)]);
if (value1.equals("sin") ||value1.equals("cos")){
result = value1 + "( pi *" + coordinate + ")";
}
else if(value1.equals("avg")){
result = value1 + "(" + coordinate + "," + coordinate + ")" ;
}
else{
result = value1 ;
}
}else{
String value = (complex[new Random().nextInt(complex.length)]);
if((value.equals("sin") ||value.equals("cos"))&&levels!=0 ){
result = value + "( pi *" + createFunction(levels - 1) + ")";
}
else if(value.equals("avg")&& levels !=0){
result = value +"(" + createFunction (levels - (levels-1)) + "," + createFunction (levels - (levels-1)) + ")" ;
}
else if(value.equals("avg")&& levels ==2){
result = value + "(" + createFunction (levels - 1) + "," + coordinate + ")" ;
}
else{
result = value ;
}
}
return result;
}
double functions = ....................... ;
result will be "sin(pi*cos(pi*x*y))" in String
how to calculate this string and keep in double functions
You are asking how to parse a string containing an arbitrary expression and then evaluate it to get a floating-point result.
That is quite difficult, requiring an expression parser, to convert the string into an expression tree, and an expression tree evaluator, to actually calculate the result.
You can do this using Groovy scripts. The trick is to evaluate your input as a Java-like expression:
public final class Test{
private static GroovyShell createMathShell() {
GroovyShell shell = new GroovyShell();
shell.evaluate("" +
"cos = {double x -> Math.cos(x)}\n" + // predefine functions as lambda
"sin = {double x -> Math.sin(x)}\n" + // expressions
"pi = Math.PI\n" // define pi
);
return shell;
}
public static void main(String[] args) {
GroovyShell shell = createMathShell();
// set values
shell.setVariable("x", 0);
shell.setVariable("y", 1);
// evaluate
double result = (Double) shell.evaluate("sin(pi*cos(pi*x*y))");
System.out.println(result);
}
}
Executing this code will print:
1.2246467991473532E-16
It would be wise to initialise a double and directly write the value into that variable.
Double answer = ....;
When you need the original value, just use the variable answer. When you need it as a string, just use:
String answer_string = String.valueOf(answer);
Or, for example:
System.out.println(String.valueOf(answer));
Math.sin and Math.cos methods will accept double values, and return a double. Simply write a method taking as arguments x and y to return the formula:
double myAlgorithm( double x, double y){
return Math.sin(Math.PI*Math.cos(Math.PI*x*y))
}
This will work passing x and y as int as it will be casted implicitly to double
double myAlgorithm( int x, int y){
return Math.sin(Math.PI*Math.cos(Math.PI*x*y))
}
And, if you want to pass Strings instead of types:
double myAlgorithm( String x, String y){
return Math.sin(Math.PI*Math.cos(Math.PI*(Double.parseDouble(x).doubleValue())*(Double.parseDouble(y).doubleValue())))
}
This should do it:
Double.valueOf(string);
I just started Computer Science last week, and we got a worksheet called Coins, in which I had to find out how many quarters, dimes, nickels and pennies there are in a set of coins. I am having a lot of trouble, and getting that error. Here's my code
package Coins;
public class Coins
{
private int change;
// two contructors
Change() //default constructor
{
change = 94;
}
Change( int c )
{
change = c;
}
// accessor method - change
public int getChange()
{
return Change;
}
// mutator method - change
public void setChange( int anotherChange)
{
change = anotherChange;
}
public void askUserForChange()
{
Scanner keyIn;
keyIn = new Scanner(System.in);
System.out.print("Please enter the amount of change: ");
String input = keyIn.nextLine();
int nChange = Integer.parseInt (input);
setChange(nChange);
// change = nChange
printChangex();
}
// action method - take accessor figure out coins -> output
// calculating the coins needed for the change
public void printChangeRange(int start, int end)
{
for(int c = start; c <= end; c++
{
setChange(c);
printChangex();
}
}
public void printChangex()
{
int c = change;
int quarter = c / 25;
System.out.println("quarter = " + quarter);
int a = c%25;
int dime = a / 10;
System.out.println("dime = " + dime);
int b = a%10;
int nickel = b / 5;
System.out.println("nickel = " + nickel);
int c = b%5;
int penny = c / 1;
System.out.println("penny = " + penny);
}
// instance variables - replace the example below with your own
private int x;
public Coins()
{
// initialise instance variables
x = 0;
}
public int sampleMethod(int y)
{
// put your code here
return x + y;
}
}
You have a class named Coins and are trying to give it a constructor named Change. The class and constructor must have the same name. Just pick one.
To elaborate on the error in your title, I assume that "Invalid Method Declaration, return type required" refers to the line with Change() //default constructor. Since this is in a class called Coins it is not a constructor as the comment claims. The Java compiler thinks that it is a method. All methods must have a return type, so the compiler complains.
The actual constructors are at the bottom of your code. It is standard practice to put constructors first, so I suggest that you put these poperly-named constructors at the beginning of your Coins class. You probably just need to remove the Change() constructors completely.
Also as a tip for asking questions here, it is extremel critical that you post the complete error message you are getting. My answer is based on some educated guesses and certainly don't solve all the problems in your code. Feel free to come back with more questions as you keep trying to fix your program.
This
// two contructors
Change() //default constructor
{
change = 94;
}
Change( int c )
{
change = c;
}
is unusual. You even have a constructor for the class Coins at the bottom of the file, so you would want to use that. Keep in mind that all Java classes have a constructor that are named the same as the class itself - even if it's the default constructor.
It's even more unusual that it has the magical value of 94 on instantiation...but in all seriousness, pick a class name and stick with it.
This
// accessor method - change
public int getChange()
{
return Change;
}
...is also odd. You may want to return the member variable change instead, so change that to a lower case C.