Object-Oriented Programming with Java, part I – Exercise 68

This program returns true if the number is in the array list more than once.

My Code


import java.util.ArrayList;
import java.util.Scanner;

public class MoreThanOnce {

    public static boolean moreThanOnce(ArrayList<Integer> list, int searched) {
        // write your code here
        int tf = 0;
        for (int num : list) {
            if (num == searched) {
                tf++;
            }
            if (tf == 2) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(3);
        list.add(2);
        list.add(7);
        list.add(2);

        System.out.println("Type a number: ");
        int number = Integer.parseInt(reader.nextLine());
        if (moreThanOnce(list, number)) {
            System.out.println(number + " appears more than once.");
        } else {
            System.out.println(number + " does not appear more than once. ");
        }
    }
}

Model Code

import java.util.ArrayList;

import java.util.Scanner;

 

public class MoreThanOnce {

 

    public static boolean moreThanOnce(ArrayList<Integer> list, int searched) {

        // write your code here

        int howMany = 0;

        for (int numberInList : list) {

            if (numberInList == searched) {

                howMany = howMany + 1;

            }

 

            if (howMany > 1) {

                return true;

            }

        }

        return false;

    }

 

    public static void main(String[] args) {

        Scanner reader = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<Integer>();

        list.add(3);

        list.add(2);

        list.add(7);

        list.add(2);

        

        System.out.println("Type a number: ");

        int number = Integer.parseInt(reader.nextLine());

        if (moreThanOnce(list, number)) {

            System.out.println(number + " appears more than once.");

        } else {

            System.out.println(number + " does not appear more than once. ");

        }

    }

}

 

Comments

🙂 Isn’t it great when you think you’ve missed something but then the model code does it the same way. Although looking back i have made a mistake.

if (tf == 2) {
                return true;
            }

should be….

if (tf > 1) {
                return true;
            }

Otherwise if the number appears three times it would return false.

Leave a comment