1. The following code uses two arrays, one to store products and the other to st
ID: 3757959 • Letter: 1
Question
1. The following code uses two arrays, one to store products and the other to store product ID's (a better organization would be to use a singe array of a class or struct, but that is not the subject of this Programming Project). The function getProductID takes as input the two arrays, the length of the arrays, and a target product to search for. It then loops through the product name array and if a match is found it returns the corresponding product ID:
int getProductID(int ids[], string names[], int numProducts, string target)
{
for (int i=0; i < numProducts; i++)
{
if (names[i] == target)
return ids[i];
}
return -1; // not found
}
int main() // Sample code to test the getProductID function
{
int productIds[]= {4, 5, 8, 10, 13};
string products[] = { "computer", "flash drive", "mouse", "printer", "camera" };
cout << getProductID(productIds, products, 5, "mouse") << endl;
cout << getProductID(productIds, products, 5, "camera") << endl;
cout << getProductID(productIds, products, 5, "laptop") << endl;
return 0;
}
One problem with this implementation of the getProductID() function is that it returns the special error code of -1 if the target name is not found. The caller later might actually want to have -1 as a valid product ID number. Revise the program so that it throws an appropriate exception when a product is not found instead of returning -1. Please define an exception classException_ID_Not_Found as a derived class of the standard exception class exception. (See the example code on iLearn for exception subclassing.) Then modify the getProductID()function to throw Exception_ID_Not_Found instead of returning -1. Finally, test this type of exceptions properly in the main() function using a try-catch statement.
You are not required to use separate compilation for this problem.
Explanation / Answer
class classException_ID_Not_Found
{
String str1;
classException_ID_Not_Found(String str2)
{
str1=str2;
}
public String toString(){
return ("Output String = "+str1) ;
}
};
int getProductID(int ids[], string names[], int numProducts, string target)
{
for (int i=0; i < numProducts; i++)
{
if (names[i] == target)
return ids[i];
}
else
try
{
throw new classException_ID_Not_Found("Not Found");
}
catch(MyException exp){
System.out.println("Hi this is my catch block") ;
System.out.println(exp) ;
}
}
int main() // Sample code to test the getProductID function
{
int productIds[]= {4, 5, 8, 10, 13};
string products[] = { "computer", "flash drive", "mouse", "printer", "camera" };
cout << getProductID(productIds, products, 5, "mouse") << endl;
cout << getProductID(productIds, products, 5, "camera") << endl;
cout << getProductID(productIds, products, 5, "laptop") << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.