It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
this is a homework problem, and I am having trouble understanding how I can create a .add() method in a class Distance.
class Distance has two integer instance variables:
private int feet;
private int inches;
It has a no argument constructor that initializes a Distance with zero feet and zero inches.
It has a two argument constructor that accepts two positive integers for feet and inches, and throws and exception if they are negative or if inches is greater than 11.
It also has get/set methods for the instance variables. My get/set methods:
public void setFeet(int f){
feet = f;
}
public void setInches(int in){
inches = in;
}
public int getFeet(){
return feet;
}
public int getInches(){
return inches;
}
My first question to anyone willing to answer: Is this how I am supposed to set up these get/set methods? I am unsure of myself.
My second problem lies with creating a method add() that adds another Distance object to itself. That is,
w1 = new Distance(4,9);
w2 = new Distance(3,6);
w1.add(w2); //w1 becomes 8 feet, 3 inches.
So far, I have this:
public int add(Distance d) {
int df = d.getFeet();
int di = d.getInches();
int a = this.feet;
int b = this.inches;
int c = a.getFeet();
int d = b.getInches();
int sumInches, sumFeet, temp;
sumInches =di + d;
sumFeet = df + c;
if (sumInches>11) {
temp = sumInches-11;
sumFeet = sumFeet+1;
sumInches = temp;
}
this.feet = sumFeet;
this.inches = sumInches;
}
But I am unsure if this would even compile (I don't have access to a computer where I can install a compiler right now). Can someone examine this and explain to me why this might be wrong?
int a = this.feet;
int b = this.inches;
Is a bit verbose...
int c = a.getFeet();
int d = b.getInches();
Won't compile, recall that primitive values (int, in our case) does not have methods.
Here's a solution, (added support for varargs, allowing infinite Distances):
public void add(Distance... distance) {
for(Distance d : distance) {
feet += d.getFeet();
if(inches + d.getInches >= 12)
feet++;
inches += d.getInches() % 12;
}
}
With this, you can easily add like this:
d1.add(d2, d3, d4, d5);
public void setInches(int in){
feet = in;
}
I assume that's a typo because you are assigning the in value to feet instead of inches.
public int getInches(){
return Inches;
}
Another typo. Java is case-sensitive so "Inches" is not the same as "inches".
Other than those, the getters/setters look fine.
As for the add() method... There's no reason to create those "a", "b", "c" and "d" variables
int a = this.feet;
int b = this.inches;
int c = a.getFeet();
int d = b.getInches();
You can just use this.feet and this.inches directly. It's not wrong per-se, just unnecessary and clutters the code. Also, I would highly recommend always creating meaningful variable names. "a", "b", "c" code is difficult to read. Variable names should be expressive.
Also, in your algorithm, you would need to subtract 12 from the summed inches.
So the add method could be written more succinctly like this:
public void add(Distance d)
{
int newFeet = this.feet + d.feet;
int newInches = this.inches + d.inches;
if (newInches > 11)
{
newFeet++;
newInches = newInches - 12;
}
this.feet = newFeet;
this.inches = newInches;
}
Personally, I would implement that logic by converting everything to inches and then using division and the modulus operator (%) to determine the feet and inches but I'll leave that as an exercise for you if you care.
My first question to anyone willing to answer: Is this how I am supposed to set up these get/set methods? I am unsure of myself.
Your getters/setter look correct; the point of them is to encapsulate the member variables so that they are not "modified" accidentally (restricting access). You probably want to initialize your member variables to some "default" value - in this case, I initialized them to 0 below.
Note: By default, the compiler will initialize them to 0.
private int feet = 0;
private int inches = 0;
public void setFeet(int f){
feet = f;
}
public void setInches(int in){
feet = in;
}
public int getFeet(){
return feet;
}
public int getInches(){
return inches;
}
My second problem lies with creating a method add().
About your "add" method, you probably want to change your local variables to be something more "descriptive", it will help "readability" and "maintainability" in the long run.
Since your "Distance" class already contains the member variables "feet" and "inches", there is no point of setting these values to a local variable. You can just access them directly -- along with any of the class's getters/setters.
public int add(Distance newDistance) {
int newDistanceFeet = newDistance.getFeet();
int newDistanceInches = newDistance.getInches();
int sumInches = newDistanceInches + this.getInches();
int sumFeet = newDistanceFeet + this.getFeet();
// Now we can check to see if any conversion are needed.. Note: 12 inches = 1 foot
//
sumInches += (sumInches % 12);
sumFeet += (sumInches / 12);
// Now set the newly added inches/feet to the class's member variables
//
this.setFeet(sumFeet);
this.setInches(sumInches);
}
Update your add() to :-
public int add(Distance d) {
int df = d.getFeet();
int di = d.getInches();
int a = this.feet;
int b = this.inches;
ERROR : c and d are integers and not Distance objects. You don't require c and d integers.
int sumInches, sumFeet, temp;
sumInches =di + b;
sumFeet = df + a;
if (sumInches>11) {
temp = sumInches-11;
sumFeet = sumFeet+1;
sumInches = temp;
}
this.feet = sumFeet;
this.inches = sumInches;
Your problem is here,
int a = this.feet;
int b = this.inches;
int c = a.getFeet();
int d = b.getInches();
Since a and b are int variable. They do not have getFeet() and getInches() method.
Change your add() method to
public int add(Distance d) {
int df = d.getFeet();
int di = d.getInches();
int sumInches, sumFeet, temp;
sumInches =di + this.inches;
sumFeet = df + this.feet;
if (sumInches>11) {
temp = sumInches-11;
sumFeet = sumFeet+1;
sumInches = temp;
}
this.feet = sumFeet;
this.inches = sumInches;
}
The basic idea is correct but you were doing some things wrong, consider instead:
public int add( Distance d ){
feet += d.feet;
inches += d.inches;
if( inches >= 12 ){
inches = inches - 12;
feet++;
}
}
The biggest issue i saw was
int a = this.feet;
int d = a.getFeet();
here a is an int not a Distance object hence you cant call getFeet()
Since it is a homework problem, I am not providing the complete solution. Since you have attempted the add method, I will optimize it further and provide the same here with comments
public void add(Distance distance) {
int extraFeet=0; /*Intializing the extra Feet*/
extraFeet = (this.inches+distance.getInches())/11; /*Calculating the additional feet*/
if(extraFeet >0)
this.inches = (this.inches+distance.getInches())%11; /*if extra feet is greater than zero thn the remainder is the inches*/
else
this.inches +=distance.getInches(); /*else teh remainder is the sum of the inches*/
this.feet += (distance.getFeet()+extraFeet);
}
Related
I'm trying to create a method in Java that prints the fib series up to the number passed to the method. My issue is that I'm required to use an int return type to return the series and I cannot use recursion.
My First Idea
My original idea was like shown. Which works just fine. It takes an argument of type int and returns void simply printing the numbers as they are calculated.
public void fibonacci(int num) {
int a = 0;
int b = 0;
int c = 1;
for (int i = 0; i < num; i++) {
a = b;
b = c;
c = a + b;
System.out.print(c + ", ");
}
}
What The Question Asks For
The code below shows what I was tasked to do. It asked for a method that takes an argument of type int and returns type int.
public int fibonacci(int num) {
//some code...
return x; //This is what confuses me. I know this isn't right.
}
To me this just seems impractical and maybe even impossible to use an int return type. I'm wondering if anyone knows a way this is possible.
Expected Output:
//Method call in driver class.
fibonacci(5);
//This would print to console.
1, 1, 2, 3, 5
You can use the equation [(h)^a - (j)^a] * [1/sqrt(5)].
'a' is fibonacci number wanted
'h' is [1 + sqrt(5)] / 2
'j' is [1 - sqrt(5)] / 2
public static int returnFibonacci(int a) {
double firstTerm; // calculate h
double secondTerm; //calculate j
double fib; //calculate 1/sqrt(5) with firstTerm and secondTerm
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Hey Guys I am learning java i wrote this simple code i can not find any error. i can't get Bike2 .getTime. thanks for reading
public class ConstructorEx3 {
int Speed;
int Distance;
int Minute;
public int getTime (){
return ((Distance/Speed)*Minute);
}
ConstructorEx3 (){
Distance = 60;
Speed = 30;
Minute = 60;
}
ConstructorEx3 (int D, int S, int M){
Distance = D;
Speed = S;
Minute = M;
}
public static void main (String []arsh){
ConstructorEx3 Bike1,Bike2;
Bike1 = new ConstructorEx3();
Bike2 = new ConstructorEx3(40,80,60);
System.out.println("Bike one is travelling at : "+ Bike1.getTime());
System.out.println("Bike two is travelling at : "+ Bike2.getTime());
}
}
Because it's integer operation (40/80)*60 will give you 0. Note here that in integer calculation 40/80 will be 0 not 0.5 you need to use double values instead of int in your program to get exact answer (for your particular case).
Some suggestions related to conventions,
Choose meaningful name for your class which describe it's purpose i.e TimeCalculator, Bike
Start variable name with small letter distance not Distance
Same way instance variable name should also start with small letter bike1 and not Bike1
Better to use this.distance in constructor instead of Distance = D
Distance = 40;
Speed = 80;
Minute - 60;
Distance / Speed = 0.5;
Since you are working with an int, the .5 is cascaded. Finally, you get 0 * Minute = 0 * 60 = 0;
The best way is to convert the value as double and convert back. Note that it's lossy as you don't get accurate results when dealing with double to int conversion.
See how I solved your problem in the getTime() method:
public class ConstructorEx3 {
int Speed;
int Distance;
int Minute;
public int getTime (){
double v = ((double)Distance/(double)Speed);
v= v * (double)Minute;
return (int)v;
// return ((Distance/Speed)*Minute);
}
ConstructorEx3 (){
Distance = 60;
Speed = 30;
Minute = 60;
}
ConstructorEx3 (int D, int S, int M){
Distance = D;
Speed = S;
Minute = M;
}
public static void main (String []arsh){
ConstructorEx3 Bike1,Bike2;
Bike1 = new ConstructorEx3();
Bike2 = new ConstructorEx3(40,80,60);
System.out.println("Bike one is travelling at : "+ Bike1.getTime());
System.out.println("Bike two is travelling at : "+ Bike2.getTime());
}
}
Output:
Bike one is travelling at : 120
Bike two is travelling at : 30
I am trying to make as generic as possible method for tweening between various types of values.
So, given a start and end value thats, say, either an Int,Float or Double as well as the number of steps (int), it will return values evenly distributed along those steps in the same type.
However, I am starting to suspect;
a) My knowledge of generics is terrible.
b) This might not be possible :(
So, just to be clear, one example;
SpiffyTween<Double> meep = new SpiffyTween<Double>(1d,10d, 100);
while (meep.hasNext()){
Log.info("value="+meep.next());
}
Would return 0.0,0.1,0.2..etc upto 9.9
But SpiffyTween could also work with other number types without needing separate code for each.
Heres the code I have right now;
class SpiffyTween<T extends Number> implements SpiffyGenericTween<T>
{
static Logger Log = Logger.getLogger("SpiffyTween <Number>");
private T start;
private T end;
int totalsteps=0;
int CurrentStep = 0;
ArrayList<T> steps = new ArrayList<T>();
public SpiffyTween(T start,T end, int steps) {
this.start = start;
this.end = end;
this.totalsteps = steps;
precalculate();
}
private void precalculate() {
//calc step difference
double dif = ((end.doubleValue() -start.doubleValue())/totalsteps);
Log.info("dif="+dif);
int i=0;
while(i<totalsteps){
T stepvalue = (T)((Number)(start.doubleValue() +(dif*i)));
steps.add(stepvalue);
Log.info("add step="+stepvalue);
i++;
}
}
public T next(){
T currentVal = steps.get(CurrentStep);
CurrentStep++;
return currentVal;
}
#Override
public boolean hasNext() {
if (CurrentStep<totalsteps){
return true;
}
return false;
}
}
This works...ish.
While the numbers come out aproximately right occasionally theres values like;
9.600000000000001
or
2.4000000000000004
I am assuming thats to do with the unchecked type conversion here;
T stepvalue = (T)((Number)(start.doubleValue() +(dif*i)));
But I cant work out how to do it better.
Whatever the solution (if theres one), my longterm plan is to try to make similar code that can also work on arrays of various number types. So, you could tween between 3 dimensional points by feeding it an array of the x/y/z co-ordinates of the start and end.
Also, possibly more relevantly, in the code example here its basic addition being done. I probably want other types of tweening possible, so that would make the maths more complex.
Is the better route to convert to, say, BigNumber, and then (somehow) back to the initial T later after all the processing is done?
Thanks in advance for any help or pointers.
YOu don't really need Generics to write code once. Consider the code below. Your exercise is to extend to other dimensions and to ensure caller does not use less than one step:
Tween Class
package com.example.stepup;
public class Tween {
public static int[] get1DimSteps (int start, int end, int steps) {
double[] preciseResult = get1DimSteps((double) start, (double) end, steps);
int[] result = new int[steps];
for (int i=0; i<steps; i++) {
result[i] = (int) (preciseResult[i] + 0.5D);
}
return result;
}
public static double[] get1DimSteps (float start, float end, int steps) {
double[] result = get1DimSteps((double)start, (double)end, steps);
return result;
}
public static double[] get1DimSteps (double start, double end, int steps) {
double distance;
double stepSize;
double[] result = new double[steps];
distance = end - start;
stepSize = distance / steps;
for (int i=0; i < steps; i++) {
result[i] = start + stepSize*i;
}
return result;
}
}
StepupTest Class
package com.example.stepup;
public class StepupTest {
public static void main(String[] args) {
// get steps from "start" to "finish"
int startI = -1;
int endI =999;
float start = (float) startI;
float end = (float) endI;
double startD = (double) startI;
double endD = (double) endI;
int numberOfSteps = 100;
double[] steps = Tween.get1DimSteps( start, end, numberOfSteps);
double[] stepsD = Tween.get1DimSteps(startD, endD, numberOfSteps);
int[] stepsI = Tween.get1DimSteps(startI, endI, numberOfSteps);
for (int i=0; i < numberOfSteps; i++) {
System.out.println(" " + i + ". " + steps[i] + ", " + stepsD[i] + ", " + stepsI[i]);
}
}
}
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 10 years ago.
I have made these codes just for fun to train a little bit since i'm a 15 year old beginner in java but don't know where the problem is and what to put after the "lol" method
thank you for the help
public class mathClass {
static int a = 10;
static int b = 15;
static int c = 22;
static int result = 0;
static double counter = 0.25;
public static void main(String[] args) {
double resultone;
double resulttwo;
double resultthree;
double resultfour;
double resultfive;
resultone = a + b;
resulttwo = a + c;
resultthree = a * c;
resultfour = b / c;
resultfive = b % a;
lala(resultone);
lala(resulttwo);
lala(resultthree);
lala(resultfour);
lala(resultfive);
}
public static void lala(double output) {
result++;
System.out.println("result " + result + " is " + output);
}
public static void lol() {
while(counter < 10){
counter++;
int number = 0;
number++;
System.out.println("Counter "+ number + " is " + counter);
}
}
}
i want to also get the lol method text
If you are trying to have it output 10 lines
public static void lol() {
for (int i = 0; i < 10; i++) {
counter++;
System.out.println("Counter "+ i + " is " + counter);
}
}
Next add:
public static void main(String[] args) {
lol();
You have to add a closing curly bracket } after the lol() method. There is one missing at the end. That bracket will close the class and resolve the compilation error.
Along with the missing brace, you never call lol() in your main method. If it isn't being called, how would it run?
I think the problem is that division is not giving results as expected
instead of
static int a = 10;
static int b = 15;
static int c = 22;
static int result = 0;
use
static double a = 10.0;
static double b = 15.0;
static double c = 22.0;
static double result = 0.0;
resultfour = b / c;
Dividing an int by an int gives you an int as a result. In this case, 15 / 22 = 0, since 0 is the largest int value less than or equal to 15.0 / 22.0.
Either make a,b,c,d doubles, or cast one of the values while doing the division...
resultfour = (double)b / c;
Say I have the following three constants:
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
I want to take the three of them and use Math.max() to find the max of the three but if I pass in more then two values then it gives me an error. For instance:
// this gives me an error
double maxOfNums = Math.max(MY_INT1, MY_INT2, MY_DOUBLE2);
Please let me know what I'm doing wrong.
Math.max only takes two arguments. If you want the maximum of three, use Math.max(MY_INT1, Math.max(MY_INT2, MY_DOUBLE2)).
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
If possible, use NumberUtils in Apache Commons Lang - plenty of great utilities there.
https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/math/NumberUtils.html#max(int[])
NumberUtils.max(int[])
Math.max only takes two arguments, no more and no less.
Another different solution to the already posted answers would be using DoubleStream.of:
double max = DoubleStream.of(firstValue, secondValue, thirdValue)
.max()
.getAsDouble();
Without using third party libraries, calling the same method more than once or creating an array, you can find the maximum of an arbitrary number of doubles like so
public static double max(double... n) {
int i = 0;
double max = n[i];
while (++i < n.length)
if (n[i] > max)
max = n[i];
return max;
}
In your example, max could be used like this
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String[] args) {
double maxOfNums = max(MY_INT1, MY_INT2, MY_DOUBLE1);
}
Java 8 way. Works for multiple parameters:
Stream.of(first, second, third).max(Integer::compareTo).get()
I have a very simple idea:
int smallest = Math.min(a, Math.min(b, Math.min(c, d)));
Of course, if you have 1000 numbers, it's unusable, but if you have 3 or 4 numbers, its easy and fast.
Regards,
Norbert
Like mentioned before, Math.max() only takes two arguments. It's not exactly compatible with your current syntax but you could try Collections.max().
If you don't like that you can always create your own method for it...
public class test {
final static int MY_INT1 = 25;
final static int MY_INT2 = -10;
final static double MY_DOUBLE1 = 15.5;
public static void main(String args[]) {
double maxOfNums = multiMax(MY_INT1, MY_INT2, MY_DOUBLE1);
}
public static Object multiMax(Object... values) {
Object returnValue = null;
for (Object value : values)
returnValue = (returnValue != null) ? ((((value instanceof Integer) ? (Integer) value
: (value instanceof Double) ? (Double) value
: (Float) value) > ((returnValue instanceof Integer) ? (Integer) returnValue
: (returnValue instanceof Double) ? (Double) returnValue
: (Float) returnValue)) ? value : returnValue)
: value;
return returnValue;
}
}
This will take any number of mixed numeric arguments (Integer, Double and Float) but the return value is an Object so you would have to cast it to Integer, Double or Float.
It might also be throwing an error since there is no such thing as "MY_DOUBLE2".
int first = 3;
int mid = 4;
int last = 6;
//checks for the largest number using the Math.max(a,b) method
//for the second argument (b) you just use the same method to check which //value is greater between the second and the third
int largest = Math.max(first, Math.max(last, mid));
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
if you want to do a simple, it will be like this
// Fig. 6.3: MaximumFinder.java
// Programmer-declared method maximum with three double parameters.
import java.util.Scanner;
public class MaximumFinder
{
// obtain three floating-point values and locate the maximum value
public static void main(String[] args)
{
// create Scanner for input from command window
Scanner input = new Scanner(System.in);
// prompt for and input three floating-point values
System.out.print(
"Enter three floating-point values separated by spaces: ");
double number1 = input.nextDouble(); // read first double
double number2 = input.nextDouble(); // read second double
double number3 = input.nextDouble(); // read third double
// determine the maximum value
double result = maximum(number1, number2, number3);
// display maximum value
System.out.println("Maximum is: " + result);
}
// returns the maximum of its three double parameters
public static double maximum(double x, double y, double z)
{
double maximumValue = x; // assume x is the largest to start
// determine whether y is greater than maximumValue
if (y > maximumValue)
maximumValue = y;
// determine whether z is greater than maximumValue
if (z > maximumValue)
maximumValue = z;
return maximumValue;
}
} // end class MaximumFinder
and the output will be something like this
Enter three floating-point values separated by spaces: 9.35 2.74 5.1
Maximum is: 9.35
References Java™ How To Program (Early Objects), Tenth Edition
Simple way without methods
int x = 1, y = 2, z = 3;
int biggest = x;
if (y > biggest) {
biggest = y;
}
if (z > biggest) {
biggest = z;
}
System.out.println(biggest);
// System.out.println(Math.max(Math.max(x,y),z));