askIT

If and else

Lagre Download example filesr

If and else are two expressions that are used to check if variables are true or not.

An example of if and else is withdrawal at an ATM. Will a user get money from a ATM if he wants to withdrawal $ 50 from ATM, and have $ 100 in his account?

To solve this problem, we must:

package ifandelse;

import java.util.Scanner;

public class Ifandelse {

        public static void main(String[] args) {
                // Import scanner
                Scanner scanner = new Scanner (System.in);
               
                // Variables money in bank
                double balance = 100;
               
                // Ask for withdraw
                System.out.println("Enter withdrawal amount: ");
                double withdrawal = scanner.nextDouble();
               
                // Calculate if it is ok
                double calculation = balance-withdrawal;
               
                // Check if calculation is ok
                if(calculation > -1){
                        System.out.println("Here is your money.");
                }
                else{
                        System.out.println("You do not have enough money on bank account.");
                }
               
        }
}

We check in the if and else if the difference between account balance and the withdrawal is greater than the number -1.
An example is if want to withdraw $ 60, and the balance is $ 100 the formula will be:

double calculation = balance-withdrawal;
calculation = 100-60;

Assignments

1. Extend the program above to view balances before and after the user has withdraw money.

2. Create a program that proposes waxing for cross-country skis. Ask user for temperature outside, and provide suggestions:
red wax for +4°C to -3°C
and
blue wax for -4°C to -15°C.

3. Create an ATM that printer a menu first. In the menu you can choose to withdraw money or to show balance.

4. In Counter Strike, you can buy different weapons and equipment. Create a program which allows the user to purchase various weapons and equipment from a menu. First, create a variable with available amount of money, also let the user buy equipment on the basis of how much money user has.

Available guns should be:
  glock
  usp
  p228
  deagle
  elite
  fn57

Available shotguns should be:
  m3
  xm1014

Available machine guns should be:
  mac10
  tmp
  mp5
  ump45
  p90

Available rifles should be:
  galil
  ak47
  sg552
  famas
  m4a1
  aug

Available snipers should be:
  g3sg1
  sg550
  scout
  awp

Available machine rifles should be:
  m249

Available equipment must be:
  defuser
  vest
  vesthelm
  flashbang
  2flashbang
  grenade
  smoke
  nvgs

Add comment

avatar_blank_60.png

Comment:

Name:

Email:

Comments

No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.