Salesforce Interview Question
Quality Assurance EngineersTeam: Quality Engineering
Country: United States
I want to know how should I handle the case int[] A={}
should I add try/catch block? or return 0 if(A.length==0)
but 0 is not the right ans
o is not the right answer. I'd go with try/catch.
Also, in test cases, one way is equivalence partitioning:
- based on elements of array (number or character or sth...):
A={a, b, c}
A={a, 1, b, c}
...
- based on position of smallest:
A={1, 5, 3}
A={3, 5, 1}
...
- based on number of elements
...
and so on
import java.util.*;
class SmallestNumber{
public static void main(String args[]){
Scanner scan = new Scanner(System.in);
int len = 0;
try{
len = scan.nextInt();
int[] arry = new int[len];
if(len > 0){
for(int i = 0;i<len;i++){
arry[i] = scan.nextInt();
}
for(int j =0;j<len;j++){
System.out.print(arry[j] + "\t");
}
int smalll = arry[0];
int smallr = arry[len-1];
for(int l = 1, r = len-2;l<len/2+1 && r>=l;l++,r--){
if(arry[l] < smalll)
smalll = arry[l];
if(arry[r] < smallr)
smallr = arry[r];
}
if(smalll < smallr)
System.out.println("The smallest is " + smalll);
else
System.out.println("The smallest is " + smallr);
}else{
System.out.println("Number should be +ve and > 0 ");
}
}catch(Exception e){
System.err.println("NumberFormatException");
}
}
}
public class SmallestNumberInArray
{
public static void main(String[] arg)
{
int[] arr = {-1,10,-5,-10};
int len_arr = arr.length;
int smallest_num = arr[0];
for(int i=1; i<len_arr;i++)
{
if(arr[i]<smallest_num)
{
smallest_num=arr[i];
}
}
System.out.println("smallest number is "+smallest_num);
}
}
Code in java
public static int min(int intArray[]){
int min = intArray[0];
for(int current:intArray)
if(current<min)
min=current;
return min;
}
Test data
intArray[] ={5,1,10} --positive no result 1
intArray[] ={-5,-1,-10} --negative no result -10
intArray[] ={5,0,10} --positive no with 0 result 0
intArray[] ={-5,0,-10} --negative no with 0 result -10
intArray[] ={5,-1,10} --positive and -ve no mix result -1
intArray[] ={5,-1,10} --non sorted order in intArray result -1
intArray[] ={-1,5,10} --increasing order no in array result -1
intArray[] ={5,-1,-10} --decreasing order no in array result -10
<pre lang="" line="1" title="CodeMonkey66588" class="run-this">/* The class name doesn't have to be Main, as long as the class is not public. */
- merry September 21, 2011class Main
{
public static int findSmallestInt(int[] A){
int smallest = A[0];
for(int i=0;i<A.length;i++){
if(A[i]<smallest){
smallest=A[i];
}
}
return smallest;
}
public static void main (String[] args) {
int[] array= {1,10,-5,-10};
System.out.print(findSmallestInt(array));
}
</pre><pre title="CodeMonkey66588" input="yes">Test Cases
int[] A = {1,10,-5,-10}
int[] A = {0}
int[] A = {1,10,-5,-10,-11}
int[] A = {1,1,1,1,1}
int[] A = {0,0}
int[] A = {}</pre>