8 – Strings and Characters

Sample Code

 String, char, int

public class StrAsc
{
    public static void main (String args [])
    {
        String s = "A String";
        System.out.println("The character at index 2 is " + s.charAt(2));
        System.out.println("The ASCII equivalent is " + (int)s.charAt(2));
    }
}

Exercises

  1. Convert the following string to its ASCII values: “I never saw a purple cow”
  2. If a = 1, b=2, c=3… convert the following String to its equivalent character codes: “DailyJava”
  3. ROT13 (“rotate by 13 places”, sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the letter 13 letters after it in the alphabet. ROT13 is an example of the Caesar cipher, developed in ancient Rome. Write a program that will accept a String as input then output that string under a ROT13 transformation, so input of HELLO will result in output of URYYB
  4. Write a ROT-N cipher, similar to a ROT13 cipher, where a string and a shift are input, and a string is outputted with the characters shifted by N, so if the input is “DAD” and 1, the output is “EBE”
  5. Write a program that uses ASCII values to convert lowercase characters to uppercase, so input of “this” will result in output of “THIS”. DO NOT use library methods such as toUpperCase()
  6. There are 62 Alphanumeric Characters: [A-Za-z0-9]. Any other character, such as %,(): is non-alphanumeric. There are also a number of control or non-printing characters. These include Line Feed, Carriage Return and Tab. Write a program that imports a text file and prints the number of alphanumeric characters it contains.
  7. Write a program that accepts a string cipher as an input and ouputs a string plaintext containing every second letter from input. Test your program using the input “Knives” and “Forks”. You should get the output “nvs” and “ok” respectively

7 – Methods (Level 5)

Sample Code

public class  Meth
{
    final double PI = 3.1415;
    Meth()
    {
    int r = 4;
    System.out.println("The Area of a circle radius " + r + " is " + area(r));
    System.out.println("The Circumference of a circle radius " + r + " is " + circumference(r));
    }
    double area(int r)
    {
    return PI*r*r;
    }
    double circumference(int r)
    {
    return 2*PI*r;
    }
    public static void main (String args [])
    {
    new Meth();
    }
}

Exercises

  1. Write a method that accepts the length and width of a rectangle and returns the perimeter of the rectangle
  2. Write a method that accepts the base and height of a triangle and returns the area of the triangle
  3. Write a method that accepts three integers as paramaters and returns the average of the integers.
  4. Write a method that accepts an integer array as a parameter and returns the average of the values of that array.
  5. Write a method that accepts an integer array as a parameter and returns the minium value in that array
  6. Write a method that returns the hypotenuse of a triangle when the other two sides are int a and int b. (Remember: hypotenuse squared equals a squared plus b squared)
  7. The scalar product of u=(u1,u2,u3) and v=(v1,v2,v3) is defined to be u1v1+u2v2+u3v3. Write a method that accepts two int arrays as parameters and returns an int representing the scalar product of those two arrays
  8. If A = (a1,a2, …an) and B = (b1,b2, …bn) then the vector sum of the two arrays A + B = (a1+b1, a2+b2, … , an+bn). Write a method that accepts two arrays as parameters and returns an array representing the vector sum of those two arrays.
  9. The Euclidean distance between two points A = (a1,a2, …an) and B = (b1,b2, …bn) is defined as sqrt((a1-b1)2 + (a2-b2)2 +… + (an-bn)2). Write a method that accepts two int arrays representing A and B as parameters and returns a double representing the Euclidean distance between them.

6 – Nesting (Level 5)

Sample Code

 Squares

public class Triangle
{
    public static void main (String args [])
    {
        for(int i=0;i<5;i++)
        {
            for (int j = 0; j<i; j++)
                   {
                   System.out.print("*");
                   }
            System.out.println("");
        }
    }
}

Table Square

public class nest1
{
    public static void main (String args [])
    {
        for(int i = 1; i<4; i++)
        {
        for(int j = 1; j<4; j++)
        {
            System.out.println(i + " x " + j + " = " + i*j );
        }
        }
    }
}

Exercise

  1. Print out the following shapes: \/ \/\/ \/\/\/ \/\/\/\/ \/\/\/\/\/
  2. Print out the following 54321 4321 321 21 1
  3. Print out the following shapes \*/ \**/ \***/ \****/ \*****/
  4. Print out a 10 x 10 table square
  5. Print out the following shapes \/ \\// \\\/// \\\\//// \\\\\/////
  6. Print out an 8 x 8 chessboard. Use * for black and – for white
  7. Print out the following shapes:
*
**
**
***
***
***
****
****
****
****
*****
*****
*****
*****
*****

5 – String Problems

1 Sample Code

public class StrSamples
{
    public static void main (String args [])
    {
       String s ="This is a sample string";
       System.out.println(s);
       System.out.println("It contains this many characters (counting spaces): "+ s.length());
       System.out.println("Here it is split up by whitespace:");
       String [] seperated= s.split("\\s+");
       for(int i=0; i<seperated.length; i++)
       {
           System.out.println(seperated[i]);
       }
       System.out.println("Here it is split up by the letter a:");
       String [] sep2= s.split("a");
       for(int i=0; i<sep2.length; i++)
       {
           System.out.println(sep2[i]);
       }
       System.out.println("Here are the characters from position 1 to 3:");
       System.out.println(s.substring(1,3));
       System.out.println("Here it is with the spaces removed");
       String r= s.replaceAll("\\s", "");
       System.out.println(r);
       System.out.println("Here it is with the letter s replaced by sausage");
       r= s.replaceAll("s", "sausage");
       System.out.println(r);
       System.out.println("Here it is with the lower case letters turned to *s");
       r= s.replaceAll("[a-z]", "*");
       System.out.println(r);
    }
}

2 Exercises

  1. Output the length of the String “I never saw a purple cow”
  2. Convert the String “I never saw a purple cow” to uppercase and output the resulting string.
  3. Output the String “I never saw a purple cow” as separate words.
  4. Output the following String array as one String: words [] = {“Calling”, “occupants”, “of”, “interplanetary”, “craft”};
  5. Prompt the user to enter a string. Output the string as separate words in alternate upper and lower case: SO it LOOKS like THIS example
  6. Prompt the user to enter a String. Output a String named acronym that contains the initial letters of the words input. Example: input “British Broadcasting Corporation” output “BBC”
  7. Prompt the user to enter a string. Output the number of times the letter ‘e’ appears in the string.
  8. Prompt the user to enter a string. Output the number of vowels in the String.
  9. Prompt the user to enter a String. Output a String with the vowels replaced with *’s. Example: input “I never saw a purple cow” output “* n*v*r s*w * p*rpl* c*w”
  10. A palindrome is a string that reads the same forwards and backwards. Examples are “radar” and “rotavator”. Write a program that accepts a String as input and outputs “Palindrome” if the String is a palindrome, and “Not Palindrome” otherwise.

4 – Arrays (Level 3)

1 Sample Code

2 Exercises

  1. Print out the elements of the following array: int [] numbers = {1,2,3,4,5};
  2. Declare and initialize a String array containing the days of the week. Print out a random day.
  3. Output the sum of the elements in this array: int [] values = {3,5,4,7,2,3};
  4. Output the average of the elements in this array: int [] values = {3,4,5,6};
  5. Declare an int array of length 5. Use a for loop to prompt for 5 numbers and enter them into the array. Print out the array.
  6. Declare an int array of length 4. Use a for loop to prompt for 4 numbers and enter them into the array. Print out the average of the four numbers
  7. The following code will convert a String s to an array of characters c. Print out the characters: String s = “This is a string”; char [] c = s.toCharArray();
  8. Use what you learned in the last question to count the number of times the letter e occurs in the String “I never saw a purple cow”

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 (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 (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