Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program with an exception handler that deals with nonnumeric operands: t

ID: 3541816 • Letter: W

Question


Write a program with an exception handler that deals with nonnumeric operands: then write another program with out using an exception handler to achieve the same objective. Your program should display a message to the user of the wrong operand type before exiting




Here is the error after running the compiled code:

Exception in thread "main" java.lang.NoClassDefFoundError: NumFormatException

(wrong name: numformatexception/NumFormatException)


Here is the source code:

package numformatexception;


public class NumFormatException

{

public static void main(String[] args)

{

if (args.length != 1)

{

System.out.println("Please use format: java NumberFormatException operand1 OPERATOR (+ or - or * or /) operand2");

System.exit(0);

}


int result = 0;

int a,b;


a = Integer.valueOf(args[0].charAt(0)) - 48;

b = Integer.valueOf(args[0].charAt(2)) - 48;


try

{

switch (args[0].charAt(1))

{

case '+':result = a+b;

break;

case '-':result = a-b;

break;

case '*':result = a*b;

break;

case '/':result = a/b;

break;

}


System.out.println(a + " " + args[0].charAt(1) + " " + b + " = " + result);


}

catch (NumberFormatException nfe)

{

String message = nfe.getMessage();

System.out.println(message);

}

}

}


Please Help me fix this...

Explanation / Answer

// code is working fine.

// give command line arguments as 3+5



package NumFormatException;
public class NumFormatException
{
public static void main(String[] args)
{
if (args.length != 1)
{
System.out.println("Please use format: java NumberFormatException operand1 OPERATOR (+ or - or * or /) operand2");
System.exit(0);
}
int result = 0;
int a,b;
a = Integer.valueOf(args[0].charAt(0)) - 48;
b = Integer.valueOf(args[0].charAt(2)) - 48;
try
{
switch (args[0].charAt(1))
{
case '+':result = a+b;
break;
case '-':result = a-b;
break;
case '*':result = a*b;
break;
case '/':result = a/b;
break;
}
System.out.println(a + " " + args[0].charAt(1) + " " + b + " = " + result);
}
catch (NumberFormatException nfe)
{
String message = nfe.getMessage();
System.out.println(message);
}
}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote