Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package class170703;
- public class functions01 {
- // Functions, exercise 01, slide 34
- // input: array of numbers and a digit
- // output: number of appearances of the digit in the array numbers
- // building a data sample: array of integers and a digit.
- // then calling function countAppearances to calculate appearances
- // and print results
- public static void main(String[] args) {
- // create a sample data for testing only
- // array of integers
- int[] numbersArray = { 144, 47, 42, 74, 19 };
- // a digit
- int aDigit = 4;
- // printing a message containing array elements and the digit
- System.out.printf("searching for %d in %s\n", aDigit,
- toString(numbersArray));
- // count and print appearances of the digit in the array values
- System.out.printf("%d appears %d times\n", aDigit,
- countAppearances(numbersArray, aDigit));
- }
- // convert an array of integer numbers to a string
- // input: an array of integer values
- // output: a string with all values from the array separated by comma
- public static String toString(int[] array) {
- // if array is empty
- if (array.length == 0) {
- // return result and quit
- return "[]";
- }
- // building a string from all numbers in the array
- String result = "" + array[0]; // start with the first number
- // scan the numbers in the array without the first
- for (int i = 1; i < array.length; i += 1) {
- // convert number to string and add it to the result string
- result += ", " + array[i];
- }
- // return the result surrounded by brackets
- return "[" + result + "]";
- }
- // count the appearances of a digit in an array of integers
- // input: an array of integer values and a digit
- // output: number of times the digit appears in the values of the array
- public static int countAppearances(int[] numbersArray, int digit) {
- // initialize a counter
- int counter = 0;
- // for each number in the array
- for (int aNumber : numbersArray) {
- // count appearances of digit in it and update counter
- counter += countAppearance(aNumber, digit);
- }
- return counter;
- }
- // count the appearances of a digit in an integer number
- // input:an integer number and a digit
- // output: number of times the given digit appears in the given number
- public static int countAppearance(int number, int digit) {
- // initialize a counter
- int count = 0;
- // loop to scan each digit in the number
- do {
- // update counter by one iff most right digit is equal to digit
- count += number % 10 == digit ? 1 : 0;
- // drop the most right digit
- number /= 10;
- } while (number > 0); // loop while number has more digits to check
- // return the result
- return count;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement