Return a string from void - java

hello I have this programming assignment where I have to use the functions they gave us, as they give it to us to use, the problem i am encountering is the fact this has to be void and I am not allowed to use System.out.println(); either so my question is how to i return the exception without changing the method header or it using System.out.println();?
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
System.out.println("ITEM " + itemID + " DOES NOT EXIST!");
}
}

In your catch block do this:
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException("ITEM " + itemID + " DOES NOT EXIST!");
}
You don't need to add a throw declaration to your method, since IndexOutOfBoundsException is a RuntimeException.
Where ever you call the function you can add a catch block to read the error message like this:
catch (IndexOutOfBoundsException ex) {
System.out.println(ex.getMessage());
}

Well, if the method is used incorrectly (without validation of the index), maybe it should throw an exception?
You can remove the try-catch block completely. IndexOutOfBoundsException is a runtime exception, so it does not require the throws IndexOutOfBoundsException syntax.
However, if you want the exception to be less cryptic, you can wrap it with your own RuntimeException:
public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new RuntimeException("Invalid item ID: " + itemID, e);
}
}

You can change your method signature and throw an exception
public void deleteItem(String itemID) throws Exception{
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}catch (IndexOutOfBoundsException e) {
Exception ex = new Exception("ITEM " + itemID + " DOES NOT EXIST!");
throw ex;
}
}
Once done you can get your error message like this
try{
xxx.deleteItem("your itemID");
}catch(Exception e){
// You will read your "ITEM " + itemID + " DOES NOT EXIST!" here
String yourErrorMessage = e.getMessage();
}

public void deleteItem(String itemID){
try {
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
catch (IndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException( "ITEM " + itemID + " DOES NOT EXIST!");
}
}
public void deleteItem(String itemID)throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
You cant return exceptions . Exceptions are thrown from the methods , you can use keyword throw for that.try above methods to throw exceptions from methods

Remove try..catch block and modify your function as
public void deleteItem(String itemID) throws IndexOutOfBoundsException{
index = Change.indexOf(itemID);
StockItems.remove(index);
Change.remove(index);
}
Add try catch where you call this method and use System.out.println("ITEM " + itemID + " DOES NOT EXIST!"); there.
Ya even if you do not add throws to this method but put call of deleteItem in try catch block will work.

Related

How do I display the updated element information when there is more than one element in the arrayList?

I have a program to update vehicle inventory. I call the updateVehicle()...it should loop through the arrayList of vehicles to look for a match based on what the user input. In the if statement, if a match is found, update the vehicle in the arrayList with what the user input, call the displayCurrentVehicleEntry() and display the updated details to console. The code works and will update the vehicle.
However, if there is more than one vehicle in the arrayList, it will update it correctly, but not display the details of the updated vehicle (it displays the info for the last element in the arrayList).
In the displayCurrentVehicleEntry() it will grab the last element and display the details, which works correctly for the addVehicle().
I'm not sure how to get that to work for the updateVehicle().
public void updateVehicle(String makeCurrent, String modelCurrent, String colorCurrent, int yearCurrent, int mileageCurrent,
String makeUpdated, String modelUpdated, String colorUpdated, int yearUpdated, int mileageUpdated) {
try {
boolean found = false;
for (int i = 0; i < listOfVehicles.size(); i++) {
AutoInv vehicle = listOfVehicles.get(i);
if (vehicle.getMake().equalsIgnoreCase(makeCurrent)
&& vehicle.getModel().equalsIgnoreCase(modelCurrent)
&& vehicle.getColor().equalsIgnoreCase(colorCurrent)
&& vehicle.getYear() == yearCurrent
&& vehicle.getMileage() == mileageCurrent) {
vehicle.setMake(makeUpdated);
vehicle.setModel(modelUpdated);
vehicle.setColor(colorUpdated);
vehicle.setYear(yearUpdated);
vehicle.setMileage(mileageUpdated);
System.out.println("\nVehicle updated successfully!\n");
displayCurrentVehicleEntry(); //FIXME not working rethink
found = true;
}
}
if (!found) {
System.out.println("\nVehicle not found in inventory!");
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Failure");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void displayCurrentVehicleEntry() {
try {
AutoInv vehicle = listOfVehicles.get(listOfVehicles.size() - 1);
System.out.println("Make: " + vehicle.getMake().toUpperCase());
System.out.println("Model: " + vehicle.getModel().toUpperCase());
System.out.println("Color: " + vehicle.getColor().toUpperCase());
System.out.println("Year: " + vehicle.getYear());
System.out.println("Mileage: " + vehicle.getMileage());
System.out.println("");
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Failure");
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public void addVehicle(AutoInv vehicle) throws Exception{
try {
if (listOfVehicles.add(vehicle)) {
System.out.println("\nFollowing vehicle added successfully:\n");
displayCurrentVehicleEntry();
}
else {
throw new Exception("\nFailed to add vehicle.");
}
} catch (Exception e) {
System.out.println(e.getMessage());
// e.printStackTrace();
}
}
Modify the displayCurrentVehicleEntry() method, add a parameter to displayCurrentVehicleEntry() like this displayCurrentVehicleEntry(int index), and change AutoInv vehicle = listOfVehicles.get(listOfVehicles.size() - 1); to AutoInv vehicle = listOfVehicles.get(index);
in addVehicle, you can use displayCurrentVehicleEntry(listOfVehicles.size() - 1); and in updateVehicle you can use displayCurrentVehicleEntry(i); to select the vehicle you want to print

why am i getting "Unhandled exception" below? [duplicate]

This question already has answers here:
Java 8: How do I work with exception throwing methods in streams?
(7 answers)
Closed 2 years ago.
public int deleteMultipleEntries(String[] idArray) throws Exception {
int result = dao.deleteMultipleEntries(idArray);
cache.invalidateAll(Arrays.stream(idArray).collect(Collectors.toList()));
if (result != idArray.length) {
Arrays.stream(idArray).forEach(s -> {
try {
cache.get(s);// this method throws ExecutionException if entry with id s not found
log.error("id:" + s + " was not deleted");
log.info("Deleting entry id:"+Integer.valueOf(s));
dao.deleteEntry(Integer.valueOf(s));//getting unhandled exception: java.lang.Exception error in IDE
} catch (ExecutionException e) {
log.info("id:" + s + " is deleted or it never existed");
}
});
}
return result;
}
public int deleteEntry(Integer primaryKey) {
String deleteSql = String.format(getDeleteSql(), primaryKey);
if (log.isDebugEnabled())
log.debug("Deleting Entry with Key: {}", primaryKey);
int affectedRows = getJdbcTemplate().update(deleteSql);
if (log.isDebugEnabled())
log.debug("Updated {} Rows", affectedRows);
return affectedRows;
}
Getting error at this statement dao.deleteEntry(Integer.valueOf(s));
if an exception occurs while executing dao.deleteEntry(Integer.valueOf(s)); the catch block cannot catch the exception since it catches ""ExecutionException" specifically, Hence the function itself should throw exception automatically since its signature has throws statement.
the try catch block i have written is for handling logic handling, if i write the same statement outside the try catch, it doesn't give any error. I want to understand the behavior here. please kindly help
Thats because you are in Arrays.stream(idArray).forEach(...)
Change this to normal foreach and it would work.
public int deleteMultipleEntries(String[] idArray) throws Exception {
int result = dao.deleteMultipleEntries(idArray);
cache.invalidateAll(Arrays.stream(idArray).collect(Collectors.toList()));
if (result != idArray.length) {
for(String s: idArray) {
try {
cache.get(s);// this method throws ExecutionException if entry with id s not found
log.error("id:" + s + " was not deleted");
log.info("Deleting entry id:"+Integer.valueOf(s));
dao.deleteEntry(Integer.valueOf(s));//getting unhandled exception: java.lang.Exception error in IDE
} catch (ExecutionException e) {
log.info("id:" + s + " is deleted or it never existed");
}
}
}
return result;
}

Create an instance of a class and initialize all its fields

I want to create an instance of a class, but I also need to initialize also all its fields recursively.
The code you see related do the objectFactory is because some of this classes could be JAXB classes, so for every package there is an ObjectFactory with methods like createJaxbObject(....).
EDITED:
My final solutions is this one:
public Object getInstance(Class<?> instanceClass, Boolean simple,
String jaxbName) {
Object instance = null;
try {
if (instanceClass.isPrimitive())
return primitiveValues.get(instanceClass.getName());
if (List.class.isAssignableFrom(instanceClass))
return new ArrayList();
else if (instanceClass.isEnum())
return instanceClass.getEnumConstants()[0];
else if (instanceClass.isArray())
return java.lang.reflect.Array.newInstance(instanceClass, 1);
else if (BigInteger.class.isAssignableFrom(instanceClass))
return new BigInteger("0");
else if (instanceClass.equals(String.class))
return "";
else if (instanceClass.equals(Boolean.class))
return false;
else if (instanceClass.equals(EntityObjectStringType.class))
return new EntityObjectStringType();
else if (JAXBElement.class.isAssignableFrom(instanceClass)) {
try {
Method m = null;
Class<?> objFactoryClass = null;
Iterator<String> it = EditorServlet.objectFactories
.iterator();
Object of = null;
while (it.hasNext()) {
objFactoryClass = Class.forName(it.next());
of = objFactoryClass.getConstructor().newInstance();
m = getMethodFromObjectFactory(objFactoryClass,
jaxbName);
if (m != null)
if (m.getParameterTypes().length > 0)
break;
}
Object jaxbElement = getInstance(m.getParameterTypes()[0],
m.getParameterTypes()[0].getSimpleName());
return m.invoke(of, jaxbElement);
} catch (NoSuchMethodException e) {
logger.error("JAXB NoSuchMethodException");
}
} else
try {
logger.info("Costruttori per " + instanceClass.getName()
+ " " + instanceClass.getConstructors().length);
instance = instanceClass.getConstructor().newInstance();
} catch (NoSuchMethodException noSuchMethodException) {
logger.error("getConstructors NoSuchMethodException");
}
} catch (IllegalArgumentException e) {
logger.error("IllegalArgumentException " + instanceClass.getName());
} catch (SecurityException e) {
logger.error("SecurityException " + instanceClass.getName());
} catch (InstantiationException e) {
logger.error("InstantiationException " + instanceClass.getName()
+ " " + instanceClass.isPrimitive());
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException " + instanceClass.getName());
} catch (InvocationTargetException e) {
logger.error("InvocationTargetException " + instanceClass.getName());
} catch (ClassNotFoundException e) {
logger.error("ClassNotFoundException " + instanceClass.getName());
}
if (!simple) {
for (Field field : instanceClass.getDeclaredFields()) {
try {
Object fieldInstance = getInstance(field.getType(),
field.getName());
field.setAccessible(true);
field.set(instance, fieldInstance);
} catch (IllegalArgumentException e) {
logger.error("IllegalArgumentException "
+ instanceClass.getName());
} catch (IllegalAccessException e) {
logger.error("IllegalAccessException "
+ instanceClass.getName());
}
}
}
return instance;
}
If I could hazard a guess, you're calling your method recursively in your NoSuchMethodException catch.
Object of = getInstance(objFactoryClass);
If your recursive call keeps on not finding the method on:
Method m = getMethodFromObjectFactory(objFactoryClass, c);
... the method will call itself again, which should end with a StackOverflowError at some point.
Your recursion has no break point
Try to stop recursion where the class is primary type:
if (List.class.isAssignableFrom(c))
instance = new ArrayList();
else if (c.isEnum())
return c.getEnumConstants()[0]; //avoid stackoverflow error
else if(c.isPrimitive()) {
instance = c.getConstructor().newInstance();
// use must stop here
return instance;
} else{
instance = c.getConstructor().newInstance();
}
The isPrimitive will judge whether the class is primary type(int ,Integer,shor,Short,String...)

Determine if a Method is a `RemotableViewMethod`

I am building a Widget which contains a ProgressBar. If the Widget is computing I set the visibility of that ProgressBar to VISIBLE, and to INVISIBILE if all computings stopped. There should be no Problem, because the setVisibility is documented as RemotableViewMethod. However some guys at HTC seem to forget it, (i.e on the Wildfire S), so a call to RemoteViews.setVisibility will result in a crash. For this reason I try to implement a check, if setVisibility is really callable. I have writen this Method for it:
private boolean canShowProgress(){
LogCat.d(TAG, "canShowProgress");
Class<ProgressBar> barclz = ProgressBar.class;
try {
Method method = barclz.getMethod("setVisibility", new Class[]{int.class});
Annotation[] anot = method.getDeclaredAnnotations();
return anot.length > 0;
} catch (SecurityException e) {
LogCat.stackTrace(TAG, e);
} catch (NoSuchMethodException e) {
LogCat.stackTrace(TAG, e);
}
return false;
}
This will work, but is REALLY ugly as it will return `True´ if ANY Annotiation is present. I looked, how RemoteView itself is doing the lookup and found this:
if (!method.isAnnotationPresent(RemotableViewMethod.class)) {
throw new ActionException("view: " + klass.getName()
+ " can't use method with RemoteViews: "
+ this.methodName + "(" + param.getName() + ")");
}
But i could't do the same, because the Class RemotableViewMethod is not accsesible through the sdk. How to know if it is accesible or not?
By Writing my question I had the Idea to lookup for the class by its Name, and it worked.
So I updated my Method to the following:
private boolean canShowProgress(){
LogCat.d(TAG, "canShowProgress");
Class<ProgressBar> barclz = ProgressBar.class;
try {
Method method = barclz.getMethod("setVisibility", new Class[]{int.class});
Class c = null;
try {
c = Class.forName("android.view.RemotableViewMethod");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return (this.showProgress= (c != null && method.isAnnotationPresent(c)));
} catch (SecurityException e) {
LogCat.stackTrace(TAG, e);
} catch (NoSuchMethodException e) {
LogCat.stackTrace(TAG, e);
}
return false;
}
which works flawlessly

Extracting and setting enum Values via reflection

I am trying to set a number of Enums to default value I am using the following method:
private void checkEnum(Field field, String setMethod) {
// TODO Auto-generated method stub
try {
String className = Character.toUpperCase(field.getName().charAt(0)) +
field.getName().substring(1);
Class<?> cls = Class.forName("com.citigroup.get.zcc.intf." + className);
Object[] enumArray = cls.getEnumConstants();
//set to the last Enum which is unknown
invoke(setMethod, enumArray[enumArray.length - 1] );
} catch(Exception e) {
System.out.println(e.toString());
}
}
The problem is actually setting the Enum. I have extracted the enum type but to then call the MethodInvoker. Passing in the Enum object is proving a problem. All the enums have the following as the last element of the enum array.
EnumName.UNKNOWN
However this is not being set via the invoke method which looks like:
private Object invoke(String methodName, Object newValue) {
Object value = null;
try {
methodInvoker.setTargetMethod(methodName);
if (newValue != null) {
methodInvoker.setArguments(new Object[]{newValue});
} else {
methodInvoker.setArguments(new Object[]{});
}
methodInvoker.prepare();
value = methodInvoker.invoke();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
} catch (java.lang.reflect.InvocationTargetException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(),e);
}
return value;
}
So I'm lost as to why the
invoke(setMethod, enumArray[enumArray.length -1] );
Is not setting my Enum
I attempted to get your code running. The methodInvoker.prepare() call was throwing:
java.lang.IllegalArgumentException: Either 'targetClass' or 'targetObject' is required
So I added in the class missing parameter and the code works, if I understand your use case.
You appear to be setting a static field whose name must be the name of an Enum class under com.citigroup.get.zcc.intf with the first character in the field name downcased.
Here is my modified code:
public void checkEnum(Field field, String setMethod, Class clazz) {
try {
String className = Character.toUpperCase(field.getName().charAt(0)) +
field.getName().substring(1);
Class<?> cls = Class.forName("com.citigroup.get.zcc.intf." + className);
Object[] enumArray = cls.getEnumConstants();
//set to the last Enum which is unknown
invoke(setMethod, enumArray[enumArray.length - 1], clazz);
} catch (Exception e) {
System.out.println(e.toString());
}
}
private Object invoke(String methodName, Object newValue, Class clazz) {
Object value = null;
try {
MethodInvoker methodInvoker = new MethodInvoker(); // this was missing
methodInvoker.setTargetMethod(methodName);
methodInvoker.setTargetClass(clazz); // This was missing
if (newValue != null) {
methodInvoker.setArguments(new Object[]{newValue});
} else {
methodInvoker.setArguments(new Object[]{});
}
methodInvoker.prepare();
value = methodInvoker.invoke();
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
} catch (NoSuchMethodException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
} catch (java.lang.reflect.InvocationTargetException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Method invocation failed. " + e.getMessage(), e);
}
return value;
}
}
My test code resembled (Show is an enum class of mine, MethodNameHelper has been previously posted to StackExchange):
public class StackExchangeTestCase {
protected static final Logger log = Logger.getLogger(StackExchangeTestCase.class);
public static Show show;
public static void setShow(Show newShow) {
show = newShow;
}
#Test
public void testJunk() throws Exception {
Method me = (new Util.MethodNameHelper(){}).getMethod();
Class<?> aClass = me.getDeclaringClass();
Field att1 = aClass.getField("show");
show = null;
methodNameHelper.checkEnum(att1, "setShow", aClass);
System.out.println(show); // worked
}
}

Categories