3 – Loops (Level 3)

1 Sample Code

1.1 for Loop

public class ForLoop
{
    public static void main (String args [])
    {
        for (int i = 1; i <6; i++)
        System.out.println(i);
    }
}

1.2 while Loop

public class  WhileLoop
{
    public static void main (String args [])
    {
        int count = 1;
        while(count < 6)
        {
            System.out.println(count);
            count++;
        }
    }
}

1.3 do while Loop

import java.util.Scanner;
public class DoWhile
{
    public static void main (String args [])
    {
        Scanner scan = new Scanner(System.in);
        do
        {
            System.out.println("Are we there yet?");
        }while(!scan.nextLine().equals("yes"));
        System.out.println("Good!");
    }
}

2 Exercises

  1. Use a for loop to print the 5 times table up to 12 x 5
  2. Use a for loop to print the 7 times table up to 12 x 7 in the form “3 x 7 = 21”
  3. Use a for loop to print the following sequence: 0.5, 0.4, 0.3, 0.2, 0.1, 0
  4. Use a for loop to print the following sequence: 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0,03
  5. Use a for loop to print five random numbers between 1 and 10
  6. Use a for loop to print the first ten square numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100
  7. Use a for loop to print the first ten triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36,45, 55
  8. Use a while loop to print the numbers from 1 to 10 inclusive
  9. Use a while loop to print the sequence 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1
  10. Use a while loop to print the 4 times table up to 12 x 4.
  11. Use a while loop to print the 9 times table up to 12 x 9 in the form “1 x 9 = 9, 2 x 9=18… “
  12. Prompt the user to enter a number. Keep a running total of the numbers entered. Loop until the user enters -1, exit the loop and print the total
  13. Prompt the user to enter a number. Keep a running total of the numbers entered. Loop until the user enters -1, exit the loop and print the average
  14. Write a program to test if 91 is prime. Use a while loop to divide 91 by the numbers from 2 to 10. Output True if none of the numbers 91%(number) = 0 for any of the numbers, output False otherwise.
  15. Write a program to test if any number is prime. Use a while loop to divide the input by the numbers from 2 to sqrt(input). Output “Prime” if the number is prime, “Not Prime” otherwise.
  16. Use a while loop to print the sequence 1, -2, 3, -4, 5, -6, 7, -8
  17. Use a while loop to calculate pi using the Liebniz formula pi/4 = 1 – 1/3 + 1/5 – 1/7 + 1/9 – … How many iterations do you need to get 3.141?

2 – Selection Answers

1) Prompt the user as follows: “What’s the capital of France?” Output “Correct” if they enter “Paris”, output “Incorrect” otherwise

Scanner scan = new Scanner(System.in);
System.out.println("What's the capital of France?");
String ans = scan.nextLine();
if(ans.equalsIgnoreCase("Paris"))
{
    System.out.println("Correct");
}
else
{
    System.out.println("Incorrect");
}

2) Prompt the user as follows: “Name a month that starts with the letter A”: Output “Correct” if they enter “April” or “August”, output “Incorrect” otherwise

Scanner scan = new Scanner(System.in);
System.out.println("Name a month that starts with the letter A");
String ans = scan.nextLine();
if(ans.equalsIgnoreCase("April")||ans.equalsIgnoreCase("August"))
{
    System.out.println("Correct");
}
else
{
    System.out.println("Incorrect");
}

3) Prompt the user as follows: “Name a Beatle”. Output “Correct” if they enter “John”, “Paul”, “George” or “Ringo”, output “Incorrect” otherwise

Scanner scan = new Scanner(System.in);
System.out.println("Name a Beatle");
String ans = scan.nextLine();
if(ans.matches("John|Paul|George|Ringo"))
{
    System.out.println("Correct");
}
else
{
    System.out.println("Incorrect");
}

4) An online whisky shop charges for shipping as follows: One bottle, £5.99; two to five bottles, £7; more than five bottles, free. Prompt the user to enter the number of bottles bought and output the shipping cost.

Scanner scan = new Scanner(System.in);
System.out.println("Number bottles purchased:");
int number = scan.nextInt();
if(number == 1)
{
    System.out.println("Shipping £5.99");
}
else if (number <=5)
{
    System.out.println("Shipping £7");
}
else
{
    System.out.println("Shipping Free");
}

5) An online bookshop charges shipping as follows: Orders less than £10, £2.99; orders £10 and over, free; add on £2.50 for all orders if next day delivery is selected. Prompt the user to enter the cost of the order, and then prompt for next day delivery. Output the shipping cost.

Scanner scan = new Scanner(System.in);
System.out.println("Next Day Delivery (y/n)?");
String del = scan.nextLine();
System.out.println("Input order Cost:");
double cost = scan.nextDouble();
double shipping = 0;
shipping = cost < 10 ? 2.99 : 0;
if(del.equals("y"))
{
    shipping += 2.50;
}
System.out.println("Cost of shipping: £" + shipping);

6) Prompt the user to enter a number. Output if the number is odd or even.

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 2 == 0)
{
    System.out.println("even");
}
else
{
    System.out.println("odd");
}

7) Prompt the user to enter a number. Output Fizz if the number is divisible by 3, otherwise just output the number

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 3 == 0)
{
    System.out.println("Fizz");
}
else
{
    System.out.println(number);
}

8) Extend yesterday’s problem so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5 and otherwise just output the number.

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 3 == 0)
{
    System.out.println("Fizz");
}
else if(number % 5 == 0)
{
    System.out.println("Buzz");
}
else
{
    System.out.println(number);
}

9) Now extend yesterday’s problem further so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5, output Fizz Buzz if the number is divisible by both 5 and 3 and otherwise just output the number.

Scanner scan = new Scanner(System.in);
System.out.println("Input Number:");
int number = scan.nextInt();
if(number % 3 == 0 && number % 5 ==0)
{
    System.out.println("Fizz Buzz");
}
else if(number % 3 == 0)
{
    System.out.println("Fizz");
}
else if(number % 5 == 0)
{
    System.out.println("Buzz");
}
else
{
    System.out.println(number);
}

2 – Selection (Level 2)

1 Sample Code

1.1 Simple Selection

System.out.println("Enter your surname");
Scanner scan = new Scanner(System.in);
String surname = scan.next();
System.out.println("Are you M or F?");
String sex = scan.next();
if(sex.equals("M"))
{
    System.out.println("Hello Mr " + surname);
}
else
{
    System.out.println("Hello Ms " + surname);
}

1.2 Operators

public class  div37
{
    public static void main (String args [])
    {
        int x = 21;
        if (x%3 == 0 & x%7 == 0)
            {
                System.out.println("Number divisible by 3 and 7");
            }
    }
}

2 Exercises

  1. Prompt the user as follows: “What’s the capital of France?” Output “Correct” if they enter “Paris”, output “Incorrect” otherwise
  2. Prompt the user as follows: “Name a month that starts with the letter A”: Output “Correct” if they enter “April” or “August”, output “Incorrect” otherwise
  3. Prompt the user as follows: “Name a Beatle”. Output “Correct” if they enter “John”, “Paul”, “George” or “Ringo”, output “Incorrect” otherwise
  4. An online whisky shop charges for shipping as follows: One bottle, £5.99; two to five bottles, £7; more than five bottles, free. Prompt the user to enter the number of bottles bought and output the shipping cost.
  5. An online bookshop charges shipping as follows: Orders less than £10, £2.99; orders £10 and over, free; add on £2.50 for all orders if next day delivery is selected. Prompt the user to enter the cost of the order, and then prompt for next day delivery. Output the shipping cost.
  6. Prompt the user to enter a number. Output if the number is odd or even.
  7. Prompt the user to enter a number. Output Fizz if the number is divisible by 3, otherwise just output the number
  8. Extend yesterday’s problem so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5 and otherwise just output the number.
  9. Now extend yesterday’s problem further so that the computer will output Fizz if the number is divisible by 3, output Buzz if the number is divisible by 5, output Fizz Buzz if the number is divisible by both 5 and 3 and otherwise just output the number.

1 – Input and Output Answers

 1) Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
System.out.println("|\to\t|\t \t|\tx\t|");
System.out.println("|\t \t|\tx\t|\to\t|");
System.out.println("|\to\t|\tx\t|\to\t|");

2) Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”

Scanner scan = new Scanner(System.in);
System.out.println("Enter your name");
String name = scan.nextLine();
System.out.println("Hello " + name + ". I hope you're well.");

3) Use Math.sqrt() to print out the square root of 20

System.out.println(Math.sqrt(20));

4) Use Math.sqrt() to print out the square root of 20 to 2 decimal places

double root = Math.round(Math.sqrt(20)*100)/100d;
System.out.println(root);

5) Use Math.random() to print out a random integer between 5 and 10

System.out.println((int)(Math.random()*5)+5);

6) Use Math.pow() to print out 2 to the power of 8

System.out.println(Math.pow(2,8));

7) Prompt the user to enter a (number). Print out “The square root of ” (number) ” is ” (answer)

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num = scan.nextDouble();
System.out.println("The square root of " + num + " is " + Math.sqrt(num));

or

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num = scan.nextDouble();
System.out.format("The square root of %f is %f%n", num, Math.sqrt(num));

8) Prompt the user to enter two numbers. Print out the average of those numbers.

Scanner scan = new Scanner(System.in);
System.out.println("Emter a number");
double num1 = scan.nextDouble();
System.out.println("Enter another number");
double num2 = scan.nextDouble();
double average = (num1 + num2)/2;
System.out.println("The average of " + num1 + " and " + num2 + " is " + average);

9) To work out your BMI, divide your weight in kilograms by your height in metres squared. In other words BMI = w / h*h. Write a program that prompts the user to input their weight and height, and then outputs their BMI.

Scanner scan = new Scanner(System.in);
System.out.println("Emter your weight in kilograms");
double weight = scan.nextDouble();
System.out.println("Enter your height in meters");
double height = scan.nextDouble();
double BMI = weight/(height*height);
System.out.println("Your BMI is " + BMI);

1 Input and Output (Level 1)

Sample Code

 Escape Characters

Escape Sequence Character
\n newline
\t tab
\b backspace
\” double quote
\’ single quote
\\ backslash
\uDDDD Unicode character
public class uni
{
    public static void main (String args [])
    {
        System.out.println("\u0041");
    }
}

Simple Scanner

import java.util.Scanner;
public class Simpscan
{
    public static void main (String args [])
    {
        System.out.println("Enter your name");
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        System.out.println("Hello " + s);
    }
}

System.out.format

double pi = 3.1415;
System.out.format("Pi is %f to 4 d.p.%n", pi);

#+RESULTS

Pi is 3.141500 to 4 d.p.

Exercise

  1. Use the \t escape character to print out a noughts and crosses grid, as shown below in fig. 1
  2. Prompt the user to enter their (name). Print out “Hello” (name) “I hope you’re well”
  3. Use Math.sqrt() to print out the square root of 20
  4. Use Math.sqrt() to print out the square root of 20 to 2 decimal places
  5. Use Math.random() to print out a random integer between 5 and 10
  6. Use Math.pow() to print out 2 to the power of 8
  7. Prompt the user to enter a (number). Print out “The square root of ” (number) ” is ” (answer)
  8. Prompt the user to enter two numbers. Print out the average of those numbers.
  9. To work out your BMI, divide your weight in kilograms by your height in metres squared. In other words BMI = w / h*h. Write a program that prompts the user to input their weight and height, and then outputs their BMI.
Table 1: fig. 1
o x
x o
o x o

The Daily Java

Background

A couple of years ago I started to write the 99 Java Problems based on a loose copy of the Ninety-Nine Lisp Problems, which were themselves translations of Ninety-Nine Prolog Problems. I intended the problems to be a study aid for my students, however it quickly became apparent that many of the problems were too hard. I thus set about working on a more basic set of questions: the Daily Java is the result.

Why the Daily Java?

A few years ago the Maths Department in my school began what they called “The Daily Dose”. 16-18 year old students were required to complete 20 minutes of maths problems a day. This regular practice  proved very successful at raising attainment.
The Daily Java is based on this idea. It consists of a levelled set of questions in an ascending order of difficulty. Students can attempt more than one question a day, particularly at the beginning where the questions are easier, however, it is better to do little and often than to attempt to complete a big block all at once.

A Levelled Approach

The Daily Java questions are levelled. It’s my experience that nearly all students are capable of coding at level 1. Some students need help to progress to subsequent levels.
The following are based on my department’s experience in teaching coding. You may disagree with the levels, you may wish to use them as a starting point for further development, either way, I’d be very interested to hear your opinion.

Level 1

  • Output Strings and numbers
  • Concatenate Strings and numbers
  • Use variables
  • Perform simple arithmetic operations
  • Prompt for user input

Level 2

  • Use if statements with Strings
  • Use if statements with numbers
  • Use if else statements
  • Understand difference between addition and concatenation.

Level 3

  • for, while and do while loops
  • 1D Arrays
  • Concise comments

Level 4

  • Boolean operators AND OR NOT
  • Counts and iterations while loops
  • Nest if statements

Level 5

  • Nest for, while and do while loops
  • Methods and parameters
  • 2D Arrays
  • Variable scope

Level 6

  • Recursion
  • Modular programming
  • Self-documenting code: high level commenting