This is the code snippet:
public void actionPerformed(ActionEvent e){
int i1,i2;
try{
if(e.getSource()==b1){
.
.
.
else if(e.getSource()==b4){
double i1,i2;
i1=Integer.parseInt(t1.getText());
i2=Integer.parseInt(t2.getText());
i1=i1/i2;
l7.setText(i1+"");
}
else if(e.getSource()==b5){
i1=Integer.parseInt(t1.getText());
i2=Integer.parseInt(t2.getText());
i1=i1%i2;
l7.setText(i1+"");
}
}
catch(ArithmeticException ex2){
l7.setText("Debugging?");
JOptionPane.showMessageDialog(null,"Divide by zero exception!!");
//*WHY THIS SECTION IS NEVER BEING EXECUTED AFTER PERFORMING A DIVIDE BY ZERO i.e. ARITHMETIC EXCEPTION!*
}
catch(Exception ex){
JOptionPane.showMessageDialog(null,"Enter Values First!!");
}
}
The JRE is never executing the Arithmetic Exception catch statement, why?
Yes, it is handing it but it not producing the output that I expect it to produce!
It is automatically displaying, "Infinity" & "NaN" on my Java application!
Thanks!
Yes! Double and float have their own inbuilt values for infinity. There might be some other issues in your code that I'm not aware about.
Check these edits:
else if(e.getSource()==b4){
double i1,i2;
i1= Integer.parseInt(t1.getText());
i2= Integer.parseInt(t2.getText());
if(i1!=0 && i2 == 0){
throw new ArithmeticException();
}
else if(i2 == 0 && i1 == 0) {
throw new ArithmeticException();
}
i1= i1/i2;
l7.setText(i1+"");
}
This throw new ArithmeticException(); will force your code to execute the section that you are willing to execute!
Also, check this link: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Hope this helps!
Check these lines of code:
} else if (e.getSource() == b4) {
double i1, i2; // Comment this line to make it work like you need
i1 = Integer.parseInt(t1.getText());
i2 = Integer.parseInt(t2.getText());
i1 = i1 / i2;
l7.setText(i1 + "");
}
You have redeclared i1 and i2 to be double. The Double type defines inbuilt values for Infinity and NaN. That's the reason your code is not executing your ArithmeticException catch block.
Simply comment the double i1, i2; line to make it work like you need.
Update
If you want to show an error message, simply put a check:
} else if (e.getSource() == b4) {
double i1, i2;
i1 = Integer.parseInt(t1.getText());
i2 = Integer.parseInt(t2.getText());
if(i2==0){
throw new ArithmeticException("Cannot divide by zero");
}
i1 = i1 / i2;
l7.setText(i1 + "");
}
Hope this helps!
Related
I've been working with SikuliX to get some try some ATDD. The code works well when only I am the one working with it. However transferring the below code to anyone else is simply counter-productive irrespective of how well I comment the code.
int numOfTries;
while (!isFinishStage && numOfTries != 3) {
numOfTries++;
try {
temp = new Pattern("imgs/img1.png").similar(0.9f);
s.wait(temp, 1);
s.find(temp);
s.hover(temp);
isFinishStage = true;
break;
}catch (FindFailed ff1) {
try {
temp = new Pattern("imgs/img2").similar(0.5f);
s.wait(temp, 1);
s.find(temp);
s.hover(temp);
isFinishStage = true;
break;
} catch (FindFailed ff2) {
try{
temp = new Pattern("imgs/img3");
s.wait(temp, 1);
s.find(temp);
s.click(temp);
} catch (FindFailed ff3) {
continue;
}
}
}
}
A FindFailed exception is thrown once a pattern/image cannot be matched against anything on the screen (similarity simply adjusts the tolerance level). For the current GUI that it is automating, there are three possible scenarios (where this piece of code comes to play)
Screen A pops up
Screen B pops up
Neither 1 or 2, instead 'Next' pops up
Thus we check for Screen A, if not we check for Screen B, if not we check for Next, if not, repeat the cycle until we exceed the number of tries — meaning that the test has failed.
With the way Sikuli works or atleast how I've been interpreting it, you would have to perform various loops through multiple try-catch statements which seems a little off putting.
PS: The idea behind the above code is to just get it to work. If there is any ambiguity let me know so that I can clarify.
The following code is (I think) equivalent to your code:
int numOfTries;
while (!isFinishStage && numOfTries < 3) {
numOfTries++;
if (tryPattern(s, "imgs/img1.png", 0.9f) ||
tryPattern(s, "imgs/img2", 0.5f)) {
isFinishStage = true;
} else {
// Note that the third "attempt" is inconsistent with
// the others because you don't set isFinishedStage.
tryPattern(s, "imgs/img3", 1.0f)
}
}
private boolean tryPattern(SomeClass s, String path, float similarity) {
try {
Pattern temp = new Pattern(path);
if (similarity != 1.0f) {
temp = temp.similar(similarity);
}
s.wait(temp, 1);
s.find(temp);
s.hover(temp);
return true;
} catch (FindFailed ff) {
return false;
}
}
I would like you to read software principles and make your code clean after lecture:
10 Object Oriented Design Principles
After this you should know basics like DRY and KISS principles that should emplace pretty well in your posted code.
Here's how:
String [] patterns = {
"imgs/img1",
"imgs/img2",
"imgs/img3"
};
float [] similarities = {
0.9f,
0.5f,
0.1f
};
for(int i=0; i<patterns.length; i++) {
String str = patterns[i];
try {
float sim = 0.1; // default
try {
sim = similarities[i];
} catch (IndexOutofBoundsException e) {;}
temp = new Pattern(str).similar(sim);
s.wait(temp, 1);
s.find(temp);
s.hover(temp);
if(i != patterns.length - 1){ // Different last case
isFinishStage = true;
break;
}
} catch (FindFailed ff) {
continue;
}
}
I am trying to write a program to equate the value of any number to any power, and I'm suppose to implement exception handling for exponents less than zero which i successfully did and also exception handle for when the value is too large to output i.e. infinity.
heres my power class which contains the function Power :
public class power
{
// instance variables - replace the example below with your own
public static double Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent cannot be less than zero");
}
else if(exp == 0){
return 1;
}
else{
return base * Power(base, exp-1);
}
}
}
Heres the Test class :
public class powerTest
{
public static void main(String [] args)
{
double [] base = {2.0, 3.0, 2.0, 2.0, 4.0 };
int [] exponent = {10, 9, -8, 6400, 53};
for (int i = 0; i < 5; i++) {
try {
double result = power.Power(base[i], exponent[i]);
System.out.println("result " + result);
}
catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
}
}
heres the output of the test :
result 1024.0
result 19683.0
Exponent cannot be less than zero
result Infinity
result 8.112963841460668E31
my question is how can i get "result infinity" to say something else through ArithmeticException handling something along the lines of "Floating point Overflow"?
thanks in advance.
When you catch the exception, here
catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
just do
System.out.println("Floating point Overflow")
as well(if you want to add more) or replace the first print with this statement
This way like you said, "you get result infinity" to say something else through ArithmeticException handling"
Not sure if this is what you are looking for, but you can test for infinity/overflow with an if statement as well:
if( mfloat == Float.POSITIVE_INFINITY ){
// handle infinite case, throw exception, etc.
}
So in your situation, you would do something like this:
public static double
Power(double base, int exp) throws IllegalArgumentException
{
if(exp < 0){
throw new IllegalArgumentException("Exponent less than zero");
}
else if(exp == 0){
return 1;
}
else{
double returnValue = base * Power(base, exp-1);
if(returnValue == Double.POSITIVE_INFINITY)
throw new ArithmeticException("Double overflowed");
return returnValue;
}
}
I wrote Java code to convert String to long. However, when dealing with overflow problem, I don't have clues how to solve it. If a number is overflowed, computer believe every number is legal in storage. How to let program, with 64bit jdk ,detect the real number is overflowed is the key problem. And I'm not allowed to use any built-in library such as parseLong or others.
public static long strTolong(String s){
//error checking
if(s == null) return 0;
s = s.trim();//remove all space character
boolean neg = false;//judge the number is negative or positive
int pos = 0 ; //index of string
long result = 0;
//check positive or negative
if(s.charAt(pos) == '-'){
neg = true;
pos++;
}else if(s.charAt(pos) == '+') pos++;
//calculate result
while(pos<s.length()){
if(s.charAt(pos) >='0' && s.charAt(pos) <='9'){
result = result*10+(s.charAt(pos) - '0');
}else
break;
pos++;
}
if(neg) result =-result;
//check overflow
if(result >Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
if(result<Long.MIN_VALUE){
return Long.MIN_VALUE;
}
return result;
}
If data is larger than long.maxvalue, the result can't be stored in computer correctly.
How to solve this problem?
Your best option is probably to do a lexicographical comparison between the input and the minimum/maximum numbers before you start.
static int compare(String v1, String v2) {
boolean neg1 = v1.startsWith("-");
boolean neg2 = v2.startsWith("-");
return neg1 ? (neg2 ? -comparePositives(v1.substring(1),v2.substring(1)):-1)
: (neg2 ? 1 : comparePositives(v1, v2));
}
static int comparePositives(String v1, String v2) {
// Is one longer?
if (v1.length() != v2.length())
return v1.length() < v2.length() ? -1 : 1;
// Both empty?
if (v1.isEmpty())
return 0;
// First digit differs?
if (v1.charAt(0) != v2.charAt(0))
return v1.charAt(0) < v2.charAt(0) ? -1 : 1;
// Recurse on rest of number
return comparePositives(v1.substring(1), v2.substring(1));
}
Use it for instance as follows:
if (compare(s, ""+Long.MIN_VALUE) == -1)
throw new NumberFormatException("Input too small");
if (compare(s, ""+Long.MAX_VALUE) == 1)
throw new NumberFormatException("Input too large");
Tested here: http://ideone.com/HmMkJ3
Note that the code does not check that the input is well formed. I suggest you do such check first. (Be aware of cases like 0 and -0 etc.)
You could do the same thing that Long#parseLong would do:
throw new NumberFormatException("too long (pun intended): "+s);
I am not sure what you trying to achieve here. If String is greater than Long.MAX_VALUE means that is no more a Long value.
If your String value is withing the range of Long, you can use Long.parseLong() with out this kind of hard ways.
If you want to have huge number you can use BigDecimal easily
String max = Long.MAX_VALUE+"";
System.out.println(max);
long maxL=Long.parseLong(max)+1;
System.out.println(maxL);
BigDecimal bigDecimal=new BigDecimal(max).add(new BigDecimal("1"));
System.out.println(bigDecimal);
Out put:
9223372036854775807 // long max value
-9223372036854775808 // incorrect result in long
9223372036854775808 // BigDecimal gives you correct one
For your case you can throws an Exception if value is greater than Long.MAX_VALUE or lower than Long.MIN_VALUE
So I'm using this recursive method to calculate the product of two numbers by recursive addition. I know that big numbers overflow the stack and my intention is to catch the stack overflow exception so the program don't crash. However, I don't understand why the output message displays several times in the same line and the return 0 is never passed out of the method. returning 0 is not that important, I'm forced to have a return statement. But instead of getting back 0, I'm getting back what seems random large numbers.
I would love for it to just display the message once and pass my value back or better yet terminate the method and just return the message. Any ideas?
here is the method:
public static long multiplicationRecursive(long num1, long num2) {
try {
if (num2 == 0) {
return 0;
} else {
return num1 + multiplicationRecursive(num1, num2 - 1);
}
} catch (StackOverflowError e) {
System.out.println("Recursion failed");
return 0;
}
}
You have to catch the error only once, at the point where you call the method for the first time (and remove the try/catch from the recursive method):
long result = 0L;
try {
result = multiplicationRecursive(num1, num2);
} catch (StackOverflowError e) {
System.out.println("Recursion failed");
result = 0L;
}
The problem with your approach is that sure, the exception gets caught, but then the method exits normally and goes back to the point where it was called recursively, effectively returning a bogus value.
whats happening is, when your recursive method call gets exception , it goes to catch block and since it has return 0, it comes back to caller with the value 0. and your caller is always will be as below
return num1 + multiplicationRecursive(num1, num2 - 1);
so num1+0 will happen internally and it returns the computed value till the exception.
since exception occured your recursive method will stop so it will print computed value as num1+0
see below code to have proper recursive handling
if (num2 == 0) {
return 0;
} else {
try{
//System.out.println("before oper");
if(multiplicationRecursive(num1, num2 - 1)==0){
return 0;
}
else{
return num1 + multiplicationRecursive(num1, num2 - 1);
}
}
catch (StackOverflowError e) {
System.out.println("Recursion failed");
return 0l;
}
//return 0;
}
This is my code to add to binary strings, I am getting correct value in res string but it still gives me an exception at the end of execution.
The strings m1 & m2 are of equal length of 28 each.
Still I tried running the loop just 10 times to verify but error still persists.
This holds true for any value of i, irrespective of greater than or lesser than actual length of both strings.
public static String addMantissa(String m1,String m2)
{
String res=" ";
int c=0;
System.out.println("Length is " + m2.length());
int i=0;
while(i < m2.length())
{
System.out.print(" " + res.charAt(i));
if(m1.charAt(i)=='1' && m2.charAt(i)=='1')
{
if(c==0)
{
res+="0";
c=1;
}
else
{
res+="1";
c=1;
}
}
if(m1.charAt(i)=='1' && m2.charAt(i)=='0')
{
if(c==0)
{
res+="1";
c=0;
}
else
{
res+="0";
c=1;
}
}
if(m1.charAt(i)=='0' && m2.charAt(i)=='1')
{
if(c==0)
{
res+="1";
c=0;
}
else
{
res+="0";
c=1;
}
}
if(m1.charAt(i)=='0' && m2.charAt(i)=='0')
{
if(c==0)
{
res+="0";
c=0;
}
else
{
res+="1";
c=0;
}
}
i++;
}
return res;
}
Thanks in advance.
Your entire method can be replaced by just one line:
public static String addMantissa(String m1, String m2) {
return new BigInteger(m1, 2).add(new BigInteger(m2, 2)).toString(2);
}
The size of 28 bits mentioned in your question means that the Integer class could have neen used for parsing, but using BigInteger means that strings of any size can be handled.
You should use the JDK instead of reinventing the wheel.
Also, "less code is good" is a great mantra (provided the code remains clear, of course), and this code has high density.
#ShreyosAdikari is basically right.
System.out.print(" " + res.charAt(i));
Should be called at the end of the loop, as then res[i] is filled.
Maybe you meant:
System.out.print((" " + res).charAt(i));
But then you do not print the last loop's res.
Actually the exception comes from the line
while(i < m2.length())
You need to change it to
while(i < m2.length() && i<m1.length())
As if m1(say 1) has a length lower than m2(say 4) and you checking only the value of m2. Then in the second iteration it will enter the loop as 2<4, and when it tryes to get m1.carAt(2) (as the length 1) it will throw String index out of bounds exception.