Is there a way to "bulk assign" boolean variables in Java? - java

The one main thing I want to avoid while Java programming is excessive boolean variable declarations like this:
public static boolean mytruebool = true, myfalsebool = false, myothertruebool = true, myotherfalsebool = false;
Is there an efficient way (perhaps w/ array usage) of declaring and assigning variables? Any help is greatly appreciated!

If these are fields (static or otherwise), boolean will have an initial value of false. At that point, you set them according to the needs of your program. So at least, you don't have to worry about half of your boolean fields.
If you're discovering that you have too many boolean fields, then you may want to reconsider the design of your program instead of pre-initializing your values.

If you are comfortable with bit manipulation, you can store all your booleans as a single integer. In this case, you can store your initial state (and other various states) of all the "variables" as a single integer value.
boolean firstVar = false;
boolean secondVar = true;
boolean thirdVar = true;
...can become...
public class Test {
public static final int INITIAL_STATE = 6;
private static int myVar = INITIAL_STATE;
public static boolean getVar(int index) {
return (myVar & (1 << index)) != 0;
}
public static void setVar(int index, boolean value) {
if (value) {
myVar |= (1 << index);
} else {
myVar &= ~(1 << index);
}
}
public static void printState() {
System.out.println("Decimal: " + myVar + " Binary: " + Integer.toBinaryString(myVar));
}
public static void main(String[] args) {
System.out.println(getVar(0)); // false
System.out.println(getVar(1)); // true
System.out.println(getVar(2)); // true
printState();
setVar(0, true);
System.out.println(getVar(0)); // now, true
printState();
}
}
Learn more about bit manipulation here: Java "Bit Shifting" Tutorial?

This should work ; tested already;
boolean mytruebool,myothertruebool;
mytruebool = myothertruebool= true;
boolean myfalsebool,myotherfalsebool;
myfalsebool=myotherfalsebool=false;

Related

Calling a 'dynamic' Object of a HashMap

I just came to the problem where I want to call a function of an Object inside a HashMap. I already searched it up and found one thread but sadly I don't understand it.
So here's my code
public class Seat {
//some attributes
public int getNumber() {
return number;
}
public boolean isReserved() {
return status;
}
}
public class Hall {
private HashMap mySeats;
public HashMap getMeinePlaetze() {
return meinePlaetze;
}
public void createSeats() {
for (int i = 1; i <= this.getnumberOfSeats(); i++) {
this.getMySeats().put(i, new Seat(i, 1));
}
}
}
public class Main {
Hall h1 = new Hall(...);
h1.createSeats();
h1.getMySeats().get(2).isReserved(); //How do I have to write this to work out?
}
I hope my intend is reasonable. Feel free to correct me if my code sucks. I already apologize for it.
Thank you very much.
Since version 5, Java has a feature called Generics. You'll find a lot about generics on the web, from articles, blog posts, etc to very good answers here on StackOverflow.
Generics allows Java to be a strongly typed language. This means that variables in Java can not only be declared to be of some type (i.e. HashMap), but also to be of some type along with one or more generic type parameters (i.e. HashMap<K, V>, where K represents the type parameter of the keys of the map and V represents the type parameter of the values of the map).
In your example, you are using a raw HashMap (raw types are types that allow for generic type parameters to be specified, however the developer has not specified them). Raw types are considered bad practice and are highly error-prone, as you are experiencing right now.
HashMap allows two generic type parameters (one for the keys and another one for the values). In your case, you are using Integer for the keys and Seat for the values. Put into simple words, you are mapping integers to seats, or you can also say that your map is a map of integers to seats.
So, inside you Hall class, you should define your map with its generic type parameters:
private Map<Integer, Seat> mySeats = new HashMap<>();
Then, this code:
h1.getMySeats().get(2)
will return an instance of type Seat, because your map already knows that all its values are of type Seat.
So your code:
h1.getMySeats().get(2).isReserved();
will compile fine and will work without any errors.
Please note that, apart from declaring the generic types of your map, I've also changed two additional things.
First, I've created an actual instance of HashMap by using its constructor:
mySeats = new HashMap<>()
If you don't create an instance of your type with new, there won't be any HashMap instance where to put your seats later, and you'll get a NullpointerException (try it!).
Secondly, I've changed the type of the variable from HashMap to Map. HashMap is a class, while Map is just an interface. The thing is that the HashMap class implements the Map interface, so, unless your code explicitly needs to access a method of HashMap that is not declared in the Map interface (which is almost never the case), you will be fine with the mySeats variable being of type Map<Integer, Seat> instead of HashMap<Integer, Seat>. This is called programming to the interface and is a best practice that you should embrace from the very beginning. It will save you a lot of headaches in the future.
Following my tip in the comments, I wouldn't use a Map to link a meaningful row or number to a map-key or an array-index.
So, actually I would do it this way (because you asked, what I mean with my tip):
Seat:
public class Seat {
private final int row;
private final int number;
private boolean reserved = false;
public Seat(int row, int number) {
this.row = row;
this.number = number;
}
public boolean reserve() {
if (!reserved) {
reserved = true;
return reserved;
}
return !reserved;
}
public int getRow() {
return row;
}
public int getNumber() {
return number;
}
public boolean isReserved() {
return reserved;
}
public boolean is(int row, int number) {
return this.row == row && this.number == number;
}
#Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + this.row;
hash = 23 * hash + this.number;
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Seat other = (Seat) obj;
if (this.row != other.row) {
return false;
}
return number == other.number;
}
}
Hall:
public class Hall {
public final Set<Seat> seats = new HashSet<>();
public Set<Seat> getSeats() {
return Collections.unmodifiableSet(seats);
}
public void createSeats(int lastRow, int seatsPerRow) { // This is an example; in case you have different count of seats per row, you better make an boolean addSeat(int row, int number) function; boolean to check if it has been added or if the seat already exists
for (int row = 1; row <= lastRow; row++) {
for (int number = 1; number <= seatsPerRow; number++) {
seats.add(new Seat(row, number));
}
}
}
public Seat get(int row, int number) {
for (Seat seat : seats) { // or you use seats.iterator; I personally hate Iterators; it is my subjective point of view.
if (seat.is(row, number)) {
return seat;
}
}
return null;
}
public boolean reserve(int row, int number) {
Seat seat = get(row, number);
if (seat != null) {
return seat.reserve();
}
return false;
}
}
And my Test-drive:
public class TestDrive {
public static void main(String[] args) {
Hall hall = new Hall();
int lastRow = 15;
int seatsPerRow = 10;
hall.createSeats(lastRow, seatsPerRow);
boolean reserved = hall.reserve(5, 9);
System.out.println("Seat(Row=5, Number=9) is reserved: " + (reserved == hall.get(5, 9).isReserved()));
boolean reservedAgain = hall.reserve(5, 9);
System.out.println("Seat(Row=5, Number=9) cannot be reserved again: " + (reservedAgain != hall.get(5, 9).isReserved()));
}
}
h1.getMySeats().get(2).isReserved();
Please use an IDE like IntelliJ IDEA. It will tell you about mistakes like forgetting parentheses while typing.

Java equality integer

I find it kind of confusing, I'm trying to solve this problem I found on the Internet as my programming exercise:
Implement a class with methods which takes one INTEGER parameter "initialValue" and returns following:
a. if initialValue is equal to 1 - return 2 (INTEGER)
b. if initialValue is equal to 2 - return 1 (INTEGER)
This is what I've done so far:
public static void main(String[] args) {
System.out.print(myMethod(1));
}
private static int myMethod(int initialValue) {
int n = 1;
if(initialValue == n) {
return 2;
} else {
return n;
}
}
But I guess this is a basic solution. Do you know any method variations other than this? Thanks.
little fancy solution would be doing XOR with 3
return initialValue ^ 3;
You might use the conditional operator ?: and something like
private static int myMethod(int initialValue) {
return initialValue == 1 ? 2 : 1;
}
The ternary operator is described in the Java Tutorials like
Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement (discussed in the Control Flow Statements section of this lesson). This operator is also known as the ternary operator because it uses three operands. In the following example, this operator should be read as: "If someCondition is true, assign the value of value1 to result. Otherwise, assign the value of value2 to result."
I really hope that you plan on using this for learning only not to hand in as your own work. Your way works very well. However, you could also use the modulo operator (assuming of course that the only two inputs would be 1 and 2).
private static int myMethod(int initialValue) {
return initialValue % 2 + 1;
}
Best of luck with your CS aspirations!
public static void main(String[] args) {
int input;
// code for input value
System.out.print(myMethod(input));
}
private static int myMethod(int initialValue) {
int n = 1;
if(initialValue == n) {
return 2;
} else if(initialValue==2) {
return 1;
}
else {
return initialValue;
}
}
This might give better output if you insert values dynamically
It can also be done this way,
private static int myMethod(int initialValue) {
switch (initialValue){
case 1:
return 2;
case 2:
return 1;
default:
return 0;
}
}

Given two numbers, return true if any one of them divides the other, else return false

Given two numbers, return true if any one of them divides the other, else return false
public class DividesAB {
static int testcase11 = 208;
static int testcase12 = 7;
boolean aDivisblebyb, bDivisblebya, answer;
public static void main(String args[]){
DividesAB testInstance = new DividesAB();
boolean result = testInstance.divides(testcase11,testcase12);
System.out.println(result);
}
//write your code here
public boolean divides(int a, int b){
boolean aDivisiblebyb = a%b == 0;
boolean bdivisiblebya = b%a == 0;
boolean answer = aDivisiblebyb||bDivisiblebya;
return answer;
}
}
I have been getting errors like cannot find symbol
You have a mess of code thrown together and half it it isn't needed. To find if a symbol is not defined, look at the line of code in your IDE where it is complaining and see why that variable is not in scope.
If you only write the code you need, there is less chance of making a mistake, and it is easier to see where the mistake is.
This is how I would write it
public class DividesAB {
public static void main(String[] args) {
int a = 208, b = 7;
System.out.printf("a: %,d divides b: %,d is %s%n", divides(a, b));
}
//write your code here
public static boolean divides(int a, int b){
return a % b == 0 || b % a == 0;
}
}
The variable names are not correct.
aDivisblebyb and you are using aDivisiblebyb
So change the variable names and it should work.
First, look at the "cannot find symbol" error from your compiler. It should tell you exactly what line the error is occurring on, and most likely the exact error that is occurring. In your case, it will point to:
boolean answer = aDivisiblebyb||bDivisiblebya;
In your declaration, the spelling is different (aDivisblebyb vs aDivisiblebyb), so the compiler does not understand what the symbol aDivisiblebyb is. Same goes for aDivisiblebya. Hence the error.
Side note: you have declared boolean aDivisblebyb and boolean bDivisblebya in two places. In the code you posted, it is unnecessary to access these boolean values outside of the divides method (same with the answer boolean). So, to clean it up a little:
public class DividesAB {
static int testcase11 = 208;
static int testcase12 = 7;
public static void main(String args[]){
DividesAB testInstance = new DividesAB();
boolean result = testInstance.divides(testcase11,testcase12);
System.out.println(result);
}
//write your code here
public boolean divides(int a, int b){
boolean aDivisiblebyb = a%b == 0;
boolean bDivisiblebya = b%a == 0;
boolean answer = aDivisiblebyb||bDivisiblebya;
return answer;
}
}

Boolean array comparisons Java

I have made a class called Iset that takes integers and modifies it's boolean array's index equivalent to the integer to true.
e.g. If I pass an integer 1 then the boolean array setI[1] is turned to true.
I have a method called include that returns true if the provided integer is in there and false if it isn't. However no matter what I do I always get true. I have made sure that everything in the array is set to false and I add in a number further up the code. Obviously I'm missing something really obvious here:
public class Iset {
public int size;
boolean[] setI;
Iset(int a) {
this.size = a;
this.setI = new boolean[size];
}
public boolean include(int i) {
for (int n = 0; n <= size; n++) {
if (setI[n]== setI[i]){
return true;
}
}
return false;
}
}
Please try this code, I think you should add a funktion: set(), and change a little of the include(int i)
public class Iset {
public int size;
boolean[] setI;
Iset(int a) {
this.size = a;
this.setI = new boolean[size];
}
public boolean include(int i) {
return setI[i];
}
//set your values in the boolean array "setI" to "true"
public void set(int... values) {
for (int i : values) {
setI[i] = true;
}
}
public static void main(String[] args) {
Iset mm = new Iset(100);
mm.set(25, 40, 22);
System.out.println(mm.include(25));
}
}
The other answers have given solutions, but I think we can also get an explanation going as to why your original code was slightly wrong as you say. Here is what your include() method is doing in pseudocode:
for each boolean called 'setI[n]' in the array:
if 'setI[n]' is the same as the boolean at 'setI[i]':
return true
So, it's not actually checking if either of those boolean are true or false, it's just checking if they are the same. This method will always return true unless the boolean at index i is the only one in the array with its value (I'd suggest trying that to see if I am right). For example, if i = 1 your method will return true for:
[false, true, false, false, ...]
[true, false, true, true, ...]
... and no other values.
Hopefully this makes things a little clearer.
You don't have to walk over the complete array, just ask the method if your number is included.
public boolean isIncluded(int i) {
if (setI[i] == true){
return true;
}
return false;
}
or even simpler:
public boolean isIncluded(int i) {
return setI[i];
}
P.S. I changed your method name to something more meaningful
Try this:
public boolean include(int i) {
if (i >= size){
// To avoid ArrayIndexOutOfBoundsException
return false;
}
return setI[i];
}
I'm not completely sure what you are after for, but, in you for-loop you are making a selfcomparison when n == i and thus return true always.

Good way to encapsulate Integer.parseInt()

I have a project in which we often use Integer.parseInt() to convert a String to an int. When something goes wrong (for example, the String is not a number but the letter a, or whatever) this method will throw an exception. However, if I have to handle exceptions in my code everywhere, this starts to look very ugly very quickly. I would like to put this in a method, however, I have no clue how to return a clean value in order to show that the conversion went wrong.
In C++ I could have created a method that accepted a pointer to an int and let the method itself return true or false. However, as far as I know, this is not possible in Java. I could also create an object that contains a true/false variable and the converted value, but this does not seem ideal either. The same thing goes for a global value, and this might give me some trouble with multithreading.
So is there a clean way to do this?
You could return an Integer instead of an int, returning null on parse failure.
It's a shame Java doesn't provide a way of doing this without there being an exception thrown internally though - you can hide the exception (by catching it and returning null), but it could still be a performance issue if you're parsing hundreds of thousands of bits of user-provided data.
EDIT: Code for such a method:
public static Integer tryParse(String text) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
Note that I'm not sure off the top of my head what this will do if text is null. You should consider that - if it represents a bug (i.e. your code may well pass an invalid value, but should never pass null) then throwing an exception is appropriate; if it doesn't represent a bug then you should probably just return null as you would for any other invalid value.
Originally this answer used the new Integer(String) constructor; it now uses Integer.parseInt and a boxing operation; in this way small values will end up being boxed to cached Integer objects, making it more efficient in those situations.
What behaviour do you expect when it's not a number?
If, for example, you often have a default value to use when the input is not a number, then a method such as this could be useful:
public static int parseWithDefault(String number, int defaultVal) {
try {
return Integer.parseInt(number);
} catch (NumberFormatException e) {
return defaultVal;
}
}
Similar methods can be written for different default behaviour when the input can't be parsed.
In some cases you should handle parsing errors as fail-fast situations, but in others cases, such as application configuration, I prefer to handle missing input with default values using Apache Commons Lang 3 NumberUtils.
int port = NumberUtils.toInt(properties.getProperty("port"), 8080);
To avoid handling exceptions use a regular expression to make sure you have all digits first:
//Checking for Regular expression that matches digits
if(value.matches("\\d+")) {
Integer.parseInt(value);
}
There is Ints.tryParse() in Guava. It doesn't throw exception on non-numeric string, however it does throw exception on null string.
After reading the answers to the question I think encapsulating or wrapping the parseInt method is not necessary, maybe even not a good idea.
You could return 'null' as Jon suggested, but that's more or less replacing a try/catch construct by a null-check. There's just a slight difference on the behaviour if you 'forget' error handling: if you don't catch the exception, there's no assignment and the left hand side variable keeps it old value. If you don't test for null, you'll probably get hit by the JVM (NPE).
yawn's suggestion looks more elegant to me, because I do not like returning null to signal some errors or exceptional states. Now you have to check referential equality with a predefined object, that indicates a problem. But, as others argue, if again you 'forget' to check and a String is unparsable, the program continous with the wrapped int inside your 'ERROR' or 'NULL' object.
Nikolay's solution is even more object orientated and will work with parseXXX methods from other wrapper classes aswell. But in the end, he just replaced the NumberFormatException by an OperationNotSupported exception - again you need a try/catch to handle unparsable inputs.
So, its my conclusion to not encapsulate the plain parseInt method. I'd only encapsulate if I could add some (application depended) error handling as well.
May be you can use something like this:
public class Test {
public interface Option<T> {
T get();
T getOrElse(T def);
boolean hasValue();
}
final static class Some<T> implements Option<T> {
private final T value;
public Some(T value) {
this.value = value;
}
#Override
public T get() {
return value;
}
#Override
public T getOrElse(T def) {
return value;
}
#Override
public boolean hasValue() {
return true;
}
}
final static class None<T> implements Option<T> {
#Override
public T get() {
throw new UnsupportedOperationException();
}
#Override
public T getOrElse(T def) {
return def;
}
#Override
public boolean hasValue() {
return false;
}
}
public static Option<Integer> parseInt(String s) {
Option<Integer> result = new None<Integer>();
try {
Integer value = Integer.parseInt(s);
result = new Some<Integer>(value);
} catch (NumberFormatException e) {
}
return result;
}
}
You could also replicate the C++ behaviour that you want very simply
public static boolean parseInt(String str, int[] byRef) {
if(byRef==null) return false;
try {
byRef[0] = Integer.parseInt(prop);
return true;
} catch (NumberFormatException ex) {
return false;
}
}
You would use the method like so:
int[] byRef = new int[1];
boolean result = parseInt("123",byRef);
After that the variable result it's true if everything went allright and byRef[0] contains the parsed value.
Personally, I would stick to catching the exception.
I know that this is quite an old question, but I was looking for a modern solution to solve that issue.
I came up with the following solution:
public static OptionalInt tryParseInt(String string) {
try {
return OptionalInt.of(Integer.parseInt(string));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
Usage:
#Test
public void testTryParseIntPositive() {
// given
int expected = 5;
String value = "" + expected;
// when
OptionalInt optionalInt = tryParseInt(value);
// then
Assert.assertTrue(optionalInt.isPresent());
Assert.assertEquals(expected, optionalInt.getAsInt());
}
#Test
public void testTryParseIntNegative() {
// given
int expected = 5;
String value = "x" + expected;
// when
OptionalInt optionalInt = tryParseInt(value);
// then
Assert.assertTrue(optionalInt.isEmpty());
}
My Java is a little rusty, but let me see if I can point you in the right direction:
public class Converter {
public static Integer parseInt(String str) {
Integer n = null;
try {
n = new Integer(Integer.tryParse(str));
} catch (NumberFormatException ex) {
// leave n null, the string is invalid
}
return n;
}
}
If your return value is null, you have a bad value. Otherwise, you have a valid Integer.
The answer given by Jon Skeet is fine, but I don't like giving back a null Integer object. I find this confusing to use. Since Java 8 there is a better option (in my opinion), using the OptionalInt:
public static OptionalInt tryParse(String value) {
try {
return OptionalInt.of(Integer.parseInt(value));
} catch (NumberFormatException e) {
return OptionalInt.empty();
}
}
This makes it explicit that you have to handle the case where no value is available. I would prefer if this kind of function would be added to the java library in the future, but I don't know if that will ever happen.
What about forking the parseInt method?
It's easy, just copy-paste the contents to a new utility that returns Integer or Optional<Integer> and replace throws with returns. It seems there are no exceptions in the underlying code, but better check.
By skipping the whole exception handling stuff, you can save some time on invalid inputs. And the method is there since JDK 1.0, so it is not likely you will have to do much to keep it up-to-date.
If you're using Java 8 or up, you can use a library I just released: https://github.com/robtimus/try-parse. It has support for int, long and boolean that doesn't rely on catching exceptions. Unlike Guava's Ints.tryParse it returns OptionalInt / OptionalLong / Optional, much like in https://stackoverflow.com/a/38451745/1180351 but more efficient.
Maybe someone is looking for a more generic approach, since Java 8 there is the Package java.util.function that allows to define Supplier Functions. You could have a function that takes a supplier and a default value as follows:
public static <T> T tryGetOrDefault(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
} catch (Exception e) {
return defaultValue;
}
}
With this function, you can execute any parsing method or even other methods that could throw an Exception while ensuring that no Exception can ever be thrown:
Integer i = tryGetOrDefault(() -> Integer.parseInt(stringValue), 0);
Long l = tryGetOrDefault(() -> Long.parseLong(stringValue), 0l);
Double d = tryGetOrDefault(() -> Double.parseDouble(stringValue), 0d);
I would suggest you consider a method like
IntegerUtilities.isValidInteger(String s)
which you then implement as you see fit. If you want the result carried back - perhaps because you use Integer.parseInt() anyway - you can use the array trick.
IntegerUtilities.isValidInteger(String s, int[] result)
where you set result[0] to the integer value found in the process.
This is somewhat similar to Nikolay's solution:
private static class Box<T> {
T me;
public Box() {}
public T get() { return me; }
public void set(T fromParse) { me = fromParse; }
}
private interface Parser<T> {
public void setExclusion(String regex);
public boolean isExcluded(String s);
public T parse(String s);
}
public static <T> boolean parser(Box<T> ref, Parser<T> p, String toParse) {
if (!p.isExcluded(toParse)) {
ref.set(p.parse(toParse));
return true;
} else return false;
}
public static void main(String args[]) {
Box<Integer> a = new Box<Integer>();
Parser<Integer> intParser = new Parser<Integer>() {
String myExclusion;
public void setExclusion(String regex) {
myExclusion = regex;
}
public boolean isExcluded(String s) {
return s.matches(myExclusion);
}
public Integer parse(String s) {
return new Integer(s);
}
};
intParser.setExclusion("\\D+");
if (parser(a,intParser,"123")) System.out.println(a.get());
if (!parser(a,intParser,"abc")) System.out.println("didn't parse "+a.get());
}
The main method demos the code. Another way to implement the Parser interface would obviously be to just set "\D+" from construction, and have the methods do nothing.
They way I handle this problem is recursively. For example when reading data from the console:
Java.util.Scanner keyboard = new Java.util.Scanner(System.in);
public int GetMyInt(){
int ret;
System.out.print("Give me an Int: ");
try{
ret = Integer.parseInt(keyboard.NextLine());
}
catch(Exception e){
System.out.println("\nThere was an error try again.\n");
ret = GetMyInt();
}
return ret;
}
To avoid an exception, you can use Java's Format.parseObject method. The code below is basically a simplified version of Apache Common's IntegerValidator class.
public static boolean tryParse(String s, int[] result)
{
NumberFormat format = NumberFormat.getIntegerInstance();
ParsePosition position = new ParsePosition(0);
Object parsedValue = format.parseObject(s, position);
if (position.getErrorIndex() > -1)
{
return false;
}
if (position.getIndex() < s.length())
{
return false;
}
result[0] = ((Long) parsedValue).intValue();
return true;
}
You can either use AtomicInteger or the int[] array trick depending upon your preference.
Here is my test that uses it -
int[] i = new int[1];
Assert.assertTrue(IntUtils.tryParse("123", i));
Assert.assertEquals(123, i[0]);
I was also having the same problem. This is a method I wrote to ask the user for an input and not accept the input unless its an integer. Please note that I am a beginner so if the code is not working as expected, blame my inexperience !
private int numberValue(String value, boolean val) throws IOException {
//prints the value passed by the code implementer
System.out.println(value);
//returns 0 is val is passed as false
Object num = 0;
while (val) {
num = br.readLine();
try {
Integer numVal = Integer.parseInt((String) num);
if (numVal instanceof Integer) {
val = false;
num = numVal;
}
} catch (Exception e) {
System.out.println("Error. Please input a valid number :-");
}
}
return ((Integer) num).intValue();
}
This is an answer to question 8391979, "Does java have a int.tryparse that doesn't throw an exception for bad data? [duplicate]" which is closed and linked to this question.
Edit 2016 08 17: Added ltrimZeroes methods and called them in tryParse(). Without leading zeroes in numberString may give false results (see comments in code). There is now also public static String ltrimZeroes(String numberString) method which works for positive and negative "numbers"(END Edit)
Below you find a rudimentary Wrapper (boxing) class for int with an highly speed optimized tryParse() method (similar as in C#) which parses the string itself and is a little bit faster than Integer.parseInt(String s) from Java:
public class IntBoxSimple {
// IntBoxSimple - Rudimentary class to implement a C#-like tryParse() method for int
// A full blown IntBox class implementation can be found in my Github project
// Copyright (c) 2016, Peter Sulzer, Fürth
// Program is published under the GNU General Public License (GPL) Version 1 or newer
protected int _n; // this "boxes" the int value
// BEGIN The following statements are only executed at the
// first instantiation of an IntBox (i. e. only once) or
// already compiled into the code at compile time:
public static final int MAX_INT_LEN =
String.valueOf(Integer.MAX_VALUE).length();
public static final int MIN_INT_LEN =
String.valueOf(Integer.MIN_VALUE).length();
public static final int MAX_INT_LASTDEC =
Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(1));
public static final int MAX_INT_FIRSTDIGIT =
Integer.parseInt(String.valueOf(Integer.MAX_VALUE).substring(0, 1));
public static final int MIN_INT_LASTDEC =
-Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(2));
public static final int MIN_INT_FIRSTDIGIT =
Integer.parseInt(String.valueOf(Integer.MIN_VALUE).substring(1,2));
// END The following statements...
// ltrimZeroes() methods added 2016 08 16 (are required by tryParse() methods)
public static String ltrimZeroes(String s) {
if (s.charAt(0) == '-')
return ltrimZeroesNegative(s);
else
return ltrimZeroesPositive(s);
}
protected static String ltrimZeroesNegative(String s) {
int i=1;
for ( ; s.charAt(i) == '0'; i++);
return ("-"+s.substring(i));
}
protected static String ltrimZeroesPositive(String s) {
int i=0;
for ( ; s.charAt(i) == '0'; i++);
return (s.substring(i));
}
public static boolean tryParse(String s,IntBoxSimple intBox) {
if (intBox == null)
// intBoxSimple=new IntBoxSimple(); // This doesn't work, as
// intBoxSimple itself is passed by value and cannot changed
// for the caller. I. e. "out"-arguments of C# cannot be simulated in Java.
return false; // so we simply return false
s=s.trim(); // leading and trailing whitespace is allowed for String s
int len=s.length();
int rslt=0, d, dfirst=0, i, j;
char c=s.charAt(0);
if (c == '-') {
if (len > MIN_INT_LEN) { // corrected (added) 2016 08 17
s = ltrimZeroesNegative(s);
len = s.length();
}
if (len >= MIN_INT_LEN) {
c = s.charAt(1);
if (!Character.isDigit(c))
return false;
dfirst = c-'0';
if (len > MIN_INT_LEN || dfirst > MIN_INT_FIRSTDIGIT)
return false;
}
for (i = len - 1, j = 1; i >= 2; --i, j *= 10) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt -= (c-'0')*j;
}
if (len < MIN_INT_LEN) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt -= (c-'0')*j;
} else {
if (dfirst >= MIN_INT_FIRSTDIGIT && rslt < MIN_INT_LASTDEC)
return false;
rslt -= dfirst * j;
}
} else {
if (len > MAX_INT_LEN) { // corrected (added) 2016 08 16
s = ltrimZeroesPositive(s);
len=s.length();
}
if (len >= MAX_INT_LEN) {
c = s.charAt(0);
if (!Character.isDigit(c))
return false;
dfirst = c-'0';
if (len > MAX_INT_LEN || dfirst > MAX_INT_FIRSTDIGIT)
return false;
}
for (i = len - 1, j = 1; i >= 1; --i, j *= 10) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt += (c-'0')*j;
}
if (len < MAX_INT_LEN) {
c = s.charAt(i);
if (!Character.isDigit(c))
return false;
rslt += (c-'0')*j;
}
if (dfirst >= MAX_INT_FIRSTDIGIT && rslt > MAX_INT_LASTDEC)
return false;
rslt += dfirst*j;
}
intBox._n=rslt;
return true;
}
// Get the value stored in an IntBoxSimple:
public int get_n() {
return _n;
}
public int v() { // alternative shorter version, v for "value"
return _n;
}
// Make objects of IntBoxSimple (needed as constructors are not public):
public static IntBoxSimple makeIntBoxSimple() {
return new IntBoxSimple();
}
public static IntBoxSimple makeIntBoxSimple(int integerNumber) {
return new IntBoxSimple(integerNumber);
}
// constructors are not public(!=:
protected IntBoxSimple() {} {
_n=0; // default value an IntBoxSimple holds
}
protected IntBoxSimple(int integerNumber) {
_n=integerNumber;
}
}
Test/example program for class IntBoxSimple:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class IntBoxSimpleTest {
public static void main (String args[]) {
IntBoxSimple ibs = IntBoxSimple.makeIntBoxSimple();
String in = null;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
do {
System.out.printf(
"Enter an integer number in the range %d to %d:%n",
Integer.MIN_VALUE, Integer.MAX_VALUE);
try { in = br.readLine(); } catch (IOException ex) {}
} while(! IntBoxSimple.tryParse(in, ibs));
System.out.printf("The number you have entered was: %d%n", ibs.v());
}
}
Try with regular expression and default parameters argument
public static int parseIntWithDefault(String str, int defaultInt) {
return str.matches("-?\\d+") ? Integer.parseInt(str) : defaultInt;
}
int testId = parseIntWithDefault("1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("test1001", 0);
System.out.print(testId); // 1001
int testId = parseIntWithDefault("-1001", 0);
System.out.print(testId); // -1001
int testId = parseIntWithDefault("test", 0);
System.out.print(testId); // 0
if you're using apache.commons.lang3 then by using NumberUtils:
int testId = NumberUtils.toInt("test", 0);
System.out.print(testId); // 0
I would like to throw in another proposal that works if one specifically requests integers: Simply use long and use Long.MIN_VALUE for error cases. This is similar to the approach that is used for chars in Reader where Reader.read() returns an integer in the range of a char or -1 if the reader is empty.
For Float and Double, NaN can be used in a similar way.
public static long parseInteger(String s) {
try {
return Integer.parseInt(s);
} catch (NumberFormatException e) {
return Long.MIN_VALUE;
}
}
// ...
long l = parseInteger("ABC");
if (l == Long.MIN_VALUE) {
// ... error
} else {
int i = (int) l;
}
Considering existing answers, I've copy-pasted and enhanced source code of Integer.parseInt to do the job, and my solution
does not use potentially slow try-catch (unlike Lang 3 NumberUtils),
does not use regexps which can't catch too big numbers,
avoids boxing (unlike Guava's Ints.tryParse()),
does not require any allocations (unlike int[], Box, OptionalInt),
accepts any CharSequence or a part of it instead of a whole String,
can use any radix which Integer.parseInt can, i.e. [2,36],
does not depend on any libraries.
The only downside is that there's no difference between toIntOfDefault("-1", -1) and toIntOrDefault("oops", -1).
public static int toIntOrDefault(CharSequence s, int def) {
return toIntOrDefault0(s, 0, s.length(), 10, def);
}
public static int toIntOrDefault(CharSequence s, int def, int radix) {
radixCheck(radix);
return toIntOrDefault0(s, 0, s.length(), radix, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int def) {
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, 10, def);
}
public static int toIntOrDefault(CharSequence s, int start, int endExclusive, int radix, int def) {
radixCheck(radix);
boundsCheck(start, endExclusive, s.length());
return toIntOrDefault0(s, start, endExclusive, radix, def);
}
private static int toIntOrDefault0(CharSequence s, int start, int endExclusive, int radix, int def) {
if (start == endExclusive) return def; // empty
boolean negative = false;
int limit = -Integer.MAX_VALUE;
char firstChar = s.charAt(start);
if (firstChar < '0') { // Possible leading "+" or "-"
if (firstChar == '-') {
negative = true;
limit = Integer.MIN_VALUE;
} else if (firstChar != '+') {
return def;
}
start++;
// Cannot have lone "+" or "-"
if (start == endExclusive) return def;
}
int multmin = limit / radix;
int result = 0;
while (start < endExclusive) {
// Accumulating negatively avoids surprises near MAX_VALUE
int digit = Character.digit(s.charAt(start++), radix);
if (digit < 0 || result < multmin) return def;
result *= radix;
if (result < limit + digit) return def;
result -= digit;
}
return negative ? result : -result;
}
private static void radixCheck(int radix) {
if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX)
throw new NumberFormatException(
"radix=" + radix + " ∉ [" + Character.MIN_RADIX + "," + Character.MAX_RADIX + "]");
}
private static void boundsCheck(int start, int endExclusive, int len) {
if (start < 0 || start > len || start > endExclusive)
throw new IndexOutOfBoundsException("start=" + start + " ∉ [0, min(" + len + ", " + endExclusive + ")]");
if (endExclusive > len)
throw new IndexOutOfBoundsException("endExclusive=" + endExclusive + " > s.length=" + len);
}
I've been using a helper class that contains a static Queue of parsed values, and I find it to look quite clean. This would be the helper class could look like:
public static class Parsing {
// Could optimise with specific queues for primitive types
// and also using a circular queue, instead of LinkedList
private static final Queue<Number> QUEUE = new LinkedList<Number>();
public static boolean parseInt(String value) {
// Could implement custom integer parsing here, which does not throw
try {
QUEUE.offer(Integer.parseInt(value));
return true;
}
catch (Throwable ignored) {
return false;
}
}
public static int getInt() {
return QUEUE.remove().intValue(); // user's fault if this throws :)
}
}
And then in code, you use it like this:
public Vector3 parseVector(String content) {
if (Parsing.parseInt(content)) {
return new Vector3(Parsing.getInt());
}
else {
String[] parts = content.split(",");
if (Parsing.parseInt(parts[0]) && Parsing.parseInt(parts[1]) && Parsing.parseInt(parts[2])) {
// the queue ensures these are in the same order they are parsed
return new Vector3(Parsing.getInt(), Parsing.getInt(), Parsing.getInt());
}
else {
throw new RuntimeException("Invalid Vector3");
}
}
}
The only problem with this, is that if you use multiple calls like i did above, but maybe the last one fails, then you'd have to roll back or clear the queue
Edit: You could remove the above problem and include some thread safely, by making the class non-static and, maybe for slightly cleaner code, make the class implement AutoCloseable so that you could do something like this:
public Vector3 parseVector(String content) {
try (Parsing parser = Parsing.of()) {
if (parser.parseInt(content)) {
return new Vector3(parser.getInt());
}
else {
String[] parts = content.split(",");
if (parser.parseInt(parts[0]) && parser.parseInt(parts[1]) && parser.parseInt(parts[2])) {
// the queue ensures these are in the same order they are parsed
return new Vector3(parser.getInt(), parser.getInt(), parser.getInt());
}
else {
throw new RuntimeException("Invalid Vector3");
}
}
}
}
You can use a Null-Object like so:
public class Convert {
#SuppressWarnings({"UnnecessaryBoxing"})
public static final Integer NULL = new Integer(0);
public static Integer convert(String integer) {
try {
return Integer.valueOf(integer);
} catch (NumberFormatException e) {
return NULL;
}
}
public static void main(String[] args) {
Integer a = convert("123");
System.out.println("a.equals(123) = " + a.equals(123));
System.out.println("a == NULL " + (a == NULL));
Integer b = convert("onetwothree");
System.out.println("b.equals(123) = " + b.equals(123));
System.out.println("b == NULL " + (b == NULL));
Integer c = convert("0");
System.out.println("equals(0) = " + c.equals(0));
System.out.println("c == NULL " + (c == NULL));
}
}
The result of main in this example is:
a.equals(123) = true
a == NULL false
b.equals(123) = false
b == NULL true
c.equals(0) = true
c == NULL false
This way you can always test for failed conversion but still work with the results as Integer instances. You might also want to tweak the number NULL represents (≠ 0).
You could roll your own, but it's just as easy to use commons lang's StringUtils.isNumeric() method. It uses Character.isDigit() to iterate over each character in the String.
You shouldn't use Exceptions to validate your values.
For single character there is a simple solution:
Character.isDigit()
For longer values it's better to use some utils. NumberUtils provided by Apache would work perfectly here:
NumberUtils.isNumber()
Please check https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/math/NumberUtils.html

Categories

Resources