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;
}

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

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");
}

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

3 – Loops Answers

1) Use a for loop to print the 5 times table up to 12 x 5

for(int i = 1; i<13; i++)
{
    System.out.println(i*5);
}

2) Use a for loop to print the 7 times table up to 12 x 7 in the form “3 x 7 = 21”

for(int i = 1; i<13; i++)
{
    System.out.format("%d x 7 = %d %n",i,i*5);
}

3) Use a for loop to print the following sequence: 0.5, 0.4, 0.3, 0.2, 0.1, 0

for(int i = 5; i>=0; i--)
{
    System.out.println((double)i/10);
}

4) Use a for loop to print the following sequence: 0.03, 0.02, 0.01, 0, -0.01, -0.02, -0.03

for(int i = 3; i>=-3; i--)
{
    System.out.println((double)i/100);
}

5) Use a for loop to print five random numbers between 1 and 10

for(int i = 1; i<11; i++)
{
    System.out.println((int)(Math.random()*5+1));
}

6) Use a for loop to print the first ten square numbers: 1, 4, 9, 16, 25, 36, 49, 64, 81, 100

for(int i = 1; i<11; i++)
{
    System.out.println(i*i);
}

7) Use a for loop to print the first ten triangle numbers: 1, 3, 6, 10, 15, 21, 28, 36,45, 55

int triangle = 0;
for(int i = 1; i<11; i++)
{
    triangle += i;
    System.out.println(triangle);
}

8) Use a while loop to print the numbers from 1 to 10 inclusive

int count = 1;
while (count < 11)
{
    System.out.println(count);
    count++;
}

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

double number = 9;
    while (number > 0)
    {
    System.out.println(number/10);
    number--;
    }
}

10) Use a while loop to print the 4 times table up to 12 x 4.

int count = 1;
while (count < 13)
{
    System.out.println(count*4);
    count++;
}

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… ”

int count = 1;
while (count < 13)
{
    System.out.format("%d x 9 =  %d%n",count,count*9);
    count++;
}

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
(Compare this with the answer to 13)

Scanner scan = new Scanner(System.in);
int total = 0;
int number;
do
{
    System.out.println("Enter a number.  -1 to exit.");
    number = scan.nextInt();
    total+=number;
} while (number != -1);
System.out.println("Total is " + (total+1));

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
(Compare this with the answer to 12)

Scanner scan = new Scanner(System.in);
int total = 0;
int number = 0;
int count = -1;
while(number != -1)
{
    total+=number;
    count++;
    System.out.println("Enter a number, -1 to quit");
    number = scan.nextInt();
}
System.out.println(total + " " + number + " " + count);
double average = (double)total/(double)count;
System.out.println("Average is " + 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.

int primep = 13;
int count = 2;
boolean flag = true;
while (count <11)
{
    if(primep % count == 0) flag = false;
    count++;
}
System.out.println(flag);

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.

Scanner scan = new Scanner(System.in);
    System.out.println("Enter number to be tested");
    int primep = scan.nextInt();
    int count = 2;
    boolean flag = true;
    while (count < Math.sqrt(primep))
    {
    if(primep % count == 0) flag = false;
    count++;
    }
    if(flag)
    {
    System.out.println("Prime");
    }
    else
    {
    System.out.println("Not Prime");
    }

16) Use a while loop to print the sequence 1, -2, 3, -4, 5, -6, 7, -8

int count = 1;
while(count < 9)
{
    System.out.println(-(Math.pow(-1,count)*count));
    count++;
}

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?

int count = 1;
double total = 1;
while(count < 10000)
{
    total = total + ((Math.pow(-1,count)/(2*count + 1)));
    System.out.println(4*total);
    count++;
}

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

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