# int

## A Java method to determine if an integer is between a range

Last night I was writing some code for my Android football game, and decided it would be best if I had a `between` method, so I could write some code like this to show that I wanted to test to see if a number was between an integer range:

`if (between(distance, 8, 10)) { ...`

That could would be interpreted as, “If the `distance` is between the values `8` and `10`, do whatever is in the code block.” (I can make that code more readable in Scala, but in Java I think that’s the best I can do.)

## Java: How to round a float or double to an integer

Java math FAQ: How do I round a float or double to an integer in Java?

Solution: Use `Math.round()` to round a `float` (or `double`) to the nearest integer (`int`) in Java.

You can see how this works in the examples that follow, where the result is shown in the comment after each line:

## How to generate random numbers, characters, and sequences in Scala

Scala FAQ: How do I generate random numbers (or characters) in Scala, such as when testing an application, performing a simulation, and many other situations?

## Solution

Create random numbers with the Scala scala.util.Random class. You can create random integers:

## Scala has no ++ or -- operator; how to increment or decrement an integer?

Scala FAQ: Scala doesn't have the `++` and `--` operators; are the some similar operators or methods that I can use instead?

## Solution

Because `val` fields are immutable, they can’t be incremented or decremented, but `var` integer fields can be mutated with Scala’s `+=` and `−=` methods:

## How to override Scala's default numeric type when defining a field

Scala FAQ: How do I override the default numeric type that Scala assigns when I declare an `Int`, `Long`, `Short`, `Float`, or `Double` val or var field?

## Solution

If you assign `1` to a variable, Scala assigns it the type `Int`:

## How to convert between numeric types in Scala

Scala FAQ: How do I convert between numeric types in Scala, such as from Int to Long, Int to Double, etc.?

## Solution

Instead of using the “cast” approach in Java, use the `to*` methods that are available on all of Scala’s numeric types. These methods can be demonstrated in the REPL (note that you need to hit the [Tab] key at the end of the first example):

## Scala: How to parse a number from a String

Scala FAQ: How do I parse a number (`Int`, `Long`, `Float`, etc.) from a `String` in Scala?

## Solution

Use the `to*` methods that are available on a `String` (courtesy of the Scala `StringLike` trait):