How do I write a test code for this? Also, I need to add one extra method for ma
ID: 3768502 • Letter: H
Question
How do I write a test code for this? Also, I need to add one extra method for manipulating an int array. public class IAM { public static void rotateDown( int[] a ) { int temp = a[a.length-1]; for( int i=a.length-2; i >= 0; i-- ) { a[i+1] = a[i]; } a[0] = temp; } public static void print( int[] a ) { for( int i=0; i < a.length; i++ ) { System.out.print( a[i] + " " ); } System.out.println(); // move cursor to new line } public static int search( int[] a, int n ) { int rv=-1; // not found return value int i=0; // array index boolean found=false; while( i < a.length && !found) { if ( a[i] == n ) { found=true; rv=i; } i++; }// while return rv; }// method }
Explanation / Answer
import java.util.Scanner;
import java.util.Scanner;
public class IAM
{
public static final int MAX = 10;
public static Scanner input = new Scanner(System.in);
public static void rotateDown( int[] a )
{
int temp = a[a.length-1];
for( int i=a.length-2; i >= 0; i-- )
{
a[i+1] = a[i];
}
a[0] = temp;
}
public static void print( int[] a )
{
for( int i=0; i < a.length; i++ )
{
System.out.print( a[i] + " " );
}
System.out.println(); // move cursor to new line
}
public static int search( int[] a, int n )
{
int rv=-1; // not found return value
int i=0; // array index
boolean found=false;
while( i < a.length && !found)
{
if ( a[i] == n )
{
found=true;
rv=i;
}
i++;
}// while
return rv;
}// method
static int manipulatingArray(int array[],int len) // new method for manipulating int array
{
int count=0;
System.out.println("Enter "+len+" positive integers");
System.out.println("Enter -1 to exit");
int i=input.nextInt();
while(i!=-1)
{
array[count]=i;
count++;
i=input.nextInt();
}
return count;
}
public static void main(String[] args) // test code
{
System.out.println("Enter array length");
int len=input.nextInt();
int array[]=new int[len];
int elements=manipulatingArray(array,len);
System.out.println("Enter element to search");
int num=input.nextInt();
if(search(array,num)!=-1)
System.out.println("Element found at "+search(array,num)+" index");
else
System.out.println("Element not found");
rotateDown(array);
System.out.println("Array after Rotate Down");
print(array);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.