Do you see anything wrong in this code? in thosen't work well it returns a NaN.
public class Method2 extends GUIct1
{
double x=0,y=0;
void settype1 (double conv1)
{
x = conv1;
}
void settype2 (double conv2)
{
y = conv2;
}
double conversion ( double amount)
{
double converted = (amount*y)/x;
return converted;
}
}
Way it is used an i already changed the set part
Method2 convert = new Method2(); \\ method is called
.....
convert.settype1(j);
.....
convert.settype2(k);
.....
double x = convert.conversion(i);
System.out.println(x);
Well, the fact that you've got methods which set variables called get-something is pretty obviously not a good idea, and there's no indentation... but it should work. But then, you haven't shown how you're using it. Perhaps you're not actually called the setter methods?
Here's an example of the same code but with different names, and a sample of using it:
class Converter
{
double multiplier = 0;
double divisor = 0;
void setMultiplier(double multiplier)
{
this.multiplier = multiplier;
}
void setDivisor(double divisor)
{
this.divisor = divisor;
}
double convert(double amount)
{
return (amount * multiplier) / divisor;
}
}
public class Test
{
public static void main(String[] args)
{
Converter converter = new Converter();
converter.setMultiplier(3.5);
converter.setDivisor(8.5);
System.out.println(converter.convert(2)); // Prints 0.8235294117647058
}
}
Personally I'd probably make the variables final and set them in the constructor, but that's another matter...
It doesn't look like you ever call gettype1 or gettype2 so the x/y is 0/0 resulting in NaN
This can happen when x=0. Division by zero is not defined. Print out x and y before you start to calculate to see whetther they are not zero.
Related
In a case like this:
public class Order {
List<Double> prices = List.of(1.00, 10.00, 100.00);
List<Double> pricesWithTax = List.of(1.22, 12.20, 120.00);
Double sumBy(/* method reference */) {
Double sum = 0.0;
for (Double price : /* method reference */) {
sum += price;
}
return sum;
}
public List<Double> getPrices() { return prices; }
public List<Double> getPricesWithTax() { return pricesWithTax; }
}
how can I declare the sumBy method in a way that can be called like this:
Order order = new Order();
var sum = order.sumBy(order::getPrices);
var sumWithTaxes = order.sumBy(order::getPricesWithTax);
I'm not using the Java 8 API for the sum because my goal is only to understand how pass a method reference.
Your 2 methods take no argument and return an object, so that fits the Supplier.get() method.
Don't use Double for the sum variable, since that will auto-box and auto-unbox way too much.
Method can be static since it doesn't use any fields or other methods of the class.
static double sumBy(Supplier<List<Double>> listGetter) {
double sum = 0.0;
for (double price : listGetter.get()) {
sum += price;
}
return sum;
}
Better yet:
static double sumBy(Supplier<List<Double>> listGetter) {
return listGetter.get().stream().mapToDouble(Double::doubleValue).sum();
}
You seem to want a Supplier like
Double sumBy(Supplier<List<Double>> f) {
Double sum = 0.0;
for (Double price : f.get()) {
sum += price;
}
return sum;
}
Your List.of syntax was giving me errors. So I did
List<Double> prices = Arrays.asList(1.00, 10.00, 100.00);
List<Double> pricesWithTax = Arrays.asList(1.22, 12.20, 120.00);
Then I tested like
public static void main(String[] args) throws IOException {
Order order = new Order();
double sum = order.sumBy(order::getPrices);
double sumWithTaxes = order.sumBy(order::getPricesWithTax);
System.out.printf("%.2f %.2f%n", sum, sumWithTaxes);
}
Outputs
111.00 133.42
I think the Supplier<T> functional interface is what you’re looking for:
Double sumBy(Supplier<Collection<Double>> supplier) {
Collection<Double> prices = supplier.get();
}
Use Double sumBy(Supplier<List<Double>> doubles)
I don't understand how to make two doubles as input and return the biggest number.
Make a new function (method) that takes two doubles as input and return the biggest one.
My solution (trying an if-statement):
public class ex1DoubleFunction {
public static void main(String[] args) {
double a = 10;
double b = 20;
System.out.println(doublefun(a, b));
public static doublefun(a,b) {
if (a>b) {
return a;
}
else if (a<b) {
return b;
}
}
}
}
This is also consider if you have equals value.
public static double whichGreater(double first, double second) {
if(first >= second){
return first;
} else {
return second;
}
}
This is a very simple task, the solution below should do.
public static double findMax(double numOne, double numTwo){ // parameters
return Math.max(numOne,numTwo); // built in class to find the max of two nums or more
}
Also, make sure you don't put this function inside the main method because it won't work. put this inside the same class as the main method for simplicity.
This should work.
public static double doublefun(double a, double b) {
if ( a > b) {
return a;
} else {
return b;
}
}
You can also use ternary operator.
return (a>b)?a:b;
For my assignment, I have been asked to create a test harness which provides feedback on whether the following sums are true. For this question, I will only provide one sum as an example. I have been asked to produce the following:
TestCalculator has a method called testParser() which:
Tests that x("12 + 5") returns a Double with the value 17
I have been given a template in which to set this out on which looks like this:
Template
public class TestCalculator {
Double x;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
return new Double(0);
}
public void testParsing() {
if (//condition) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
And this is what I've managed to come up with so far:
Current program...Main class
public class Main {
public static void main(String[] args) {
TestCalculator call = new TestCalculator();
call.testParsing();
}
}
TestCalculator class
public class TestCalculator {
Double x;
Double doubleObject = 1.0;
/*
* Adds the parameter x to the instance variable x and returns the answer as a Double.
*/
public Double x(Double x){
System.out.println("== Adding ==");
this.x = 12.0;
x = 5.0;
return new Double(0);
}
public void testParsing() {
if (x(doubleObject) == 17) {
System.out.println("Adding Success");}
else {
System.out.println("Adding Fail");
}
}
}
I have two main queries. Firstly, I have been asked to test if "x("12 + 5") returns a Double with the value 17". I can see that this has been laid out so that the sum is a data type of String and I am confused as to why or how you would perform this calculation using the string data type.
Secondly, Within my current version of the program, the output returns that the adding calculation failed because I cannot access the returned double value of the calculation. But I am unsure of how I would access that value in my if statement and also return the output of the calculation and put it into the Double value that is returned in the method.
I have tried to make the question as clear and concise as possible for the reader to understand, any help on this would be greatly appreciated, thanks.
to return a new value that adds two values consider
public Double x(Double x){
System.out.println("== Adding ==");
//Sum here
this.x = x;
return new Double(x + 5);
}
Called as
if (x(12.0) == 17.0) {
first i would like to start saying that i am new to programing and i don t know much. with that said i would appreciate if anyone could help me with my program that it is supposed to read 2 fractions and an operator for example "2/3 + 4/5". i have some of the code done but it still give me an error when i run it here is what i have so far:
public class Fraction {
private static int numer;
private static int denom;
public Fraction(int num, int den)
{
numer = num;
denom = den;
simplify();
}
int findGcd(int a, int b)
{
int temp;
while(b != 0)
{
temp = b;
b = a % b;
a = temp;
}
return a;
}
void simplify()
{
int gcd = findGcd(numer, denom);
numer /= gcd;
denom /= gcd;
}
public int getNumer(){
return numer;
}
public int getDenom(){
return denom;
}
Fraction add(Fraction x) {
Fraction result;
if (x.getDenom()== getDenom()) {
result = new Fraction(x.getNumer() + getNumer(), denom);
} else {
denom = this.getDenom() * x.getDenom();
numer = this.getNumer() * x.getDenom() + x.getNumer() * this.getDenom();
return new Fraction(numer,denom);
}
return result;
}
public String toString(){
return (Integer.toString(numer) + "/" +
Integer.toString(denom));
}
public static void main (String []args){
Fraction a = new Fraction(1,3);
Fraction b = new Fraction(4,5);
System.out.println(a.toString());
System.out.println(b.toString());
}
}
thank you for your help i really appreciate it.
Why are you making your fields static? static fields belong to the class as opposed to each instantiation (not what you want here). Try removing the static keyword.
On another note, you mentioned that you'd like to read input from the user. You might want to look into using a Scanner for this (in case you don't already know about this handy class).
Once you read the input, something like 2/3 + 4/5, you can split your string using a space as your delimiter. Now, you can parse a fraction from the first (2/3) and third (4/5) elements of the newly formed string array, and perform the operation that corresponds to the second element of the array (+).
There is a difference between static variable and instance variable.
Static variable is a class variable which is common for all instances.. So, if you change these variables for one instance, it will be changed for all the instances.
Instance variable, on the other hand, are specific to each instance.. They are binded to an instance of a class.
That being said.. You need to modify your code a little bit..
Change your static variables in your class to instance variables..
private static int numer;
private static int denom;
The above two variables should be instance variables.. So that they are unique for each instance you create for your class..
So, change them to: -
private int numer;
private int denom;
And for reading user input, A.R.S has already given you link to a valuable class..
I read the next answer about passing function as parameter.
Still, I don't get the idea. My function can get any function: sin(x), cos(x), etc.
As I understood, I can create an interface, for example:
public interface functionI<T> {
}
that would wrap It.
Now I have my function:
public void needToDo(functionI<Integer> a, int x0Par, int hPar){
}
(needToDo, for example, need to substitue the x of the function n x0par and hPar, and find the Max. If I got sin(x), I need to find the max of sin(x0Par) and (sin(hPar)).
I didn't understand how I use it in my function. How will I know what to do when I got the function, that can be anything (polynomial, sin(x), and so on)
Something like this:
public interface Function1<RESULT,INPUT> {
RESULT call(INPUT input);
}
public class Sin implements Function1<Double,Double> {
public static final Sin instance = new Sin();
private Sin() {
}
public Double call(Double x) {
return Math.sin(x);
}
}
public Double needToDo(Function1<Double,Double> aFunction, Double x0Par, Double hPar) {
Double d1 = aFunction.call(x0Par);
Double d2 = aFunction.call(hPar);
return d1 > d2 ? d1 : d2;
}
public static void main(String[] args) {
Double x0Par = 10.2;
Double hPar = 1.9;
Double ret = needToDo(Sin.instance, x0Par, hPar);
System.out.println(ret);
}
It doesn't quite work like that; you cannot pass arbitrary functions as parameters in Java, instead you pass objects which have specific, often generic sounding, functions.
So you could define a MathOperation interface, which has an execute method, taking a double and returning a double.
public interface MathOperation {
double execute(double x);
}
and then you can create
public class Sin implements MathOperation {
public double execute(double x) { return Math.sin(x); }
}
and have a function that uses it like
public void needToDo(MathOperation op, double x) {
System.out.println(op.execute(x));
}
You could create an on-the-fly function for needToDo like
...
needToDo(new MathOperation() {
public double execute(double x) { return x * 2.0; }
});
...
But you can't pass Math.sin as a parameter. There are reflection tricks you can do, but that's another issue.