In: Computer Science
1) Design and implement a method to double all elements of an array.
Important: You don’t need to test test method in main(). You don’t need to initialize the array.
pubilc static void doubleElements(int [] arr)
{
}
2) Start with the code below and complete the getInt method. The method should prompt the user to enter an integer. Scan the input the user types. If the input is not an int, throw an IOException; otherwise, return the int. In the main program, invoke the getInt method, use try-catch block to catch the IOException.
import java.util.*;
import java.io.*;
public class ReadInteger
{
pubilc static void main()
{
// your code goes here
}
public static int getInt() throws IOException
{
// your code goes here
}
}
3) Create a class called Car (Car.java).
It should have the following private data members:
• String make
• String model
• int year
Provide the following methods:
• default constructor (set make and model to an empty string, and set year to 0)
• non-default constructor Car(String make, String model, int year)
• getters and setters for the three data members
• method print() prints the Car object’s information, formatted as follows:
Make: Toyota
Model: 4Runner
Year: 2010
public class Car
{
}
4) Complete the following unit test for the class Car described above. Make sure to test each public constructor and each public method, print the expected and actual results.
// Start of the unit test of class Car
public class CarTester
{
public static void main()
{
// Your source codes are placed here
return;
}
}
I will answer the first question here.
What we have to do is just iterate through the array and multiply each element by 2.
Here's the code.
import java.util.*;
import java.lang.*;
import java.io.*;
class Problem
{
public static void main (String[] args){
int[] arr = {3,4,5,6,6};
doubleElements(arr);
System.out.println(Arrays.toString(arr));
}
public static void doubleElements(int[] arr){
for(int i = 0; i < arr.length; i++){
arr[i] = arr[i] * 2;
}
}
}
Here are the screenshots of the code and the output.
Let me know if you have any doubts in the comments.