Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Java Fundamentals

You're reading from   Java Fundamentals A fast-paced and pragmatic introduction to one of the world's most popular programming languages

Arrow left icon
Product type Paperback
Published in Mar 2019
Publisher
ISBN-13 9781789801736
Length 408 pages
Edition 1st Edition
Languages
Arrow right icon
Authors (5):
Arrow left icon
Miles Obare Miles Obare
Author Profile Icon Miles Obare
Miles Obare
Basheer Ahamed Fazal Basheer Ahamed Fazal
Author Profile Icon Basheer Ahamed Fazal
Basheer Ahamed Fazal
Rogério Theodoro de Brito Rogério Theodoro de Brito
Author Profile Icon Rogério Theodoro de Brito
Rogério Theodoro de Brito
Gazihan Alankus Gazihan Alankus
Author Profile Icon Gazihan Alankus
Gazihan Alankus
Vinicius Isola Vinicius Isola
Author Profile Icon Vinicius Isola
Vinicius Isola
+1 more Show less
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Java Fundamentals
Preface
1. Introduction to Java 2. Variables, Data Types, and Operators FREE CHAPTER 3. Control Flow 4. Object-Oriented Programming 5. OOP in Depth 6. Data Structures, Arrays, and Strings 7. The Java Collections Framework and Generics 8. Advanced Data Structures in Java 9. Exception Handling Appendix

Lesson 3: Control Flow


Activity 6: Controlling the Flow of Execution Using Conditionals

Solution:

  1. Create a class named Salary and add main() method:

    public class Salary {
       public static void main(String args[]) { 
  2. Initialize two variables workerhours and salary.

    int workerhours = 10; 
    double salary = 0;
  3. In the if condition, check whether the working hours of the worker is below the required hours. If the condition holds true, then the salary should be (working hours * 10).

    if (workerhours <= 8 ) 
    salary = workerhours*10;
  4. Use the else if statement to check if the working hours lies between 8 hours and 12 hours. If that is true, then the salary should be calculated at $10 per hour for the first eight hours and the remaining hours should be calculated at $12 per hour.

    else if((workerhours > 8) && (workerhours < 12)) 
    salary = 8*10 + (workerhours - 8) * 12;
  5. Use the else block for the default of $160 (additional day's salary) per day.

    else
        salary = 160;
    System.out.println("The worker's salary is " + salary);
    }
    }

Activity 7: Developing a Temperature System

Solution:

  1. Declare two strings, temp and weatherWarning, and then initialize temp with either High, Low, or Humid.

    public class TempSystem
    {
        public static void main(String[] args) {
            String temp = "Low";
            String weatherWarning;
  2. Create a switch statement that checks the different cases of temp, and then initialize the variable weatherWarning to appropriate messages for each case of temp (High, Low, Humid).

    switch (temp) { 
            case "High": 
                weatherWarning = "It's hot outside, do not forget sunblock."; 
                break; 
            case "Low": 
                weatherWarning = "It's cold outside, do not forget your coat."; 
                break; 
            case "Humid": 
                weatherWarning = "The weather is humid, open your windows."; 
                break;
  3. In the default case, initialize weatherWarning to "The weather looks good. Take a walk outside".

    default: 
      weatherWarning = "The weather looks good. Take a walk outside"; 
      break;
  4. After you complete the switch construct, print the value of weatherWarning.

    } 
            System.out.println(weatherWarning); 
        }
    }
  5. Run the program to see the output, it should be similar to:

    It's cold outside, do not forget your coat.

    Full code is as follows:

    public class TempSystem
    {
        public static void main(String[] args) {
            String temp = "Low";
            String weatherWarning;
                switch (temp) { 
            case "High": 
                weatherWarning = "It's hot outside, do not forget sunblock."; 
                break; 
            case "Low": 
                weatherWarning = "It's cold outside, do not forget your coat."; 
                break; 
            case "Humid": 
                weatherWarning = "The weather is humid, open your windows."; 
                break; 
            
            default: 
                weatherWarning = "The weather looks good. Take a walk outside"; 
                break; 
            } 
            System.out.println(weatherWarning); 
        }
    }

Activity 8: Implementing the for Loop

Solution:

  1. Right-click the src folder and select New | Class.

  2. Enter PeachBoxCounter as the class name, and then click OK.

  3. Import the java.util.Scanner package:

    import java.util.Scanner;
  4. In the main() enter the following:

    public class PeachBoxCounter
    {
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
    System.out.print("Enter the number of peaches picked: ");
    int numberOfPeaches = sc.nextInt();
    for (int numShipped = 0; numShipped < numberOfPeaches; numShipped += 20)      {
    System.out.printf("shipped %d peaches so far\n", numShipped);
    }
    }
    }

Activity 9: Implementing the while Loop

Solution:

  1. Right-click the src folder and select New | Class.

  2. Enter PeachBoxCounters as the class name, and then click OK.

  3. Import the java.util.Scanner package:

    import java.util.Scanner;
  4. In the main() enter the following:

    public class PeachBoxCounters{
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        System.out.print("Enter the number of peaches picked: ");
        int numberOfPeaches = sc.nextInt();
        int numberOfBoxesShipped = 0;
    
        while (numberOfPeaches >= 20) {
            numberOfPeaches -= 20;
            numberOfBoxesShipped += 1;
            System.out.printf("%d boxes shipped, %d peaches remaining\n", 
                    numberOfBoxesShipped, numberOfPeaches);
        }
    }
    }

Activity 10: Implementing Looping Constructs

Solution:

  1. Import the packages that are required to read data from the user.

    import java.util.Scanner;
    public class Theater {
    public static void main(String[] args)
  2. Declare the variables to store the total number of seats available, remaining seats, and tickets requested.

    {
    int total = 10, request = 0, remaining = 10;
  3. Within a while loop, implement the if else loop that checks whether the request is valid, which implies that the number of tickets requested is less than the number of seats remaining.

    while (remaining>=0)
    {
    System.out.println("Enter the number of tickets");
    Scanner in = new Scanner(System.in);
    request = in.nextInt();
  4. If the logic in the previous step is true, then print a message to denote that the ticket is processed, set the remaining seats to the appropriate value, and ask for the next set of tickets.

    if(request <= remaining)
    {
    System.out.println("Your " + request +" tickets have been procced. Please pay and enjoy the show.");
    remaining = remaining - request;
    request = 0;
    }
  5. If the logic in step 3 is false, then print an appropriate message and break out of the loop:

    else
    {
    System.out.println("Sorry your request could not be processed");
    break;
    }
    }
    }
    }

Activity 11: Continuous Peach Shipment with Nested Loops

Solution:

  1. Right-click the src folder and select New | Class.

  2. Enter PeachBoxCounter as the class name, and then click OK.

  3. Import the java.util.Scanner package:

    import java.util.Scanner;
  4. In the main() enter the following:

    public class PeachBoxCount{    
    static Scanner sc = new Scanner(System.in);
    public static void main(String[] args) {
        int numberOfBoxesShipped = 0;
        int numberOfPeaches = 0;
        while (true) {
            System.out.print("Enter the number of peaches picked: ");
            int incomingNumberOfPeaches = sc.nextInt();
            if (incomingNumberOfPeaches == 0) {
                break;
            }
            numberOfPeaches += incomingNumberOfPeaches;
            while (numberOfPeaches >= 20) {
                numberOfPeaches -= 20;
                numberOfBoxesShipped += 1;
                System.out.printf("%d boxes shipped, %d peaches remaining\n",
                        numberOfBoxesShipped, numberOfPeaches);
            }
        }
    }
    }
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime