Category Archives: Java

7: More Collections: Return to Lisp Problems

These problems were inspired by the 99 Lisp problems. Lisp is a very different language to Java; its use of lists means it’s not appropriate to emulate all the original problems in Java, however, there is some benefit in practising the use of Java collections.

The introduction of lambda functions in Java8 made me rethink how best to approach these problems. There are three things being practised here: collections, generics and lambdas. I’ve split up the questions so that they give a chance to practice these different skills.

1 Last Item

Find the last item in an List of String objects

1.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastItem(myList));
3:  *** Output ***
4: spoon

2 Last Item Generic

Find the last item in a Generic List

2.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: List<Integer> anotherList = new ArrayList<>(asList(1,2,3));
3: System.out.println(gLastItem(myList));
4: System.out.println(gLastItem(anotherList));
5:  *** Output ***
6: spoon
7: 3

3 Last But One

Find the last but one item in a List

3.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(lastButOneItem(myList));
3:  *** Output ***
4: fork

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "fork", "spoon"));
2: System.out.println(printEach(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

5 Eliminate consecutive duplicates from a List

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2: printEach(removeDuplicates(myList));
3:  *** Output ***
4: knife
5: fork
6: spoon

Remembering that a HashSet cannot contain duplicates

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Use this Pair class

 1: class Pair<T>
 2:    {
 3:        int count;
 4:        T value;
 5: 
 6:        Pair(int count, T value) 
 7:        {
 8:        this.count = count;
 9:        this.value = value;
10:        }
11: 
12:        void print()
13:        {
14:        System.out.print("("+ count + ", " + value +") ");
15:        }
16:    } 

7.1 Example

1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
2:  List<Pair> rle = RLE(myList);
3:  for (Pair r: rle)
4:  {
5:      r.print();
6:  }
7:  System.out.println("");
8:  *** Output ***
9: (2, knife) (1, fork) (2, spoon)

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

8.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2:     List<Pair> rle = RLE(myList);
 3:     for (Pair r: rle)
 4:     {
 5:         r.print();
 6:     }
 7:     System.out.println("");
 8: 
 9:     List<Object> decoded = decodeRLE(rle);
10: 
11:     for (Object o: decoded)
12:     {
13:         System.out.println(o);
14:     }
15:  *** Output ***
16: (2, knife) (1, fork) (2, spoon) 
17: knife
18: knife
19: fork
20: spoon
21: spoon

9 Duplicate the elements of a list

9.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(dupli(myList));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: fork
 9: fork
10: spoon
11: spoon
12: spoon
13: spoon

10 Replicate the elements of a list a given number of times

10.1 Example

 1: List<String> myList = new ArrayList<>(asList("knife", "knife", "fork", "spoon","spoon"));
 2: printEach(repli(myList,3));
 3:  *** Output ***
 4: knife
 5: knife
 6: knife
 7: knife
 8: knife
 9: knife
10: fork
11: fork
12: fork
13: spoon
14: spoon
15: spoon
16: spoon
17: spoon
18: spoon

– More Collections: Return to Lisp Problems Solutions

1 Last Item

Find the last item in an List of String objects

1.1 Solution

1: String lastItem(List<String> a)
2: {
3:     return  a.get(a.size()-1);
4: }

2 Last Item Generic

Find the last item in a Generic List

2.1 Solution

1: Object gLastItem(List<?> a)
2: {
3:     return  a.get(a.size()-1);
4: }

3 Last But One

Find the last but one item in a List

3.1 Solution

1: Object lastButOneItem(List<?> a)
2: {
3:     if (a.size() > 1) 
4:  return  a.get(a.size()-2);
5:     else  
6:  return "List too small";
7: }

4 Iterate through the Elements of a List

Iterate through the Elements of a List, printing them out in turn

4.1 Solution

1: void printEach(List<?> a)
2: {
3:     for (Object e: a)
4:     {
5:  System.out.println(e);
6:     }        
7: }

or using a stream

1: void streamPrintEach(List<?> list)
2: {
3:     list
4:  .stream()
5:  .forEach(System.out::println);
6: 
7: }

5 Eliminate consecutive duplicates from a List.

Write a method that removes consecutive duplicates from a List. The order of the elements should not be changed.

5.1 Solution

1: List<?> removeDuplicates(List<?> a)
2: {
3:     for (int i = 0; i<a.size()-1; i++)
4:     {
5:  if(a.get(i) == a.get(i+1)) a.remove(a.get(i));        
6:     }
7:     return a;
8: }

6 Eliminate consecutive duplicates from a List using HashSet

Remembering that a HashSet cannot contain duplicates, repeat the above question using a HashSet

6.1 Solution

1: HashSet<String> hashRemoveDuplicates(List<String> a)
2: {
3:     HashSet<String> hSet = new HashSet<String>(a);
4:     return hSet;
5: }

7 RLE

Run-length encoding of a list. Consecutive duplicates of elements are encoded as pairs where N is the number of duplicates of the element E.

Note this solution uses the Pair class, defined in the question

7.1 Solution

 1: List<Pair> RLE(List<?> list)
 2: {
 3:     List<Pair> encoded = new ArrayList<Pair>();
 4:     for (int i = 0; i < list.size(); i++)
 5:     {
 6:     int runLength = 1;
 7:     while (i < list.size() -1 && list.get(i) == list.get(i+1))
 8:     {
 9:         runLength++;
10:         i++;
11:     }
12: 
13:      Pair<Object> pair = new Pair<Object>(runLength, list.get(i));
14:      encoded.add(pair);
15:     }
16:     return encoded;
17: 
18: }

8 Decode a run-length encoded list

Given a run-length code list generated in a previous problem, construct its uncompressed version.

Note this solution uses the Pair class, defined in the question

8.1 Solution

 1: List<Object> decodeRLE(List<Pair> list)
 2: {
 3: 
 4:     List<Object> decoded = new ArrayList<Object>();
 5:     for (Pair pair: list)
 6:     {
 7:     for (int i =0; i<(int)pair.count; i++)
 8:     {
 9:         decoded.add(pair.value);
10:     }
11:     }
12: 
13:     return decoded;
14: }

9 Duplicate the elements of a list

9.1 Solution

 1: List<String> dupli(List<String> list)
 2: {
 3:     List<String> dup = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     dup.add(s);
 8:     dup.add(s);
 9:     }
10: 
11:     return dup;
12: }

or, using a stream

1: List<String> streamDupli(List<String> list)
2: {
3:     List<String> dupli = list
4:              .stream()
5:              .collect(Collectors.toList());
6: 
7:     return dupli;        
8: 
9: }

10 Replicate the elements of a list a given number of times

10.1 Solution

 1: List<String> repli(List<String> list, int num)
 2: {
 3:     List<String> rep = new ArrayList<String>();
 4: 
 5:     for(String s: list)
 6:     {
 7:     for (int i=0; i<num; i++)
 8:     {
 9:         rep.add(s);
10:     }
11:     }
12: 
13:     return rep;
14: }

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 Answers

1) Write a method that accepts the length and width of a rectangle and returns the perimeter of the rectangle

double Perimeter(double length, double width)
{
    return length*2 + width*2;          
}

2) Write a method that accepts the base and height of a triangle and returns the area of the triangle

double areaTriangle(double base, double height)
{
   return 0.5*base*height;
}

3) Write a method that accepts three integers as paramaters and returns the average of the integers.

double average(int a, int b, int c)
{
    return((a+b+c)/3.0);
}

4) Write a method that accepts an integer array as a parameter and returns the average of the values of that array.

double average(int [] numbers)
{
    double av = 0;
    double total = 0;
    for(int n: numbers)
    {
    total += n;
    }

    return total/numbers.length;
}

5) Write a method that accepts an integer array as a parameter and returns the minium value in that array

double min(int [] numbers)
{
    int minVal = numbers[0];
    for (int n : numbers)
    {
    if (n < minVal) minVal = n; 
    }
    return minVal;
}

or

double min(int [] numbers)
{
    Arrays.sort(numbers);
    return numbers[0];
}

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)

double hypotenuse(double a, double b)
{
    return Math.sqrt(a*a + b*b);
}

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

double scalarProduct(int [] u, int [] v) throws Exception
{
    if (u.length != v.length) throw new Exception();
    double product = 0;
    for(int i = 0; i<u.length; i++)
    {
    product += u[i]*v[i];
    }
    return product;
}

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.

double [] vectorSum(int [] u, int [] v) throws Exception
{
    if (u.length != v.length) throw new Exception();
    double [] sum = new double[u.length];

    for(int i = 0; i<u.length; i++)
    {
    sum[i] = u[i] + v[i];
    }
    return sum;
}

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.

double [] eDistance(int [] u, int [] v) throws Exception
{
  if (u.length != v.length) throw new Exception();
  double [] sum = new double[u.length];
  double dist = 0;
  for(int i = 0; i<u.length; i++)
  {
       dist += Math.pow((u[i]-v[i]),2);
  }
  return sum;

}

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 Answers

1) Print out the following shapes: \/ \/\/ \/\/\/ \/\/\/\/ \/\/\/\/\/

for (int i = 1; i<6; i++)
{
    for(int j = 0; j<i; j++)
    {
    System.out.print("\\/");
    }
    System.out.print(" ");            
}

2) Print out the following 54321,4321,321,21,1

for (int i = 5; i>0; i--)
{
    for(int j =i; j>0; j--)
    {
    System.out.print(j);
    }
    System.out.print(" ");            
}

3) Print out the following shapes */ */ */ */ *****/

for (int i = 1; i<6; i++)
{
    System.out.print("\\");
    for(int j = 0; j<i; j++)
    {
    System.out.print("*");
    }
    System.out.println("/");            
}

4) Print out a 10 x 10 table square

for (int i = 1; i<11; i++)
{
    for(int j = 1; j<11; j++)
    {
    System.out.print("\t"+ i*j + "\t |");
    }
    System.out.println();            
}

5) Print out the following shapes \/ \// \\/// \\//// \\\/////

String seed = "";
for (int i = 1; i<6; i++)
{
    seed = "\\" + seed + "/";
    System.out.print(seed + " ");
}

6) Print out an 8 x 8 chessboard. Use * for black and – for white

boolean isBlack = true;
for (int i = 1; i<9; i++)
{
    for(int j = 1; j<9; j++)
    {
    System.out.print(isBlack ? "*" : "-");
    isBlack = !isBlack;
    }
    isBlack=!isBlack;
    System.out.println();            
}

7) Print out the following shapes:

*

**
**

***
***
***

****
****
****
****

*****
*****
*****
*****
*****
String stars = "";
for (int i = 1; i<6; i++)
{
    stars = stars + "*";
    for(int j = 0; j<i; j++)
    {
    System.out.println(stars);
    }
    System.out.println();            
}

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 Answers

1) Output the length of the String “I never saw a purple cow”

String s = "I never saw a purple cow";
System.out.println(s.length());

2) Convert the String “I never saw a purple cow” to uppercase and output the resulting string.

String s = "I never saw a purple cow";
String u = s.toUpperCase();
System.out.println(u);

3) Output the String “I never saw a purple cow” as separate words.

String s = "I never saw a purple cow";
String [] words = s.split("\\s+");
for(String w:words)
{
    System.out.println(w);
}

4) Output the following String array as one String: words [] = {“Calling”, “occupants”, “of”, “interplanetary”, “craft”};

String s = "";
String [] words = {"Calling", "occupants", "of", "interplanetary", "craft"};
for(String w:words)
{
    s = s + w + " ";
}
System.out.println(s);

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

boolean isUpper = true;
Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = scan.nextLine();

String [] words = s.split("\\s+");
String sentence = "";
for(String word: words)
{
    if(isUpper)
    {
    sentence = sentence + word.toUpperCase() + " ";
    }
    else
    {
    sentence = sentence + word.toLowerCase() + " ";
    }
    isUpper = !isUpper;
}

System.out.println(sentence);

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”

Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = scan.nextLine();

String [] words = s.split("\\s+");
String acronym = "";
for(String word: words)
{
    acronym = acronym + word.substring(0,1).toUpperCase();            
}

System.out.println(acronym);

7) Prompt the user to enter a string. Output the number of times the letter ‘e’ appears in the string.

Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = scan.nextLine();

int count = 0;
for(int i = 0; i < s.length(); i++)
{
    if(s.charAt(i) == 'e') count++;
}

System.out.println("Number of times e appears: " + count);

8) Prompt the user to enter a string. Output the number of vowels in the String.

Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = scan.nextLine();

int count = 0;
for(int i = 0; i < s.length(); i++)
{
    if(s.substring(i,i+1).matches("[aeiouAEIOU]")) count++;
}

System.out.println("Number of times vowel appears: " + count);

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”

Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = scan.nextLine();

System.out.println(s.replaceAll("[AEIOUaeiou]", "*"));

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.

Scanner scan = new Scanner(System.in);
System.out.println("Enter a sentence");
String s = scan.nextLine();

String reverse= "";
for (int i = 0; i<s.length(); i++)
{
    reverse = s.substring(i,i+1) + reverse;
}

if (s.equals(reverse))
{
    System.out.println("Palindrome");
}
else
{
    System.out.println("Not Palindrome");
}

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 Answers

1) Print out the elements of the following array: int [] numbers = {1,2,3,4,5};

int [] numbers = {1,2,3,4,5}; 
for (int i = 0; i < numbers.length; i++) 
{ 
    System.out.println(numbers[i]); 
} 
// OR for(int element : numbers) { System.out.println(element); }

2) Declare and initialize a String array containing the days of the week. Print out a random day.

String [] days = {  "Monday", "Tuesday", "Wednesday", "Thursday",
            "Friday", "Saturday",  "Sunday" };

int random = (int)(Math.random()*days.length);
System.out.println(days[random]);

3) Output the sum of the elements in this array int [] values = {3,5,4,7,2,3};

int [] values = {3,5,4,7,2,3};
int sum =0;
for(int i = 0; i < values.length; i++)
{
    sum+=values[i];
}
System.out.println(sum);

//OR if you have Java 8...

sum = IntStream.of(values).sum();
System.out.println(sum);

4) Output the average of the elements in this array int [] values = {3,4,5,6};

int [] values = {3,4,5,6};
int sum =0;
for(int i = 0; i < values.length; i++)
{
    sum+=values[i];
}
System.out.println((double)sum/(values.length));

//OR if you have Java 8...

double average = IntStream.of(values).average().getAsDouble();
System.out.println(average);

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.

int [] numbers = new int[5];
Scanner scan = new Scanner(System.in);
for (int i = 0; i<numbers.length;i++)
{
    System.out.println("Enter a number");
    int n = scan.nextInt();
    numbers [i] = n;
}
System.out.println("... and your numbers are... ");
for (int i =0; i<numbers.length; i++)
{
    System.out.println(numbers[i]);
}

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

int [] numbers = new int[4];
Scanner scan = new Scanner(System.in);
for (int i = 0; i<numbers.length;i++)
{
    System.out.println("Enter a number");
    int n = scan.nextInt();
    numbers [i] = n;
}

int sum =0;
for (int i =0; i<numbers.length; i++)
{
    sum += numbers[i];
}
System.out.println("Average: " + (double)sum/numbers.length);

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

String s = "This is a string";
char [] c = s.toCharArray();

for(char e: c)
{
    System.out.print(e+",");
}
System.out.println("");

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”

String s = "I never saw a purple cow";
char [] c = s.toCharArray();
int count = 0;
for(char e: c)
{
    if (e == 'e') count++;
}
System.out.println("Number of e's: "+ count);