Conditional logic in Java
Overview
Teaching: 30 min
Exercises: 30 minQuestions
How to implement branches and decision points in Java contorl flow?
How do I use if statements?
Objectives
Understand the if statement syntax.
Apply operator logic to resolve scenario based problems.
Conditional logic exercises
- Recall that the we can use command-line arguments from args[] which are passed as an array of String variables.We can also use a prompt and take input from the user. So for example:
Scanner sc= new Scanner(System.in); //System.in is a standard input stream.
System.out.print("Enter a string: ");
String str= sc.nextLine(); //reads string.
System.out.println("Here is what you entered: " + str)
Create a simple program, HelloMatt, that asks the user to input a name then prints “Hello “ + name unless the name is ‘Matt’. If the user inputs ‘Matt’ print ‘Hello Matt the programmer!’.
Note, the == boolean comparator does not work as you might expect for the String class so try using .equals() method.
- Note that the Scanner object (with System.in) does not return anything until the user presses return or enter. Note also that the input always returns a string, even if you enter a number. You can convert the entered number into an int using Integer.parseInt( input ).
Consider the following hypothetical scenario: A government decides to simplify the income tax regulations so that the amount of tax a person pays depends solely on their taxable income. The tax rate paid is then defined by the table below.
Taxable income | Tax rate |
---|---|
Up to $11,000 | 0% |
$11,001 to $43,000 | 30% |
$43,001 to $150,000 | 40% |
Over $150,000 | 55% |
Note, the current UK system is more complicated.
if statements can help detect the boundaries of the tax brackets. Write a program, TaxOwed, that uses if statements to calculate and print the amount of tax that should be paid by a person with the given income. Use System.in and the Scanner class to ask the user for an income for which your program will then print the amount of tax owed per year.
Solution link
- Write a program Odd that asks the user for a number and prints true if the number is odd. Test your function on the following values 1, 2, 3, 4, -2, 2.5. Note, you may want to use defensive programming and input validation.
Key Points
Java is a general purpose, high-level, compiled, strongly typed, object oriented programming language