219k views
22 votes
Complete the getOdds method so it returns a new ArrayList of Integers containing all odd Integers from the parameter ArrayList vals in the order they originally appeared. The contents of vals should not change. For example if an ArrayList containing the Integers 2,5,8,6,7,3, 12 in that order is passed as a parameter to getOdds, it should return an ArrayList containing the Integers 5, 7,3 in that order. Write your getOdds method in the U7_L2_Activity Three class. Use the runner class to test your method but do not add a main method to your U7_L2_Activity Three.java file or your code will not be scored correctly.

1 Answer

3 votes

Answer:

Following are the code to this question:

import java.util.*;//import package for user-input

public class U7_L2_Activity Three//defining class U7_L2_Activity Three

{

public static ArrayList<Integer> getOdds(ArrayList<Integer> val)//defining a static method getOdds as an ArrayList

{

ArrayList<Integer> odd = new ArrayList<Integer>();//creating ArrayList Object

int i; //defining integer variable

for(i=0;i<val.size();i++)//defining for loop for calculating odd values

{

if(val.get(i)%2!=0)//defining if block to check odd numbers

{

odd.add(vals.get(i));//add values in odd ArrayList

}

}

return odd;//return ArrayList odd

}

public static void main(String[] asr)//defining main method

{

int l,i;//defining integer variable

Scanner sob = new Scanner(System.in);//creating Scanner calss Object

ArrayList<Integer> num = new ArrayList<Integer>();//creating ArrayList object

System.out.println("Enter length of the ArrayList: ");//print message

l = scan.nextInt();//input length value

System.out.println("Enter ArrayList values: "); //print message

for(i = 0; i < l; i++)//use for to input value

{

num.add(sob.nextInt());//input value

}

System.out.println("Odds list: " + getOdds(num));//calling method getOdds

System.out.println("Original list: " + num);//print array value

}

}

Output:

Enter ArrayList length:

7

Enter values:

2

5

8

6

7

3

12

Odds list: [5, 7, 3]

Original list: [2, 5, 8, 6, 7, 3, 12]

Step-by-step explanation:

In the above-program inside the class, a static method "getOdds "is declared, that accepts an array list in its parameters, and defined an array list "odd", in this a for loop is defined, that check the odd numbers in the array and add the value in the odd Arraylist, and returns its values.

Inside the main method is defined that creates scanner class object for input array value and pass the value into the method "getodds" and print its return values.

User Meerkat
by
5.0k points