Tuesday, March 15, 2016

Intro To Java: Section 3.3 - Using Switch Statements

Topic 3.3 Overview

In this section we will cover how to use another control structure known as a Switch.

Lecture Video 3.3

Switch Statements

Switch statements in Java allow you to easily define certain paths in which code can be executed based on specific values. Switches are composed of two parts - the switch, which takes the value, and the case, which corresponds to a particular value. For example, you could create a switch that takes a number representing a particular day of the week, and then each case could print out what day it is based on that value. Although you could achieve the same thing using multiple if/else statements. it is much cleaner in this scenario to use a single switch. The end of each code section should end with a break; to end the execution. If you do not include a break, once the case is satisfied, Java will continue executing the following cases regardless of whether or not the value matches the particular case.

public class DayOfWeek{
 public static void main(String[] args) {
  //Day of the week
  int day = 5;
  //Switch
  switch (day) {
   case 1: System.out.println("It is Sunday"); break;
   case 2: System.out.println("It is Monday"); break;
   case 3: System.out.println("It is Tuesday"); break;
   case 4: System.out.println("It is Wednesday"); break;
   case 5: System.out.println("It is Thursday"); break;
   case 6: System.out.println("It is Friday"); break;
   case 7: System.out.println("It is Saturday"); break;
   //Handle all other cases
   default: break;
  }
 }
}
It is Thursday

The above code prints out "It is Thursday" because it begins executing code at the 5th case. If the break statements were not there the blocks would fall through - Cases 5, 6, and 7 would all be executed without a break statement. The default case handles all of the other possible cases - in this case they're all just set to break.

Combining Cases

In addition to having a single case with a single set of actions, it is possible to have multiple cases perform one set of actions. You do this simply by adding multiple cases to a set of actions. The example below demonstrates this.

public class Test {

 public static void main(String[] args) {
  
  //Initialize
  int someValue = 5;
  
  //Create Switch
  switch(someValue){
  //Operations for cases 1, 2, and 3
  case 1: case 2: case 3: 
   System.out.println("Case 1, 2, or 3 has been triggered.");
   break;
  //Operations for cases 4, 5, and 6
  case 4: case 5: case 6:
   System.out.println("Case 4, 5, or 6 has been triggered.");
   break;
  //Default case for all other cases not caught in 1,2,3,4,5,6
  default: break;
  
  }
        
 }

}
Case 4, 5, or 6 has been triggered.

The system prints out that case 4, 5, or 6 has been triggered because someValue is equal to 5. It would also trigger if someValue was equal to 4 or 6. The first block would trigger if the value was 1, 2 or 3, and nothing would be printed if any value less than 1 or greater than 6 is given.

Review Exercise 3.3 - Menu Calculator

Instructions: Create a calculator which prompts the user to enter two values. It should then display a menu with 4 options - 1 to find the sum, 2 to find the difference, 3 to find the product, and 4 to find the quotient. The program should determine which number the user entered using a scanner and then calculate the result within the context of a switch and print out the result to the screen.

Sample Output:

Welcome to Calculator.
Please enter a first value:
10.00
Please enter a second value:
5.00
Would you like to:
1) Find the sum
2) Find the difference
3) Find the product
4) Find the quotient
1
Calculated Sum: 15.00

Console Based Sales Tax Calculator in Java

The code below can be used to create a sales tax calculator in Java. This is for review exercise 3.1 in the Intro to Java Series.
package salestaxcalc;
package topic03SalesTaxCalcReview;
 
import java.math.BigDecimal;
import java.util.Scanner;
 
public class salesTaxCalc {
 
    public static void main(String[] args) {
        //Initialize Variables
        BigDecimal salesTaxRate = new BigDecimal("0.06");
         
        //Create a Scanner & Ask For User Input
        Scanner userInput = new Scanner(System.in);
         
        System.out.println("Enter item price:");
        BigDecimal itemPrice = userInput.nextBigDecimal().setScale(2, BigDecimal.ROUND_HALF_UP);
         
        userInput.close();
         
        //Calculations
        BigDecimal salesTax = itemPrice.multiply(salesTaxRate).setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal totalPrice = itemPrice.add(salesTax).setScale(2, BigDecimal.ROUND_HALF_UP);
         
        //Print Out The Results
        System.out.println("Item Price:  $" + itemPrice);
        System.out.println("Sales Tax:   $" + salesTax);
        System.out.println("Total Price: $" + totalPrice);
         
 
    }
 
}

Monday, March 14, 2016

Intro To Java: Section 3.2 - Decision Making

In this section we will learn how to use control structures to make decisions in Java.

Watch 3.2 Lecture Video

Equality and Relational Operators

Computers are much more than calculators which take input and return formatted output. They can also make decisions using that data. Java makes it extremely easy to make decisions using if then conditional statements. Essentially they work just as they sound - The JVM will check to see if a certain condition is met, and if it is, it will perform a certain set of actions. The three most basic ways you can compare values using if/else statements are checking if two values are equal to one another or if one value is greater or less than the other value. The operators we use to compare values are known as equality and relational operators.

If then statements follow the syntax shown below:

if(conditions){
     //Code to execute in brackets
}

Equality and Relational Operators

You should memorize all the operators below. They are easy to remember and you will use them often.

NameOperatorDescriptionExample
Equal to == Checks if two values are equal if(x==y){}
Not equal to != Checks if two values are not equal if(x!=y){}
Less than < Checks if the first value is less than the second value if(x<y){}
Greater than > Checks if the first value is greater than the second value if(x>y){}
Less than or equal to <= Checks if the first value is less or equal to than the second value if(x<=y){}
Greater than or equal to >= Checks if the first value is greater than or equal to the second value if(x>=y){}

If-Then Statements With Equality

Equality can be assessed using the equality operator "==". We always use two equal signs to determine if two values are equal instead of one because the one equal sign operator is reserved for assigning values. Additionally, the not equals operator "!=" is used to determine if two values are not equal to each other. The following lines of code check to determine what the value of x is and print out a corresponding message based on what the value of x is.

public class EqualityTest{

     public static void main(String []args){
        int x = 5;
        if(x==5){
            System.out.println("x is equal to 5");
        }
        if(x!=5){
            System.out.println("x is not equal to 5");
        }
     }
}

The output of the program is as follows because x is in fact equal to 5. Note that if you change the value of x the second message will be printed instead of the first one.

x is equal to 5

If-Then Statements With Greater/Less Than

In addition to checking for equality, it is also extremely useful to be able to tell if one value is greater than or less than another value. This can be done using the greater than operator ">" and the less than operator "<". Combinations of these can be made with an equals sign to create the greater than or equal to ">=" operator and the less than or equal to "<=" operator.

The example below checks if one value is greater than another and prints out which value is greater.

public class GreaterLessThan{

     public static void main(String []args){
        //Initialize Variables
        double x = 5.0;
        double y = 10.0;
        //Check Values
        if(x>y){
            System.out.println("x is greater than y");
        }
        if(x<y){
            System.out.println("x is less than y");
        }
        if(x==y)
        {
            System.out.println("x is equal to y");
        }
        
     }
}

In this case the output is as follows, because x is less than y. Note that if you change the values of x and y the output can be different.

x is less than y

If Then Else Statements

In addition to if then statements, you can add an else block to create if then else statements. The "else" part of the statement is executed when the if statement is not executed. In other words, if the first condition is not met, it will execute the "else" statement. This helps shorten your code and allows you to use less if then statements. The example below checks if x is greater than or equal to y, and if not it prints out a message saying that x must be less than y.

public class IfElseExample{

     public static void main(String []args){
        //Initialize Variables
        int x = 10;
        int y = 20;
        
        //If Then Else Statement
        if(x>=y){
            //If x is greater than or equal to y
            System.out.println("x is greater than or equal to y");
        }
        else
        {
            //This code is executed if the first block is not executed, so x must be less than y
            System.out.println("x must be less than y");
        }
        
     }
}

The output is as follows, because x is less than y, and not greater than or equal to y, the else block is executed.

x must be less than y

Else If Statements

In addition to the if then else statements shown above, it is possible to have "else if" statements. They function similarly to else statements, but they also have conditions. So if the first condition is not met, Java will check the second, third, fourth, fifth conditions and so on. The example below quite simply prints out whether the value is equal to one, two, or not one of those two values.

public class ElseIfExample{
 
 public static void main(String[] args) {
  int x = 2;
  if(x==1){
   System.out.println("x is equal to one");
  }
  else if(x==2){
   System.out.println("x is equal to two");
  }
  else
  {
   System.out.println("x is not equal to one or two");
  }
 }

}
x is equal to two

Naturally the output is "x is equal to two" because the second condition is satisfied. Note that it stops once the condition is satisfied - the first block (x==1) is skipped and final else block is not executed.

Nested If Statements

It is possible to add if statements within if statements - this is known as nesting. This allows you to check for multiple things. The example below the age of the user based on if they're at or under the age of 10. It then determines if they are male or female after determining if they are 10 years old or younger with a second if statement within the first.

public class NestedExample{

 public static void main(String[] args) {
  
  //Nested If Statement Example
  int age = 6;
  boolean isMale = true;
  
  //Check to see if user is under the age of 10 and is a male
  if(age<=10){
   if(isMale==true){
    System.out.println("The user is a male under the age of 10");
   }
   else{
    System.out.println("The user is a female under the age of 10");
   }
  }
  else{
   System.out.println("The user is over the age of 10");
  }

 }

}

 

The user is a male under the age of 10

Multiple Conditions With And/Or

It is possible to have multiple conditions in a single if statement. This can be used as an alternative to nested if statements. The example below produces the same types of output as the previous example, but this uses the logical AND operator "&&". This means both conditions must be true for the block to execute. You can add as many additional conditions to the statement as you want.

public class Test {

 public static void main(String[] args) {
  
  //Example Using AND
  int age = 6;
  boolean isMale = false;
  
  //Check if user is under the age of 10 and is a male
  if(age<=10 && isMale==true){
   System.out.println("The user is a male under the age of 10");
  }
  //Check if user is under age of 10 and is female
  else if (age<=10 && isMale==false){
   System.out.println("The user is a female under the age of 10");
  }
  //User is over the age of 10
  else
  {
   System.out.println("The user is over the age of 10");
  }
  
 }
}
The user is a female under the age of 10

The output is "The user is a female under the age of 10" because the first condition is not satisfied (the user is not a male) so it continues on to the second block (the user is a female age 10 or younger).

The logical OR operator is made using two vertical bars "||" (should be located above the enter/return key). When you use OR operators if EITHER of the conditions are true in the if statement, the block will be executed.

public class Test {

 public static void main(String[] args) {
  
  //Example Using OR
  int age = 66;
  boolean isMale = true;
  
  //Check to see if the user is under the age of 10 OR if they are male
  if(age<=10 || isMale==true){
   System.out.println("The user is a male and/or is under the age of ten");
  }
  //If they are not a male OR aged < = 10 they MUST be female AND over the age of 10
  else
  {
   System.out.println("The user must be a female over the age of 10");
  }

 }
}
The user is a male and/or is under the age of ten

The output states that the user is a male and/or is under the age of ten because the user is a male. Even though they are aged 66 the first block is still executed. If this used an AND operator instead of an OR operator like the previous example, the first block would not have been executed. The else block of code will only be executed if the user is over the age of 10 and is a female - because that is the only logical thing that follows if the user is not a male or aged 10 or younger.

Combining/Multiple Operators

In addition to using a single and/or operator, it is possible to use multiple. You can separate each comparison using parenthesis. The example below prints out information based on the user's age, sex, and hair color.

 

The user is a male over age 30 AND/OR they have blond hair

Note what this code is doing. First, it checks if they are a male over the age of thirty, and then it checks if they have blond hair. If either of these conditions are true, the first message is printed. The second condition (haircolor=='R') checks to see if the user's hair color is red - this block will only be executed if the user has red hair and is not a male over age thirty. Try changing the values of the variables to see how it affects the results.

Additionally, notice that you do not have to check if "isMale==true" in the first condition - you can simply type the name of the boolean to check boolean values. If the boolean is true Java will execute the code. In other words, "if(isMale){}" is equivalent to "if(isMale==true){}". It's slightly shorter to type it this way.

public class Test {

 public static void main(String[] args) {
 
  //Example - Combining AND and OR
  
  int age = 43;
  boolean isMale = true;
  char hairColor = 'R'; //Red hair (R), Brown hair (B), or Blond Hair (L) 
  
  //Check to see if they are a male over the age of 30 OR if they have blond hair
  if((isMale && age>=30) || hairColor=='L'){
   System.out.println("The user is a male over age 30 AND/OR they have blond hair");
  }
  else if(hairColor=='R'){
   System.out.println("The user is not a male over age 30 and their hair color is Red.");
  }

 }
}

Sunday, March 13, 2016

Intro To Java: Section 3.1 - BigDecimals

In this section you will learn how to create and use BigDecimals to store currency values and control rounding.

BigDecimals

Unfortunately none of the primitive data types are apropriate for storing currency. Integers and longs cannot hold decimals. Floats and doubles are not percise enough to represent currency. If we used floats and doubles to perform calculations in important financial systems the values could regularly be off by one penny or more. Balances would be off, customers would be angry, and accounting would be impossible. This is where the BigDecimal object comes into play - BigDecimals are specialized objects which are appropriate for storing currency values. BigDecimals are immutable objects meaning once you create it its value cannot be changed directly - in order to perform computations you must use the appropriate BigDecimal methods and create entirely new BigDecimals. In order to access this class in your program, it must be properly imported in the same manner as the Scanner object from the previous topic. In order to import and use Big Decimals, you must access it from the math package of the Java API.

import java.math.BigDecimal;
Once you've imported the BigDecimal class you will be able to use BigDecimals in your code. Keep in mind that BigDecimals are not the same as primitive data types. Like Scanner objects, BigDecimals are also treated as objects and must be initialized as follows. First you must tell Java what type of object you are creating (BigDecimal) and name it (myDecimal). You must then initialize it as a new BigDecimal object with a value of your choice. Pass the value you would like to set it to as the first argument. (I chose 250.05).

BigDecimal myDecimal = new BigDecimal("250.05");
Now that the BigDecimal is initialized we can use it elsewhere in our code. Just like primitive data types, we can add, subtract, divide, and multiply. Unfortunately we cannot simply use the traditional operators (+, -, /, *). We must use the methods provided to us by the BigDecimal class. View the following example.

//Create Big Decimals
 //Note - We are passing the argument as a string instead of a double (note the quotes)
 //       the quotation marks are optional here but this prevents rounding errors.
 BigDecimal decimalOne = new BigDecimal("10.00");
 BigDecimal decimalTwo = new BigDecimal("5.00");
 
 //Operation Examples using BigDecimal methods
 //Addition decimalAdditionResult = decimalOne + decimalTwo
 BigDecimal decimalAdditionResult = decimalOne.add(decimalTwo);
 
 //Subtraction decimalSubtractionResult = decimalOne - decimalTwo
 BigDecimal decimalSubtractionResult = decimalOne.subtract(decimalTwo);
 
 //Multiplication decimalProductResult = decimalOne * decimalTwo
 BigDecimal decimalProductResult = decimalOne.multiply(decimalTwo);
 
 //Division decimalDivisionResult = decimalOne / decimalTwo
 BigDecimal decimalDivisionResult = decimalOne.divide(decimalTwo);
The code above is fairly simple to understand. All we're doing is applying operations to decimalOne using whatever values are passed in the arguments - the value is then stored in the new respective result BigDecimal. Whenever you use these operations (add/subtract/multiple/divide) you are generating a new BigDecimal.
Although BigDecimals are immutable objects, it is possible to "change" their values indirectly by updating their reference variable. Technically, you are not changing the value of the BigDecimal, but instead are creating an entirely new BigDecimal object to which the old variable name references. For example, you could add a second BigDecimal to a first BigDecimal using the .add() method - this returns an entirely new BigDecimal to which you can reference using the old name. This works because we are not directly modifying the values of the original BigDecimal, but are replacing it with a new BigDecimal that has the same name.

import java.math.BigDecimal;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create BigDecimals
  BigDecimal someDecimal = new BigDecimal("14.00");
  BigDecimal otherDecimal = new BigDecimal("6.00");
  
  //Add otherDecimal to someDecimal
  someDecimal = someDecimal.add(otherDecimal);
  
  //Print
  System.out.println("The value of someDecimal is " + someDecimal.toString()); 
  
 }
}
The value of someDecimal is 20.00
Note that if you are doing this, you must always do it in this format: "someDecimal = someDecimal.add(otherDecimal);" - you cannot just have "someDecimal.add(otherDecimal);"
The diagram below illustrates what happens in the previous example.
Given this knowledge, it is also possible to change the value of the BigDecimal by having it reference a new BigDecimal.

import java.math.BigDecimal;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create BigDecimals
  BigDecimal aDecimal = new BigDecimal("14.00");
  
  System.out.println("The value of aDecimal is: " + aDecimal.toString());
  
  //Reference a new BigDecimal
  aDecimal = new BigDecimal("10.00");
  System.out.println("The value of aDecimal is: " + aDecimal.toString());
 }
}
Output
The value of aDecimal is: 14.00
The value of aDecimal is: 10.00

Printing Results

You may print out the results in the same manner that we printed out the values of variables in the previous sections. Note that Java is actually converting the value of the BigDecimal into a string automatically. This means we don't have to manually convert the BigDecimal into another primitive data type such as a double before we print out its result.

 //Printing out results - Java automatically converts BigDecimals to Strings for output
  System.out.println("Addition result is: " + decimalAdditionResult);
  System.out.println("Subtraction result is: " + decimalSubtractionResult);
  System.out.println("Product result is: " + decimalProductResult);
  System.out.println("Divison result is: " + decimalDivisionResult);
Addition result is: 15.00
Subtraction result is: 5.00
Product result is: 50.0000
Divison result is: 2
It is also possible to manually convert the BigDecimal to a string and then print out its value. Note that the two examples below are basically the same thing - we're just printing out two concatenated strings.

//Convert to String - option one
  String resultString = decimalAdditionResult.toString();
  System.out.println("Result is: " + resultString);
  
  //All in one step - option two
  System.out.println("Result is: " + decimalAdditionResult.toString());
Result is: 15
Result is: 15
Alternatively, you could manually convert the BigDecimals to doubles and then print the values out to whatever amount of spaces you want using the proper format specifiers. BigDecimals can be converted to doubles using the .doubleValue method.

//Convert Result to Double
  double additionResult = decimalAdditionResult.doubleValue();
  System.out.printf("The addition result to two decimal places is %.2f",additionResult);
The addition result to two decimal places is 15.00
Just like the string result of the BigDecimal can be printed using one line of code - we can also print out the double result for the BigDecimal using one line of code by throwing the BigDecimal.doubleValue directly into the print method's arguments.

System.out.printf("The addition result to two decimal places is %.2f",decimalAdditionResult.doubleValue());
You may use any of the above methods to print out the values of variables. Many other objects in Java aside from BigDecimal also make use of the .toString and .doubleValue methods.

Setting Scale To Control Rounding

In addition to being able to control the amount of decimal places in BigDecimals by converting them to doubles you can also use the BigDecimal setScale method. This is the preferred way to do it because it gives you control over exactly how your decimals will be rounded. After creating your BigDecimal, you can use the setScale method to define the amount of decimal places you would like the BigDecimal to go to. In most cases with currency you will be using a value of 2 to go to two decimal places. The format for creating a BigDecimal with a set scale is as follows:

BigDecimal someDecimal = new BigDecimal("value").setScale(scale, roundingMode);
The beginning of the BigDecimal is set in the same manner as we previously created BigDecimals. Now however, we have introduced the .setScale method. You should always pass this two arguments. First, you should pass it an integer which represents how many decimal places you want to use. Second, you need to select a rounding mode. There are five main rounding modes we will discuss. Additional modes exist and can be referenced in the Java API.
  • BigDecimal.ROUND_CEILING: Rounds to the next highest number (1.222 -> 1.23) (-1.222 -> -1.22)
  • BigDecimal.ROUND_DOWN: Rounds in the direction of zero (1.222 -> 1.22) (-1.222 -> -1.22)
  • BigDecimal.ROUND_FLOOR: Rounds to the next lowest number (1.222 -> 1.22) (-1.222 -> -1.23)
  • BigDecimal.ROUND_HALF_UP: Rounds up if the decimal is >= 5 (1.225 -> 1.23) (1.224 -> 1.22)
  • BigDecimal.ROUND_HALF_DOWN: Rounds down if the decimal is <= 5 (1.225 -> 1.22) (1.226 -> 1.23)
Typically in math class we're taught to round up at 0.5 and down at 0.4 - so this fits with the BigDecimal.ROUND_HALF_UP rounding mode. The example below demonstrates this type of rounding.

import java.math.BigDecimal;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create a BigDecimal
  BigDecimal someDecimal = new BigDecimal("14.555").setScale(2, BigDecimal.ROUND_HALF_UP);
  
  //Print
  System.out.println("The value of someDecimal is " + someDecimal.toString()); 
  
 }
}
Output:
The value of someDecimal is 14.56
The output was 14.56 because 14.555 was rounded up to 14.56.

Unreferenced Objects With BigDecimals

In Java, it is possible to create unreferenced objects, which are not referenced by name. This is especially useful in situations where you want to create an object for a single purpose and then get rid of it. The example below illustrates how we would typically add 10 to a BigDecimal object - by creating a second BigDecimal which holds the values we want to add and then combining the two BigDecimals and storing them in a third BigDecimal which stores the total sum.

import java.math.BigDecimal;
public class Test {
 public static void main(String[] args) {
  //Adding 5 to aBigDecimal
  //Create aBigDecimal
  BigDecimal aBigDecimal = new BigDecimal("5");
  BigDecimal bBigDecimal = new BigDecimal("10");
  //Add the two together and store result in sumDecimal
  BigDecimal sumDecimal = aBigDecimal.add(bBigDecimal);
  //Print Results
  System.out.println("aBigDecimal + 10 = " + sumDecimal.toString());   
 }
}
aBigDecimal + 10 = 15
But what if you want to add 10 to aBigDecimal without creating bBigDecimal to store the value of 10? If you're only using the value 10 one time to perform one computation it's quite tiresome to create a second bBigDecimal object. This can be simplified by using an unreferenced object. You can create unreferenced objects without names directly in the arguments for the BigDecimal arithmetic methods.

import java.math.BigDecimal;
public class Test {
 public static void main(String[] args) {
  //Adding 5 to aBigDecimal
  //Create aBigDecimal
  BigDecimal aBigDecimal = new BigDecimal("5");
  //Add 10 to aBigDecimal and store the result in sumDecimal
  BigDecimal sumDecimal = aBigDecimal.add(new BigDecimal("10"));
  //Print Results
  System.out.println("aBigDecimal + 10 = " + sumDecimal.toString());   
 }
}
aBigDecimal + 10 = 15
The result is the same as in the previous example, but the method is different. We added "(new BigDecimal("10")" directly inside the arguments for the BigDecimal addition method. This created an unreferenced BigDecimal object with the value of 10 so we didn't have to create a second bBigDecimal to perform the one time computation.

Scanners With BigDecimals

It is important to understand how to get user input and store it as a BigDecimal. The method works quite similarly to how it did in the previous lesson. The example below demonstrates how you can ask a user to give you a monetary value and then print that value to the screen.

import java.math.BigDecimal;
import java.util.Scanner;
public class Topic03Demos {
 public static void main(String[] args) {
  
  //Create a scanner
  Scanner userInput = new Scanner(System.in);
  
  //Ask the user for a value
  System.out.println("Enter some monetary value");
  BigDecimal numberEntered = userInput.nextBigDecimal();
  
  //Close Scanner
  userInput.close();
  //Print Result
  System.out.println("The value of numberEntered is " + numberEntered.toString());
 }
}
Output:
Enter some monetary value
20.20
The value of numberEntered is 20.20

Review Exercise 3.1: Sales Tax

Instructions:Create a simple program using BigDecimals that calculates a sales tax of 6% and prints out the total.
Suggested Methodology:
  1. Create a Scanner to retrieve user input as a BigDecimal
  2. Create a BigDecimal with value 0.06 for multiplying with total to calculate taxes
  3. Create an additional taxes BigDecimal and total BigDecimal to store the tax amount and the total.
  4. Use the .setScale method to set the rounding scale to 2 on each of the BigDecimals.
  5. Use the BigDecimal methods to calculate the taxes and totals
  6. Print out the results
Sample Output
Please enter item price:
100.00
Item Price: $100.00
Sales Tax: $6.00
Total Price: $106.00
View Solution

Intro to Java: Topic 03 - Money & Decision Making Overview


Topic 03: Money & Decision Making, discusses how to keep track of currency using BigDecimals. Additionally, you will learn how you can use Java to make decisions using if/then/else statements. We will learn how basic logic works with regards to computers. We will also discuss how switches may be used. For the final review exercise we will create a program that can calculate federal income tax based on set tax brackets.

Intro To Java: Section 2.4 - Importing Scanners

In this section we will discuss using Scanners to take user input from the console.

Watch Lecture Video 2.4

Scanners

One of the most useful things about computers is their ability to take user input and perform computations. In the example programs we've looked at so far all of the variable values have been hard coded into the programs - but this severely limits their functionality. A program that only calculates the area of a circle with a radius of 1.5 is pretty useless to most people. What we need is a program that asks the user the radius, and can then find the area of any circle. We do this with user input. In Java, you can read user input from the console using the scanner object.

The scanner object can be found within the "util" package of the Java API. As was stated in the previous lesson the Java API includes all the objects you can use by default with Java. This is what fundamentally makes Java an object oriented programming language. We can access objects from the Java API by importing them into our java files using an import statement. The diagram to the right visually represents how this happens.

Using the Import Statement

You can use the keyword import followed by the name of the package you want to import from the Java API. In this case, the scanner class is stored with "util" package, so our import statement looks as follows:

import java.util.Scanner;

All import statements can be placed directly at the top of the class file, right after the package declarations. If you create a new Java project with an import statement it should look something like what follows:

package test1;

//import at beginning of the file after package
import java.util.Scanner;

public class main {

 public static void main(String[] args) {
  
  //Todo: Create a scanner and use it
 }

}

Creating & Using The Scanner

Now that we have imported the scanner class we can begin using it. To create any object in follow you will use the following syntax:

ObjectType objectName = new ObjectType(Arguments);

In the case of scanners, the object type is "Scanner," you may name the scanner whatever you want. The argument we use to create a scanner is a System.in input stream object - this essentially lets the scanner that it should be expecting input. Write the following code in the main method of your test program.

Scanner userInput = new Scanner(System.in);

Once the scanner has been created, you can use it to get user input and store it in a variable. It is important that you use the right scanner method to get the proper data type (i.e. don't look for integers when users are entering strings). The example below illustrates how this is done and how the scanner is used. You may also view example console output below.

//import at beginning of the file after package
import java.util.Scanner;

public class main {

 public static void main(String[] args) {
  
  //Create the scanner
  Scanner userInput = new Scanner(System.in);
  
  //Get user input
  System.out.println("Please enter a number.");
  //Create variable "userNumberEntered" and set it to the next integer the user enters
  int userNumberEntered = userInput.nextInt();
  //Print out the value of the number
  System.out.println("You have entered the number: " + userNumberEntered);
  
  //Close the scanner
  userInput.close();
  
 }

}
Please enter a number.
5
You have entered the number: 5

Note that in addition to using the .nextInt() method, you may also use the .nextLine() and .nextDouble() methods to get the values of strings and doubles respectively. Also pay attention to the last line of code in the program which closes the scanner after we are done using it. This will be important in the future to prevent resource leaks. Make sure you always close the scanner when you're done using it.

Review Exercise 2.4: Calculator

Instructions: Given the knowledge you've gained in this section on how to use and manipulate variables, create a program that allows the user to enter two double values. The program should then find the sum, product, quotient, and remainder of the two values and print them out.

Stop: Before you begin reading the suggested methodology below, try to think about the steps you need to take to make this application yourself. Try to create the program yourself without following my instructions word for word, then come back and see how I did it if you still need help.

Suggested Methodology:

  1. Create a new project called "BasicCalculator"
  2. Create a new class "calculator.java"
  3. Import the Scanner and setup the main method
  4. Create the input Scanner
  5. Ask the user to input values and save their input as doubles using the .nextDouble() method on the scanner
  6. Create separate variables and use them to compute the sum, product, quotient, and remainder.
  7. Print the values of the variables to the screen
  8. Close the scanner
  9. Run your program to see if it's working and compare it to the source code I've provided

Sample Output

Welcome to Calculator.
Please enter first value: 
100
Please enter second value:
10
The results are as follows:
Sum 100.000000 + 10.000000 = 110.000000 
Product 100.000000 x 10.000000 = 1000.000000 
Quotient 100.000000 / 10.000000 = 10.000000 
Remainder 100.000000 / 10.000000 = 0.000000 

Debugging Tips:

Review your code for syntax errors, improperly spelled object/variable names, missing semicolons, brackets, etc.

If you run into any issues or errors when you attempt to execute your program try the following:

  • Pay attention to where the error occurred and attempt to read the error message to determine what you did wrong
  • Make sure you created and use all of your objects properly, that they all have proper arguments.
  • Make sure you're using the correct data type for the operation you're doing (i.e. don't add a string to a double)
  • Double and triple check code for syntax errors
  • Compare your code to my example code
  • Post your code in the forums and ask for help
Watch Exercise Walkthrough Video View Calculator Solution