Setter method for BigDecimal Array - java

I want to create a setter method for BigDecimal array but I can't get the right way of assigning a value for it. I want my array to contain at least a "zero" element or none for the mean time.
public void setAddends(BigDecimal addends[]){
addends[] = BigDecimal.ZERO;
}

BigDecimal addends[] = new BigDecimal [10];
...
public void setAddends(BigDecimal addends[]){
addends[0] = BigDecimal.ZERO;
}

If you want to put some constraints on the input parameter, you should require the caller of the method to provide a valid parameter instead of changing it inside the method. Consider throwing IllegalArgumentException if the parameter is invalid.
As far as I understood, you want the array to either contain at least one zero or contains nulls only:
public void setAddends(BigDecimal[] addends) {
if (numberOfNonNullsIn(addends) != 0 && numberOfZerosIn(addends) == 0) {
throw new IllegalArgumentException("addends should either contain at least one zero or contain nulls only");
}
// ...
}
private long numberOfZerosIn(BigDecimal[] addends) {
return Arrays.stream(addends).filter(a -> a != null && a.compareTo(BigDecimal.ZERO) == 0).count();
}
private long numberOfNonNullsIn(BigDecimal[] addends) {
return Arrays.stream(addends).filter(a -> a != null).count();
}

Related

java enum with value between x and y

This is a simple question:
Is it possible to have an enum with a variable value ?
To be clear i would like to create an enum corresponding to an error code returned by a function which is two bytes, so i would like to do something like
public enum ErrorCode {
ERR_NONE ((byte)0x9000), // No error
ERR_PARAM ((byte)0x8200), // Parameter error
ERR_DATA ((byte)0x83XX), // XX could be any value
}
how to return ERR_DATA for all values beginning by 0x83 ?
Is it possible ?
Thanks
Here's an implementation following Dawood ibn Kareem's suggestion in comments above.
Some points:
This implementation throws an exception if a code matches two enum values. You would need to decide whether you wanted that behaviour, or just return the first match. In that case the ordering of the enum values becomes significant.
You can add new constructors for common cases, e.g. I have one for a value which matches a single code. You could add one for a value which matches a range of codes.
You might also want to throw an exception if no ErrorCode matches the integer code. This implementation returns null in that case, so you'll get an NPE if the caller doesn't check for null, but you won't know what value triggered it.
import java.util.function.Predicate;
public enum ErrorCode {
ERR_NONE (0x9000), // No error
ERR_PARAM (0x8200), // Parameter error
ERR_DATA (n -> (n >= 0x8300 && n <= 0x83FF)), // 0x83XX
ERR_ANOTHER_83 (0x8377);
private final Predicate<Integer> forValue;
ErrorCode(Predicate<Integer> matches) {
this.forValue = matches;
}
ErrorCode(int singleValue) {
this(n -> n == singleValue);
}
public static ErrorCode forInt(int code) {
ErrorCode matchingCode = null;
for (ErrorCode c : ErrorCode.values()) {
if (c.forValue.test(code)) {
if (matchingCode != null) {
throw new RuntimeException("ErrorCodes " + matchingCode.name()
+ " and " + c.name() + " both match 0x"
+ Integer.toHexString(code));
} else {
matchingCode = c;
}
}
}
return matchingCode;
}
public static void main(String[] args) {
System.out.println(ErrorCode.forInt(0x8312));
System.out.println(ErrorCode.forInt(0x9000));
System.out.println(ErrorCode.forInt(0x8377));
}
}
Write a method which, given 0x83NN as input, returns ERR_DATA. Done.
ErrorCode errorCode(int n) {
if (n == 0x9000)
return ERR_NONE;
else if (n == 0x8200)
return ERR_PARAM;
else if (n >= 0x8300 && n <= 0x83ff)
return ERR_DATA;
else
throw new IllegalArgumentException();
}
You have to write code to look up the value in any case. There's no intrinsic 'associate this integer value with this enum constant, and provide a lookup for enum constant given an integer value'.
Note that, for this, there's no need to store the numeric value inside each member of the enum. And also note that your constructor calls like ERR_NONE(0x9000) are not valid unless you've defined a suitable constructor. And if you do define a suitable constructor, you'll need to decide on a single value for the argument of ERR_DATA.
I believe it cannot be the case. According to Oracle Doc,
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.

Can we combine two methods that differ largely based on type?

I have two similar, but of different types, blocks of code in Java:
private Integer readInteger() {
Integer value = null;
while (value == null) {
if (scanner.hasNextInt()) {
value = scanner.nextInt();
} else {
scanner.next();
}
}
return value;
}
private Double readDouble() {
Double value = null;
while (value == null) {
if (scanner.hasNextDouble()) {
value = scanner.nextDouble();
} else {
scanner.next();
}
}
return value;
}
Is it possible to make just one method which would work for both of them?
I'd say, use a generic method, combined with the functional interfaces introduced in Java 8.
The method read now becomes a higher order function.
private <T> T read(Predicate<Scanner> hasVal, Function<Scanner, T> nextVal) {
T value = null;
while (value == null) {
if (hasVal.test(scanner)) {
value = nextVal.apply(scanner);
} else {
scanner.next();
}
}
return value;
}
Calling code becomes:
read(Scanner::hasNextInt, Scanner::nextInt);
read(Scanner::hasNextDouble, Scanner::nextDouble);
read(Scanner::hasNextFloat, Scanner::nextFloat);
// ...
So the readInteger() method can be adapted as follows:
private Integer readInteger() {
return read(Scanner::hasNextInt, Scanner::nextInt);
}
You could have something with three methods:
One which says if there is a value of the right type
Another which gets the value of the right type.
Another which discards whatever token you have.
For example:
interface Frobnitz<T> {
boolean has();
T get();
void discard();
}
You can pass this into your method:
private <T> T read(Frobnitz<? extends T> frob) {
T value = null;
while (value == null) {
if (frob.has()) {
value = frob.get();
} else {
frob.discard();
}
}
return value;
}
And then just implement Frobnitz for your Double and Integer cases.
To be honest, I'm not sure this gets you very much, especially if you've only got two cases; I'd be inclined just to suck up the small amount of duplication.
A lot of people have answered that you can use generics, but you can also simply remove the readInteger method, and only use the readDouble, as integers can be converted to doubles without data loss.
This is about code duplication.
The general approach is to turn similar code (you have) into equal code that can be extracted to a common parameterized method.
In your case what make the two code snipped differ is the access to methods of Scanner. You have to encapsulate them somehow. I'd suggest to do this with Java8 Functional interfaces like this:
#FunctionalInterface
interface ScannerNext{
boolean hasNext(Scanner scanner);
}
#FunctionalInterface
interface ScannerValue{
Number getNext(Scanner scanner);
}
Then replace the actual invocation of methods in scanner with the functional interface:
private Integer readInteger() {
ScannerNext scannerNext = (sc)->sc.hasNextInt();
ScannerValue scannerValue = (sc)-> sc.nextInt();
Integer value = null;
while (value == null) {
if (scannerNext.hasNext(scanner)) {
value = scannerValue.getNext(scanner);
} else {
scanner.next();
}
}
return value;
}
There is one more problem that the type of the value variable differs. So we replace it with its common supertype:
private Integer readInteger() {
ScannerNext scannerNext = (sc)->sc.hasNextInt();
ScannerValue scannerValue = (sc)-> sc.nextInt();
Number value = null;
while (value == null) {
if (scannerNext.hasNext(scanner)) {
value = scannerValue.getNext(scanner);
} else {
scanner.next();
}
}
return (Integer)value;
}
Now you have to places with a big equal section. You can select one of those sections starting with Number value = null; ending with the } before return ... and invoke your IDEs automated refactoring extract method:
private Number readNumber(ScannerNext scannerNext, ScannerValue scannerValue) {
Number value = null;
while (value == null) {
if (scannerNext.hasNext(scanner)) {
value = scannerValue.getNext(scanner);
} else {
scanner.next();
}
}
return value;
}
private Integer readInteger() {
return (Integer) readNumber( (sc)->sc.hasNextInt(), (sc)-> sc.nextInt());
}
private Double readDouble() {
return (Double) readNumber( (sc)->sc.hasNextDouble(), (sc)-> sc.nextDouble());
}
Comments argue against the use of custom interfaces against predefined interfaces from the JVM.
But my point in this answer was how to turn similar code into equal code so that it can be extracted to a single method rather that giving a concrete solution for this random problem.
Not an ideal solution but it still achieves the necessary removal of duplicate code and has the added benefit of not requiring Java-8.
// This could be done better.
static final Scanner scanner = new Scanner(System.in);
enum Read{
Int {
#Override
boolean hasNext() {
return scanner.hasNextInt();
}
#Override
<T> T next() {
return (T)Integer.valueOf(scanner.nextInt());
}
},
Dbl{
#Override
boolean hasNext() {
return scanner.hasNextDouble();
}
#Override
<T> T next() {
return (T)Double.valueOf(scanner.nextDouble());
}
};
abstract boolean hasNext();
abstract <T> T next();
// All share this method.
public <T> T read() {
T v = null;
while (v == null) {
if ( hasNext() ) {
v = next();
} else {
scanner.next();
}
}
return v;
}
}
public void test(String[] args) {
Integer i = Read.Int.read();
Double d = Read.Dbl.read();
}
There are some minor issues with this such as the casting but it should be a reasonable option.
A totally different approach from my other answer (and the other answers): don't use generics, but instead just write the methods more concisely, so you don't really notice the duplication.
TL;DR: rewrite the methods as
while (!scanner.hasNextX()) scanner.next();
return scanner.nextX();
The overall goal - write it as a single method - is only possible if you accept some amount of additional cruft.
Java method signatures do not take into account the return type, so it's not possible to have a next() method return an Integer in one context, and Double in another (short of returning a common supertype).
As such, you have to have something at the call sites to distinguish these cases:
You might consider passing something like Integer.class or Double.class. This does have the advantage that you can use generics to know that the returned value matches that type. But callers could pass in something else: how would you handle Long.class, or String.class? Either you need to handle everything, or you fail at runtime (not a good option). Even with a tighter bound (e.g. Class<? extends Number>), you still need to handle more than Integer and Double.
(Not to mention that writing Integer.class and Double.class everywhere is really verbose)
You might consider doing something like #Ward's answer (which I do like, BTW: if you're going to do it with generics, do it like that), and pass in functional objects which are able to deal with the type of interest, as well as providing the type information to indicate the return type.
But, again, you've got to pass these functional objects in at each call site, which is really verbose.
In taking either of these approaches, you can add helper methods which pass the appropriate parameters to the "generic" read method. But this feels like a backwards step: instead of reducing the number of methods to 1, it's increased to 3.
Additionally, you now have to distinguish these helper methods somehow at the call sites, in order to be able to call the appropriate one:
You could have overloads with a parameter of value type, rather than class type, e.g.
Double read(Double d)
Integer read(Integer d)
and then call like Double d = read(0.0); Integer i = read(0);. But anybody reading this code is going to be left wondering what that magic number in the code is - is there any significance to the 0?
Or, easier, just call the two overloads something different:
Double readDouble()
Integer readInteger()
This is nice and easy: whilst it's slightly more verbose than read(0.0), it's readable; and it's way more concise that read(Double.class).
So, this has got us back to the method signatures in OP's code. But this hopefully justifies why you still want to keep those two methods. Now to address the contents of the methods:
Because Scanner.nextX() doesn't return null values, the method can be rewritten as:
while (!scanner.hasNextX()) scanner.next();
return scanner.nextX();
So, it's really easy to duplicate this for the two cases:
private Integer readInteger() {
while (!scanner.hasNextInt()) scanner.next();
return scanner.nextInt();
}
private Double readDouble() {
while (!scanner.hasNextDouble()) scanner.next();
return scanner.nextDouble();
}
If you want, you could pull out a method dropUntil(Predicate<Scanner>) method to avoid duplicating the loop, but I'm not convinced it really saves you that much.
A single (near-)duplicated line is way less burdensome in your code than all those generics and functional parameters. It's just plain old code, which happens to be more concise (and, likely, more efficient) than "new" ways to write it.
The other advantage of this approach is that you don't have to use boxed types - you can make the methods return int and double, and not have to pay the boxing tax unless you actually need it.
This may not be of advantage to OP, since the original methods do return the boxed type; I don't know if this is genuinely desired, or merely an artefact of the way the loop was written. However, it is useful in general not to create those objects unless you really need them.
Reflection is an alternative if you don't care about performance.
private <T> T read(String type) throws Exception {
Method readNext = Scanner.class.getMethod("next" + type);
Method hasNext = Scanner.class.getMethod("hasNext" + type);
T value = null;
while (value == null) {
if ((Boolean) hasNext.invoke(scanner)) {
value = (T) readNext.invoke(scanner);
} else {
scanner.next();
}
}
return value;
}
Then you call
Integer i = read("Int");

I'm creating a poker client, how can I make the exception handling more clean?

I'm checking if the values are valid. The if parts looks still messy for me, checking a lot of || operator, and there is multiple InvalidArgumentException, but I always check for that.
How can this be more clean ?
This is part of my script :
public Card(String cardCode) throws IllegalArgumentException {
this.cardCode = cardCode;
String cardColor = this.cardCode.substring(0, 1).toUpperCase();
String cardValue = cardCode.substring(1).toUpperCase();
Integer intCardValue = Integer.parseInt(cardValue);
if (!colors.contains(cardColor))
{
throw new IllegalArgumentException("card color isn't valid: " + cardColor);
}
if (alphabeticCardValue.get(cardValue) == null || intCardValue > 10 || intCardValue < 2 ) {
throw new IllegalArgumentException("card number isn't valid: " + intCardValue);
}
}
Thank you
What you actually trying to do is validating the input. Using IllegalArgumentException is not appropriate, imo, because the purpose is of this exception is defined in JavaDoc as follows:
Thrown to indicate that a method has been passed an illegal or
inappropriate argument.
What I would do is as follows:
Define an enum for possible colors:
public enum Color { BLACK, RED, ... }
Define an enum for possible card values:
public enum CardValues {
TWO(2),
THREE(3); // ...
private int value;
private CardValues(final int v) {
value = v;
}
public getValue() { return value;}
}
Change the constructor as follows:
public Card(Color color, CardValues cardValues) {
if (color == null || cardValues == null) {
throw new IllegalArgumentException("....");
}
// doSomething else
}
Note: IllegalArgumentException is an unchecked exception. So you don't need to specify it in the throws clause.
If you check the values in the constructor you can make sure all the cards will be valid. There's a downside - you'll have to decide which (valid) card will be created when the constructor is called with invalid parameters.
Maybe by putting the check into a separate method?
Something like isValidCard() and isValidColor(), so you can create a method isValidCard() using those methods.
Edit: Just go with ujulu's answer

Suspicious call to Collection.contains method in ArrayList

I am getting a warning that watchStore.contains(s) is a suspicious call to java.util.Collection#contains. How can I fix it? I want to use contains() to find a particular object with the matching serial number.
public Watch findWatchBySerialNumber(long srch) {
long s = srch;
Watch watch = null;
for(int i = 0; i < watchStore.size(); i++) {
watch = watchStore.get(i);
if(watchStore.contains(s)) {
System.out.print("item found");
return watch;
}
}
System.out.print("item not found");
return null; // watch is not found.
}
Presuming that Watch is the class, watchStore is a List<Watch>, and that a field serialNo exists on Watch...
public Optional<Watch> findWatchBySerialNumber(long serial) {
return watchStore.stream()
.filter(w -> w.getSerialNo() == serial)
.findFirst();
}
If you're not using Java 8, the code is close, but a bit more dangerous since you have the chance to return null. If you can use Guava's Optional, that'd be a better choice here.
public Watch findWatchBySerialNumber(long serial) {
for(Watch w : watchStore) {
if(w.getSerialNo() == serial) {
return w;
}
}
return null;
}
Your contains isn't going to work since your list doesn't contain Longs, it contains Watchs. This is also why the compiler sees it as dubious; contains accepts an Object but it will return false if what you're looking for doesn't have a comparable equals for what's in your list.
You have to iterate over the entirety of your collection to find it in this scenario, especially since you're looking for a specific property on those objects as opposed to a specific, easy-to-provide value.
please how can I fix that. I want to use the contain() to find a
particular object with the matching serial number.
In that case override Watch's equals() to use serialNumber field for comparison.
Then add constructor that accepts serialNumber.
public class Watch {
private final long serialNumber;
public Watch(long serialNumber) {
this.serialNumber = serialNumber;
}
#Override
public boolean equals(Object obj) {
return obj == this ||
(obj instanceof Watch && ((Watch)obj).serialNumber == serialNumber);
}
#Override
public int hashCode() {
return (int)serialNumber;
}
}
Replace if(watchStore.contains(s)){ with if(watchStore.contains(watchToFind)){ where Watch watchToFind = new Watch(s);
you can use contains method from org.apache.commons.lang.ArrayUtils package.
Checks if the value is in the given array.
The method returns false if a null array is passed in.
Parameters:
array the array to search through
valueToFind the value to find
Returns:
true if the array contains the object
long [] imageHashes= {12l,13l,14l,15l};
System.out.println(ArrayUtils.contains(imageHashes, 13l));

error: incomparable types: double and <null>

My code gives me this error:
error: incomparable types: double and .
I have no clue why.
This is what I want to do:
I have a formule (who gives me a double) but if this formule gives me no answer (divide by zero, ... ) I want to print : No answer!
beta & alfa are 2 doubles, you can choose.
double valueOne = valueOne(alfa,beta);
double valueTwo = valueTwo(alfa,beta);
public double valueOne(double alfa, double beta)
{
return (-(Math.sqrt((-beta)/alfa)))+alfa;
}
public double valueTwo(double alfa, double beta)
{
return (Math.sqrt((-beta)/alfa))+alfa;
}
if(valueOne == null && valueTwo == null)
{
System.out.println("No values");
}
Comparing a double to a null is of course illegal because the first one is a value type and value types are never null for which the null stands when comparing to reference types. This page might help you to distinguish the two: What’s the difference between a primitive type and a class type in Java?
If you don't want to throw exceptions on invalid values or results your method could make use of the Double.NaN constnt field:
public double valueOne(double alfa, double beta)
{
// At least one of the values is invalid.
if (Double.isNaN((alfa) || Double.isNaN((beta))
{
return Double.NaN;
}
// Check the alpha or otherwise a div/0 exception may be thrown.
if (alfa == 0.0)
{
return Double.NaN;
}
double divResult = (-beta)/alfa;
// Check the div result because Math.sqrt accepts only positive values:
// If the argument is NaN or less than zero, the result is NaN.
if (divResult < 0.0)
{
return Double.NaN;
}
return (-(Math.sqrt(divResult)))+alfa;
}
double resultValueOne = valueOne(alfa, beta);
if(Double.isNaN((resultOne))
{
System.out.println("No resultValueOne");
}
Sample at ideone
I think you've misunderstood a few things here.
you don't seem to be calling your two methods - I assume you mean something like valueOne(1, 2)
If your calculation gets an error (such as divide by zero) it doesn't return null, it throws an ArithmeticException
Therefore you shouldn't be comparing to null you should use a try catch block to handle errors
you can't compare an atomic type like double to null; only references to objects can be compared to null
you can use string manipulation since java does not allow a primitive type to have null values.
if the string is empty , no values will appear. i hope this helps.
public static void main(String []args){
if(valueOne(0,0).equals("") && valueTwo(0,0).equals(""))
System.out.println("No values");
else
System.out.println("val1:"+valueOne(0,0)+"val2:"+valueTwo(0,0));
}
public static String valueOne(double alfa, double beta){
return ""+(-(Math.sqrt((-beta)/alfa)))+alfa;;
}
public static String valueTwo(double alfa, double beta){
return ""+(-(Math.sqrt((-beta)/alfa)))+alfa;;
}
I guess you need something like this:
public double[] myMethod(double vAlfa, double vBeta, double wAlfa, double wBeta) {
double[] answers = new double[2];
try {
answers[0] = (-(Math.sqrt((-vBeta) / vAlfa))) + vAlfa;
answers[1] = (Math.sqrt((-wBeta)/wAlfa)) + wAlfa;
} catch (Exception e) {
System.out.println("No values");
}
return answers;
}
This method returns the result of processes as an array of doubles (because you have two values).
In the try block, we try to calculate the answers and put them in the array.
and in the catch block, we deal with every exceptions (NullPointerException or DivisionByZero or ...) by an call to System.println(); to print the given string for us.
Hope it helps.
First of all both valueOne and valueTwo are methods but you try to refer to them as variables (?!):
if(valueOne == null && valueTwo == null){
Second, anyway the return type of these methods and (if you define variables of the same type) is double that is a primitive and cannot be null. null is a special value that can be used with object references only.
Take some java tutorial that explains java types for the beginning.

Categories

Resources