Tutorial 7 - Answers

Question One

Write a small program that asks user to input the name of a good book that they

read recently, stores the input as elements of a character array in order, then

counts how many 'a' s are there in the input.

Output:

Enter the name of a book that you like: aaa aa ahhhh

There are 6 a's.

import java.io.*;

public class BookRead

{

public static void main (String arg[]) throws IOException

{

System.out.print("Enter the name of a book that you like: ");

BufferedReader stdin = new BufferedReader (

new InputStreamReader (System.in));

String bookName = stdin.readLine();

char[] nameArray = new char[bookName.length()];

int count = 0;

for (int i = 0; i < nameArray.length; i++) {

nameArray[i] = bookName.charAt(i);

if (nameArray[i]=='a')

count++;

}

System.out.println("There are " + count + " a's.");

}//end main

} //end class

Question Two

Write a program that does the following:

a. Initialize an integer array of 10 elements of randomly generated values

from 0 to 99.

b. Find and print out the largest and the smallest values.

c. Interchange the smallest element with the first element of the array.

d. "Rotate" the elements of the array to the right. That is, move the

element one position forward, putting the last element in position 0.

Output:

The array contains 22 16 65 51 91 13 6 70 8 78 (assume this is the array after generating random numbers)

The largest element: 91

The smallest element: 6

The array after changing smallest for first is: 6 16 65 51 91 13 22 70 8 78

The array after rotating one to the right is 78 6 16 65 51 91 13 22 70 8

public class ArrayManipulation

{

public static void main (String arg[])

{

//initialize array

int i;

int [] myNums = new int[10];

int min = 99, max = 0, posMin = 0;

for (i=0; i<10; i++)

myNums[i] = (int) (Math.random() * 100);

//print the Array

System.out.print(“The array contains “);

for (i = 0; i< myNums.length; i++)

System.out.print(myNums [i] + " ");

System.out.println();

//find smallest and largest

for (i=0; i<10; i++) {

if (myNums[i] < min) {

posMin = i;

min = myNums[i];

}

if (myNums[i] > max)

max = myNums[i];

}

System.out.println("The largest element: " + max);

System.out.println("The smallest element: " + min);

//interchange the smallest with the first element

int first = myNums[0];

myNums[0] = myNums[posMin];

myNums[posMin] = first;

//print the array

System.out.print (“The array after changing smallest for first is: “);

for (i = 0; i< myNums.length; i++)

System.out.print(myNums[i] + " ");

System.out.println();

//rotate to the right by one position

int last = myNums[9];

for (i = 9; i > 0; i--)

myNums[i] = myNums[i-1];

myNums[0] = last;

//print the array

System.out.print(“The array after rotating one to the right is “);

for (i = 0; i< myNums.length; i++)

System.out.print(myNums[i] + " ");

System.out.println();

}//end main

}//end class

1