I want to create a method that calculates multiplication of an integer and a bigdecimal. I search on Google and forums, but I didn't find anything.
import java.math.BigDecimal;
private Integer quantite;
private BigDecimal prixUnit;
public Integer getQuantite() {
return quantite;
}
public void setQuantite(Integer quantite) {
this.quantite = quantite;
}
public BigDecimal getPrixUnit() {
return prixUnit;
}
public void setPrixUnit(BigDecimal prixUnit) {
this.prixUnit = prixUnit;
}
public BigDecimal methCal(BigDecimal quantite, BigDecimal prixUnit) {
this.prixUnit=prixUnit;
BigDecimal j = new BigDecimal(quantite);
this.j = quantite;
return quantite*prixUnit;
}
How can I fix this?
To multiply an integer (or byte/short/float/double) with a BigInteger (or BigDecimal), you must convert the native number to BigInteger/BigDecimal first.
// int parameter can be int or Integer
public static BigInteger multiply ( int a, BigInteger b ) {
return BigInteger.valueOf( a ).multiply( b );
}
// BigInteger <> BigDecimal
public static BigDecimal multiply ( int a, BigDecimal b ) {
return BigDecimal.valueOf( a ).multiply( b );
}
// same for add, subtract, divide, mod etc.
Note: valueOf is not the same as new, and for different reasons on BigDecimal and BigInteger.
In both cases, I recommend valueOf over new.
I see that you added your code, nice.
It doesn't work because Integer is mixed with BigDecimal, and also * does not work with BigDecimal.
If you compare it with my code, the fix should be obvious:
public BigDecimal methCal ( int quantite, BigDecimal prixUnit ) {
return BigDecimal.valueOf( quantite ).multiply( prixUnit );
}
Google definitely could have helped you, if you know what to look for:
https://docs.oracle.com/javase/9/docs/api/java/math/BigDecimal.html#BigDecimal-int-
This is one of the constructors for BigDecimal, which allows you to do the following:
BigDecimal five = BigDecimal.valueOf(5);
BigDecimal seven = BigDecimal.valueOf(2).add(five);
Seeing as you stated you wanted to multiply an int and a BigDecimal, this would be achieved as follows:
BigDecimal result = yourBigDecimal.multiply(BigDecimal.valueOf(yourInt));
And, supposing you want this result as an int:
int intResult = result.intValue();
Keep in mind that this throws away the fraction though. If you want rounding instead:
int intResult = result.round(0, RoundingMode.HALF_UP).intValue();
Try this:
import java.math.*;
public class calculator {
public static void main(String[] args) {
BigDecimal value1 = new BigDecimal("3383878445");
BigDecimal returnValue = calculation(2, value1);
System.out.println("value is:" + returnValue);
}
public static BigDecimal calculation(int no1, BigDecimal no2) {
BigDecimal value = BigDecimal.valueOf(no1).multiply(no2);
return value;
}
}
These methods from the Java API will be helpful.
public BigDecimal multiply(BigDecimal multiplicand)
Returns a BigDecimal whose value is (this × multiplicand), and whose scale is (this.scale() + multiplicand.scale()).
Parameters:
multiplicand - value to be multiplied by this BigDecimal.
Returns:
this * multiplicand
public BigDecimal(int val)
Translates an int into a BigDecimal. The scale of the BigDecimal is zero.
Parameters:
val - int value to be converted to BigDecimal.
Related
Since Java doesn't allow to return two types in one method, I thought best way to do it is to use get methods.
Simply, I wanted computer to generate two random numbers, and if they were not the same I wanted it to print sum of them. If they were the same, I wanted it to roll once more and sum all of the rolls. Until here, it was okay, but then I wanted to see not only sum, but also the numbers that computer generated randomly before adding them up. Therefore, it had to be several return types.
But it prints 0 three times instead.
Can you help me with this? I want to learn what is wrong exactly with this code and if it can be done neater and cleaner? I know Java loves long ways..
Thank you.
class App {
public static int monopolyRoll(int side) {
double randomNumber = Math.random();
randomNumber = randomNumber * side;
randomNumber = randomNumber + 1;
int randomInt = (int) randomNumber;
return randomInt;
}
private int roll1 = monopolyRoll(6);
private int roll2 = monopolyRoll(6);
public int userRolls() {
if (roll1 != roll2) {
return roll1 + roll2;
} else {
int roll3 = monopolyRoll(6);
int roll4 = monopolyRoll(6);
return roll1 + roll2 + roll3 + roll4;
}
}
private static int first;
private static int second;
private static int third;
public App(int first, int second, int third) {
App.first = roll1;
App.second = roll2;
App.third = userRolls();
}
public static int getFirst() {
return first;
}
public static int getSecond() {
return second;
}
public static int getThird() {
return third;
}
public static void main(String[] args) {
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
}
}
Math.random() works, but you never actually call it in your application. This is what your application does:
int first = getFirst();
int second = getSecond();
int third = getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
That's it. Aside from the single return statements in those getter methods and the declared-but-never-assigned integers they return (so, zeroes), none of that other code ever executes.
I suspect this is coming from a bit of a misunderstanding on your part about the static keyword. By sprinkling around the static keyword until the code compiled, what you've done is create something that's syntactically correct but doesn't do anything :)
As a bit of a learning exercise, try moving all of the business logic out of the App class, leaving only the main() method as the application's entry point. And removing all static keywords from the new class you create. This should make the use of that class more clear.
Something like:
class Roller {
private int roll1;
private int roll2;
// other private variables
private int monopolyRoll(int side) {
// your code
}
// your other methods, also private and non-static
public Roller(int first, int second, int third) {
this.first = roll1;
this.second = roll2;
this.third = userRolls();
}
// and so on
}
The idea here is to make things instance-based (non-static) by default. Also make things private by default until explicitly needed to be accessed outside the class. Currently the only things your class needs to expose publicly are the constructor and the getters.
Then in the main() method you'll need to create an instance of your class to use it. Something like this:
Roller roller = new Roller(1, 2, 3);
int first = roller.getFirst();
int second = roller.getSecond();
int third = roller.getThird();
System.out.println(first);
System.out.println(second);
System.out.println(third);
I am very new to streams in java 8 so my approach could be wrong.
I have 2 objects as follows
object1 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
String desc;
}
object2 {
BigDecimal amount;
Code1 code1;
Code2 code2;
Code3 code3;
}
So I want to collect all object1 where code1 && code2 && code3 are same and then sum the amount add it to object2 list.
I do not have a code to do it...I want to write a code that does the job
I am trying to implement something from http://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
Or compute the sum of all salaries by department:
// Compute sum of salaries by department
Map<Department, Integer> totalByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment,
Collectors.summingInt(Employee::getSalary)));
Thanks to JB Nizet for pointing me in the right direction.
I had to modify my object2
public class CodeSummary {
Double amount;
CodeKey key;
//getters and setters
}
public class CodeKey {
String code1;
String code2;
String code3;
//getters and setters
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CodeKey)) return false;
CodeKey that = (CodeKey) o;
if (!code1.equals(that.code1)) return false;
if (!code2.equals(that.code2)) return false;
if (!code3.equals(that.code3)) return false;
return true;
}
#Override
public int hashCode() {
int result = code1.hashCode();
result = 31 * result + code2.hashCode();
result = 31 * result + code3.hashCode();
return result;
}
}
iterate over object1 and populate object2. Once i had my object2 (now codeSymmary) populated. i could use the method below to do the job.
Map<CodeKey, Double> summaryMap = summaries.parallelStream().
collect(Collectors.groupingBy(CodeSummary::getKey,
Collectors.summingDouble(CodeSummary::getAmount))); // summing the amount of grouped codes.
If anyone is using this as an example. then make sure you override the equal and hashcode function in your key object. else grouping will not work.
Hope this helps someone
Why does this work only up to n=90 or so?
Trying to calculate the 94th fibonacci number gives the incorrect result.
Same thing happens if I use the Integer class instead of Long.
import java.util.HashMap;
public class FDP {
private static HashMap<Long, Long> fib = new HashMap<Long, Long>();
private static Long calculateFib(Long n) {
if(fib.get(n)==null){
Long temp = calculateFib(n-1) + calculateFib(n-2);
fib.put(n, temp);
return temp;
}
else{
return fib.get(n);
}
}
}
public static void main(String[] args) {
fib.put(0L, 0L);
fib.put(1L, 1L);
System.out.println(calculateFib(90L)); //success
System.out.println(calculateFib(94L)); //garbage??
}
}
here is a list of the Fibonacci numbers:
http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibtable.html
Its an overflow.
The 94th Fibonacci number is: 19740274219868223167
Long.MAX_VALUE is:
9223372036854775807
19740274219868223167 - 9223372036854775807 > 0
You can use BigInteger to handle numbers with arbitrary length.
You reach the limitations of the type Long (64bit), use BigInteger instead
I would like some help in casting a pointer to a C struct to a jna strucuture. I am using jna to receive a callback function from a dll, the function has a parameter that is a pointer to a C struct, when a I try to cast the pointer to a jna structure I get wrong structure values.
That is the C struct:
typedef struct
{
int x;
int y;
}Point;
Point *gpt;
typedef struct
{
int x;
int y;
Point pt1;
}Point2;
Point2 *gpt2;
That is the callback function in C with a pointer (void *params) to Point2 sctruct:
void __stdcall PointCallback(void *params, int param_size)
So, I've made this code in java to receive the callback and get the original struct:
// Point.java
package Callback.UsePointLib;
import com.sun.jna.Structure;
public class Point extends Structure
{
public static class ByValue extends Point implements Structure.ByValue {}
public int x;
public int y;
}
//Point2.java
package Callback.UsePointLib;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
public class Point2 extends Structure {
public int x;
public int y;
Point pt1;
public Point2(Pointer p){
super(p);
}
}
Callback implementation:
//UsePointLib.java
public interface IFuncCallback extends StdCallCallback{
void callback(Pointer Params, int ParamSize);
}
public class FuncCallback implements IFuncCallback{
#Override
public void callback(Pointer Params, int ParamSize) {
Point2 pt2; // = new Point2();
pt2 = new Point2(Params);
System.out.println("pt2.x = "+pt2.x); **<- I get zero here instead of four**
System.out.println("pt2.y = "+pt2.y); **<- I get zero here instead of five**
System.out.println("pt2.pt1.x = "+pt2.pt1.x);**<- pt1 is null, throwing exception**
System.out.println("pt2.pt1.y = "+pt2.pt1.y);**<- same as pt1.**
}
}
I've made a C program to access the dll and receive the callback and it works ok, it receives the correct values. So, the problem is my java code. I've tried many alternatives with no success.
Please, I'd appreciate any help on that.
Thanks,
Fernando.
EDIT
I've modified the code and it works partially.
//UsePointLib.java
public interface IFuncCallback extends StdCallCallback{
void callback(Pointer Params, int ParamSize);
}
public class FuncCallback implements IFuncCallback{
#Override
public void callback(Pointer Params, int ParamSize) {
Point2 pt2; // = new Point2();
pt2 = new Point2(Params);
*pt2.read();* **<--Modification**
System.out.println("pt2.x = "+pt2.x); **<- I get the correct value (four)**
System.out.println("pt2.y = "+pt2.y); **<- I get the correct value (five)**
System.out.println("pt2.pt1.x = "+pt2.pt1.x);**<- pt1 is still null, throwing exception**
System.out.println("pt2.pt1.y = "+pt2.pt1.y);**<- same as pt1.**
}
}
The jna docs say that the constructor Structure(Pointer) allocates a structure onto a preallocated memory. It wont automatically assign values for you.I don't think thats what you want.
Change the constructors to
public Point2(){
super();
}
public Point2(Point1 p){
super();
pt1.x = p.x;
pt1.y = p.y;
this.x = something;
this.y = something;
}
Within the context of a callback, JNA will automatically call Structure.read on entry and Structure.write on exit for any parameters of type Structure.
If you declare your callback method signature to use a Structure type of the appropriate subclass ("Point2" in your example), the copying to/from native memory should be automatic.
A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.
Of course, it's trivial to implement it manually:
import java.util.LinkedList;
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
super.add(o);
while (size() > limit) { super.remove(); }
return true;
}
}
As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:
CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.
import java.util.Queue;
import org.apache.commons.collections4.queue.CircularFifoQueue;
Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.
Update: updated answer following release of commons collections version 4 that supports generics.
Guava now has an EvictingQueue, a non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full.
import java.util.Queue;
import com.google.common.collect.EvictingQueue;
Queue<Integer> fifo = EvictingQueue.create(2);
fifo.add(1);
fifo.add(2);
fifo.add(3);
System.out.println(fifo);
// Observe the result:
// [2, 3]
I like #FractalizeR solution. But I would in addition keep and return the value from super.add(o)!
public class LimitedQueue<E> extends LinkedList<E> {
private int limit;
public LimitedQueue(int limit) {
this.limit = limit;
}
#Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
}
Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.
I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):
public LimitedSizeQueue implements Queue
{
private int maxSize;
private LinkedList storageArea;
public LimitedSizeQueue(final int maxSize)
{
this.maxSize = maxSize;
storageArea = new LinkedList();
}
public boolean offer(ElementType element)
{
if (storageArea.size() < maxSize)
{
storageArea.addFirst(element);
}
else
{
... remove last element;
storageArea.addFirst(element);
}
}
... the rest of this class
A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:
public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
private int maxSize;
private CircularFifoBuffer storageArea;
public LimitedSizeQueue(final int maxSize)
{
if (maxSize > 0)
{
this.maxSize = maxSize;
storateArea = new CircularFifoBuffer(maxSize);
}
else
{
throw new IllegalArgumentException("blah blah blah");
}
}
... implement the Queue interface using the CircularFifoBuffer class
}
The only thing I know that has limited space is the BlockingQueue interface (which is e.g. implemented by the ArrayBlockingQueue class) - but they do not remove the first element if filled, but instead block the put operation until space is free (removed by other thread).
To my knowledge your trivial implementation is the easiest way to get such an behaviour.
You can use a MinMaxPriorityQueue from Google Guava, from the javadoc:
A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.
An LRUMap is another possibility, also from Apache Commons.
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/LRUMap.html
Ok I'll share this option. This is a pretty performant option - it uses an array internally - and reuses entries. It's thread safe - and you can retrieve the contents as a List.
static class FixedSizeCircularReference<T> {
T[] entries
FixedSizeCircularReference(int size) {
this.entries = new Object[size] as T[]
this.size = size
}
int cur = 0
int size
synchronized void add(T entry) {
entries[cur++] = entry
if (cur >= size) {
cur = 0
}
}
List<T> asList() {
int c = cur
int s = size
T[] e = entries.collect() as T[]
List<T> list = new ArrayList<>()
int oldest = (c == s - 1) ? 0 : c
for (int i = 0; i < e.length; i++) {
def entry = e[oldest + i < s ? oldest + i : oldest + i - s]
if (entry) list.add(entry)
}
return list
}
}
public class ArrayLimitedQueue<E> extends ArrayDeque<E> {
private int limit;
public ArrayLimitedQueue(int limit) {
super(limit + 1);
this.limit = limit;
}
#Override
public boolean add(E o) {
boolean added = super.add(o);
while (added && size() > limit) {
super.remove();
}
return added;
}
#Override
public void addLast(E e) {
super.addLast(e);
while (size() > limit) {
super.removeLast();
}
}
#Override
public boolean offerLast(E e) {
boolean added = super.offerLast(e);
while (added && size() > limit) {
super.pollLast();
}
return added;
}
}