Program Logic

Unit 4 Index

Number Methods

Common Number Methods

Number manipulation is something that every developer does. One of the most common tasks is to parse a string into a number. To parse means to change. If you ask the end-user to give you a number, you do not know if they followed directions. Perhaps they gave you the word four, instead of the number 4. Rule number one of programming; never trust end-user input. Always validate their input before you try to use it. In addition, to parsing abilities, high-level programming languages have several library methods that help you do the math.

Parsing a String into a Number

The ability to parse is common to most high-level languages, however, the syntax may vary. Remember, learn the concepts; the knowledge is portable to other languages. Java has several parsing methods. Remember in this course, we mainly use int and double to represent numbers. Also remember, that int and double are primitive types with most, but not all the capabilities of their wrapper class. For these reasons, we call upon wrapper classes for parsing. Each parsing method, accepts a String and returns a specific data type. The Java syntax is:

int myInt = Integer.parseInt(stringNumber);
double myDouble = Double.parseDouble(stringNumber);

Input Mismatch Exception

Simple enough, except there is one huge “gotcha”. If the value you are trying to parse is not actually a numerical value and you do not handle that situation, your program will crash with an input mismatch exception.

One way to handle the situation is to use a try/catch block, which is beyond the scope of this course. Mainly, we will be using the Scanner object and therefore can access some of its built-in methods. The Scanner can pre-read input, so you can ask the Scanner “Please let me know if the next thing the end-user enters is an int” If the answer comes back as true, then you know it is safe to save the end-user input into your int variable. Do not worry, we will cover this concept more in the future.

Math Library Methods

Java has a Math class, which has many methods to handle tasks such as rounding, square root, finding the max or min of two numbers, and generating a random number. Every year some student says that there really is not such thing as a random number generator. I know, but its close.

Math.random()

The basic Java syntax for this method is: double myValue = Math.random(); This syntax will only return a double value that is greater than or equal to 0.0 but less than 1.0. Yes, you read that right. Your number is never less than zero and it will never be 1.0, that is unless you code the method differently.

Below are some examples of coding Math.random() differently. Please study these examples.

//ten will be greater than or equal to 0, but less than 10
double ten = Math.random()* 10;
System.out.println(ten);

//eleven will be greater than or equal to 1, and can include 10
double eleven = (Math.random() * 10) + 1;
System.out.println(eleven);

//generating a number within a range
//genRange will be greater than or equal to 1 but can include 20
int minValue = 1;
int maxValue = 20;
int range = (maxValue - minValue) + 1;
double genRange = (Math.random() * range) + minValue;
System.out.println(genRange);

Math.round()

The .round() method returns the closets whole number. If the number you wish to round is a double data type, then Math.round() returns a long. If the number you wish to round is a float data type, then Math.round() returns a int. Remember, a long is a whole number data type that can contain a very large number. The max value of a long is greater than the max value of an int

Simplified Java code might be similar to this: long myLongValue = Math.round(doubleNumber);

Take a look at the generated random numbers above and notice they have quite a few decimal places. There are a couple of ways to round those number into whole number and using Math.round() is one of them.

Chaining Methods

In the String Library Methods, I chained together two methods, .toLowerCase() and .contains(). You can also chain together Math methods. Remember, Math.random, returns a double, however, think about when you ask someone to pick a number between one and ten. You usually do not expect them to choose a fractional number. So if you need to generate a whole number, you can chain together Math.round() with Math.random

Simplified Java code might be similar to this: long myGenValue = Math.round((Math.random() * 10) + 1); Notice that the variable myGenValue is a data type of long. This is because the method .round() returns a long when fed a double. Unlike casting, using the library method .round() follows established rounding rules, so if the decimal portion of your generated number is greater than or equal to .50, then the result is rounded up to the nearest whole number.

Math.min() and Math.max()

The library methods .min() and .max() compare two numbers and lets you know which is the smaller or greater of the two depending on which library method you use.

Simplified Java code might be similar to this:

int min = Math.min(x,y); 
int max = Math.max(x,y);

Casting

Casting is not a library method, however, you can use the technique to change one number type into a different number type. Be careful! If you cast a double into an int, it does not round, it just drops the values after the decimal points. If you cast a number that has been put through the Math.round() method, then you are writing unneeded code because the the rounding rules were already applied, therefore your number is already a whole number.

Simplified Java code might be similar to this:

int castFromDouble = (int)doubleNumber; 

Casting is used in situations other than math. However, keep in mind, when doing the math, casting does not round.

Comparing Numbers

The double equals sign ( == ) is a comparison operator. It is used when you want to compare two numbers. Again, typically, when you compare two pieces of data, you want to make a decision based on whether or not the values match each other. Please review the code below.


Scanner input = new Scanner(System.in);

int guess = 0;
final int ANSWER = 15;

System.out.println("Can you guess what whole number I am thinking of?");

guess = input.nextInt();

if(guess == ANSWER){
	System.out.println("Wow, you are good!");
}

The line of code that starts with the keyword if is the decision statement. Basically you are saying if what the end-user entered and my named constant compare equally, then print the statement between the curly braces. The next chapter in this unit goes over the Scanner object.

What You Learned

What's next?

The next chapter in this unit is: Common Print Methods