So this is basically what I want my code to say, as to avoid compile error's in the event that the user selects "Tea" instead of using the corresponding integer.
if(appSelection < 1 || appSelection > appetizersArray.length || appSelection != int)
the first two conditions are obviously to catch data that would be out of bounds, but I'm looking for a way to specify that the input needs to be an int.
If the only option is try catch just say so but I'm hoping there's a more elegant solution.
You could use a regular expression. The lower case \\d matches digits and adding a plus means consecutive. So,
String regex = "\\d+";
String[] arr = { "Tea", "123" };
for (String str : arr) {
if (str.matches(regex)) {
System.out.printf("%s is all digits%n", str);
} else {
System.out.printf("%s is NOT all digits%n", str);
}
}
Output is
Tea is NOT all digits
123 is all digits
Is this command-line input? If so, you can use the Scanner class's nextInt method (https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#nextInt%28%29). If it's coming from a web form, either your library should convert the value to an integer, in which case you already know it's an integer, or it's a string and you can call Integer.parseInt(String). Documentation here: https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#parseInt%28java.lang.String%29
Assuming that the data comes in a String, well, a try/catch is the thing to use, or some function to check if the provided data is a valid integer, like this:
boolean isValidInt(String s) {
try {
Integer.parseInt(s);
} catch (Exception e) {
return false;
}
return true;
}
Then you can say:
if(!isValidInt(appSelection)) someError();
Hope it helps!
Assuming this is a Java-related question, int is a primitive. The operation you are referring to has a operator: instanceof. Unfortunately, it does not work for primitive data types. In order to use this you have to use a wrapper class (i.e Integer). So:
int x = 1;
if (x instanceof Integer) { // compilation error }
Unfortunately, autoboxing does not work for this. What you can do is the following:
String value = ???; // ??? represents some unknown string value.
Later on, you can try to convert that String value to an Integer value:
try
{
Integer x = new Integer(str);
}
catch (NumberFormatException e)
{
// The exception will be thrown if the string does not represent a numeric value. For example: a34bc
}
If the instantiation of variable x succeeds, it will hold a numeric value. Because of Java unboxing mechanism, you will be able to pass 'x' to some method that takes a primitive int. For example:
try
{
Integer x = new Integer(str);
int result = addThisValue(x);
}
catch (NumberFormatException e) {// Do something }
...
public int addThisValue(int value) {...}
You will be able to pass variable x to that method safely.
Related
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.
I want to create validator for input filed in order to check values and send error message if the inserted value is not int.
bean:
public class PricingCalculatorValidator implements Validator
{
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException
{
// Cast the value of the entered input to String.
String input = (String) value;
// Check if they both are filled in.
if (input == null || input.isEmpty())
{
return; // Let required="true" do its job.
}
// Compare the input with the confirm input.
if (containsDigit(input))
{
throw new ValidatorException(new FacesMessage("Value is not number."));
}
}
public final boolean containsDigit(String s)
{
boolean containsDigit = false;
if (s != null && !s.isEmpty())
{
for (char c : s.toCharArray())
{
if (containsDigit = Character.isDigit(c))
{
break;
}
}
}
return containsDigit;
}
}
What is the proper way to cast the inserted value? Now I get exception
serverError: class java.lang.ClassCastException java.lang.Integer cannot be cast to java.lang.String
As per the exception, JSF is actually passing an Integer instance as value to the validate() method. Technically, you should be casting it to Integer as below to keep the Java runtime happy.
// Cast the value of the entered input to Integer.
Integer input = (Integer) value;
Apparently you already bound the input field to an Integer property in the model like so:
<h:inputText value="#{bean.pricing}" />
private Integer pricing;
In other words, the whole custom validator is unnecessary. There's no point of validating if the value is an integer if it's already an Integer in first place. It can impossibly contain a non-digit as value.
Just get rid of that custom validator altogether.
JSF has several builtin converters for standard types like Integer which run automatically depending on the model value type. And, converters run right before validators. That's why the value already arrives as Integer in your custom validator. The only thing which seems relevant in your custom validator is the error message which is different from the standard conversion error message. In case you merely wanted to customize the conversion error message on the specific input field, just set it as converterMessage attribute on the input field.
<h:inputText value="#{bean.pricing}" converterMessage="Value is not numeric." />
Unrelated to the concrete problem, "validating" if the value represents a valid Integer or not (this process is in JSF actually called conversion and is supposed to take place in a custom converter) can be performed in a much simpler way:
String string = getItSomehowWithoutClassCastException();
try {
Integer integer = Integer.valueOf(string);
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage("Value is not an integer."));
}
No need to inspect every single digit if you ultimately want to get an Integer. As said, the JSF builtin converter already takes care of this.
You don't have to verify each character.
Just perform:
boolean isDigit = true;
try {
new Integer(input).intValue();
} catch (NumberFormatException nfe) {
isDigit = false;
}
If any of the chars in input is not a number, the catch block will be executed, otherwise, that block will be skipped.
At the end, isDigit tells you whether input is an integer or not.
Note, if your input has too many digits to be an integer, it will also tell you that input is not an integer, even if every single character is a digit.
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.
This question already has answers here:
Determine if object is integer
(3 answers)
Closed 6 years ago.
I'm using some API by restTemplate. The API returns a key whose type is integer.
But I'm not sure of that value, so I want to check whether the key is really an integer or not.
I think it might be a string.
What is the best way of checking if the value is really integer?
added:
I mean that some API might return value like below.
{id : 10} or {id : "10"}
If what you receive is a String, you can try to parse it into an integer, if it fails, it's because it was not an integer after all. Something like this:
public static boolean isInteger(String str) {
try {
Integer.parseInt(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
Object x = someApi();
if (x instanceof Integer)
Note that if someApi() returns type Integer the only possibilities of something returned are:
an Integer
null
In which case you can:
if (x == null) {
// not an Integer
} else {
// yes an Integer
}
One possibility is to use Integer.valueOf(String)
Assuming your API return value can either be an Integer or String you can do something like this:
Integer getValue(Object valueFromAPI){
return (valueFromAPI != null ? Integer.valueOf(valueFromAPI.toString()) : null);
}
I am parsing XML files and I have several methods similar to:
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
try {
return Integer.parseInt(integer.toString(), 10);
} catch (Exception ex) {
return 0;
}
}
So basically, you pass an object in with the assumption of converting it to an Integer (I also have versions for Float, etc).
This seems to work well but being a Java newbie, I was wondering how you would improve it. I am especially interesting in the boxing/unboxing aspect (at least, from a C# developer's perspective).
Thanks
EDIT
Sorry, I wasn't clear to what goes into the method. Yes, it's for an XML file now so it's always a string. But the string could be empty or maybe even null. I guess I wanted to always return a 0 if there was an error of any kind.
You shouldn't generally catch Exception. Catching NumberFormatException would be more appropriate here.
Any reason for converting to Integer instead of int? Why not let the caller perform the boxing conversion if they need it?
You don't say whether integer is an instance of Integer or not. If it is you can just cast it:
Integer i = (Integer) integer;
having checked for null and instanceof first.
If it is not an instance of Integer then what you're doing seems reasonable, although you only need to catch a NumberFormatException.
You should use instanceof operator, then make safe casting (so if Object integer is instanceof Integer, cast it).
Then you don't have to catch Exception (which in this case is unchecked NumberFormatException)
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
if (integer instanceof Integer) {
return (Integer)integer;
}
return 0;
}
EDIT
If data is coming from XML, then it will of course never be Integer :) Then parsing from String is required still, so see other answers.
As Jon hinted, returning int (the primitive data type) instead of Integer (the wrapper class) would probably be better (assuming you never want to return null).
Also, adding this code could be a shortcut, when the input is often an Integer object or other Number subclass (I'm calling the input input because it's too confusing otherwise):
if (input instanceof Number) {
return ((Number) integer).intValue();
}
Returning Integer makes sense if you want to signal, that a value is empty. You're testing that already but you shouldn't return 0, unless you have a very clear and somewhat special requirement to do so. No value is not equal to 0.
Also, you can add more special cases besides null, like check for empty string:
public static Integer getInteger(Object integer) {
if (integer == null) {
return 0;
}
try {
String s = integer.toString();
if (s.isEmpty())
return 0;
return Integer.parseInt(s, 10);
} catch (Exception ex) {
return 0;
}
}
On the other side, you can cut all special cases, and go with only:
public static Integer getInteger(Object integer) {
try {
return Integer.parseInt(integer.toString(), 10);
} catch (Exception ex) {
return 0;
}
}
In the end, performance gains (or losses) depends on what portion of your input data is null, empty, unparsable integers, or "normal" integer strings.