Advertisement
cgorrillaha

Untitled

Jan 6th, 2022
787
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class NumberGroup {
  4.     private int[] nums;
  5.  
  6.     public NumberGroup(int[] nums){
  7.         this.nums=nums;
  8.     }
  9.  
  10.     public int[] getNums() {
  11.         return nums;
  12.     }
  13.  
  14.     public void setNums(int[] nums) {
  15.         this.nums = nums;
  16.     }
  17.  
  18.     /**
  19.      * print all elements in nums array in the following format:
  20.      * [element1, element2, element3, element4, . . . last element]
  21.      * */
  22.     public void printNums(){
  23.         //write a loop that will access each item in the list
  24.         //each iteration of the loop should print one item in the list
  25.         System.out.print("["+nums[0]);
  26.         for (int i=1; i<nums.length;i++){
  27.             System.out.print(", "+nums[i]);
  28.         }
  29.         System.out.println("]");
  30.  
  31.     }
  32.  
  33.     /**
  34.      * find and return the index of the target number in nums array
  35.      * If target is not found, return -1
  36.      * @param -1 < target < nums.length
  37.      * @return index of the target element or -1 if target not found in nums
  38.      * */
  39.     public int findTargetNumber(int target){
  40.         int count=0;
  41.         int found=-1;
  42.         while(found<0&&count<nums.length){
  43.             if(nums[count]==target){
  44.                 found=count;
  45.             }
  46.         }
  47.         return found;
  48.     }
  49.     /**
  50.      * @return the count of even numbers stored in nums
  51.      * */
  52.     public int countEven(){
  53.         //make a counter
  54.         int count=0;
  55.         //traversal loop from 0 to length-1
  56.         for(int i=0; i<nums.length; i++){
  57.             if(nums[i]%2==0){
  58.                 count++;
  59.             }
  60.         }
  61.         return count;
  62.     }
  63.  
  64.     @Override
  65.     public String toString() {
  66.         return "NumberGroup{" +
  67.                 "nums=" + Arrays.toString(nums) +
  68.                 '}';
  69.     }
  70.  
  71.  
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement