10 Replies Latest reply: Oct 24, 2007 5:48 PM by 3004 RSS

    Negative numbers don't work

    807600
      Need help with some code, It is supposed to add two integers using only recursion, cannot use any operators such as (+,-,/,*,%) can use -- and ++, i got it working for multiplying positive numbers but it only works with negatives sometimes, when sending in

      4,4 = 16 Check
      -4,4 = -16 Check
      4,-4 = 16 Wrong
      -4,-4 = -16 Wrong

      I can't seem to figure out a way to make it work in all cases.
         import javax.swing.*;
         import java.lang.*;
        
           
          public class Recursion{
         
             public static void main(String[] args)
            {
               initialize();
               gatherAndCall();
            
            }
            private static int tot = 0;
            private static int divide = 0;
            private static int count = -1;
         
         
             public static void initialize()
            {
               int tot = 0;
               int divide = 0;
               int count = -1;
            
            }
              
             public static void choose()
            {
               String[] choose = {"continue","exit"};
               String options = (String) JOptionPane.showInputDialog(null, "Please select an option below...",
                  "Toggle Display", JOptionPane.QUESTION_MESSAGE, null,                                                          // icon
                  choose, // Array of choices
                  choose[0]); // Initial choice
                      
               if(options.equals("continue"))
               {
                  initialize();
                  tot = 0;
                  gatherAndCall();
               }
            
               if(options.equals("exit"))
                  System.exit(0);     
            
            }
         
             public static void gatherAndCall()
            {
               String[] choose = {"add","subtract","multiply","divide","mod","all"};
               String options = (String) JOptionPane.showInputDialog(null, "Please select an option below...",
                  "Toggle Display", JOptionPane.QUESTION_MESSAGE, null,                                                          // icon
                  choose, // Array of choices
                  choose[5]); // Initial choice
                      
                      
               String numbers =JOptionPane.showInputDialog("Please Enter Two Number Seperated By A Comma: ");
               int loc = numbers.indexOf(',');
               String sub1 = numbers.substring(0,loc);
               String sub2 = numbers.substring(loc+1);
               int a = Integer.parseInt(sub1);
               int b = Integer.parseInt(sub2);          
            
               if(options.equals("add"))
                  System.out.println(a+" Plus "+b+" = " +Recursion.add(a,b));
               if(options.equals("subtract"))
                  System.out.println(a+" Minus "+b+" = " + Recursion.subtract(a,b));
               if(options.equals("multiply"))
                  System.out.println(a+" Times "+b+" = " + Recursion.multiply(a,b));
               if(options.equals("divide"))
                  if(Recursion.divide(a,b)==12321)
                     System.out.println("You divided by Zero");
                  else{     
                     System.out.println(a+" Divided "+b+" = " +Recursion.divide(a,b));
                  }
               if(options.equals("mod"))
                  System.out.println(a+" Mod "+b+" = " +Recursion.mod(a,b));     
               if(options.equals("all"))
               {          
                  System.out.println(a+" Plus "+b+" = " +Recursion.add(a,b));     
                  System.out.println(a+" Minus "+b+" = " +Recursion.subtract(a,b));     
                  System.out.println(a+" Times "+b+" = " +Recursion.multiply(a,b));     
                  System.out.println(a+" Divided "+b+" = " +Recursion.divide(a,b));
                  System.out.println(a+" Mod "+b+" = " +Recursion.mod(a,b));
               }
                 
               choose();
            
            }
             public static int add(int a, int b)
            {
               if(a <= 0)
                  return (a < 0) ? add(MCH.succ(a), MCH.pred(b)) : b;
               else
                  return (a > 0) ? add(MCH.pred(a), MCH.succ(b)) : b;
                 
            }
         
             public static int subtract(int a, int b)
            {
               if(b <= 0)
                  return (b < 0) ? subtract(MCH.succ(a), MCH.succ(b)) : a;
               else
                  return (b > 0) ? subtract(MCH.pred(a), MCH.pred(b)) : a;
            }
              
             public static int multiply(int a, int b)
            {
            
               if (b==0) 
                  return(tot);
               else
               {      
                  tot = add(tot,a);
                    
                  if(b<0)
                     b=MCH.succ(b);
                  
                  else
                     b=MCH.pred(b);
                 
                  multiply(a,b);
               }
               return (tot);
                 
            }
              
         }
      Thanks for any help also if any part of the code looks really inefficient and you know a better method please let me know thanks.
        • 1. Re: Negative numbers don't work
          807600
          Forgot to mention that

          MCH.pred = --
          and
          MCH.succ = ++
          • 2. Re: Negative numbers don't work
            807600
                  private static int tot = 0;
                  private static int divide = 0;
                  private static int count = -1;
               
               
                   public static void initialize()
                  {
                     int tot = 0;    // these initializations are useless, all you're initializing are these local variables, which go out of scope when this method ends. 
                     int divide = 0;
                     int count = -1;
                  // do this instead
                     tot=0;
                     divide = ... etc
                  }
            What do you get when you trace through your code by hand with -4 and -4? Get a piece of paper and work out the result your code gives yourself, that will show you what you're doing wrong.
            • 3. Re: Negative numbers don't work
              807600
              The initialize method is pointless i just never got around to removing it, i did trace it by hand and have found the problem however i don't know how to fix it. I have tried several things all leading to varying degrees of failure.
              • 4. Re: Negative numbers don't work
                807600
                Well, what is the problem, do you think?

                BTW it's rude to post code here that you know is irrelevant. It means that you're wasting others' time. Ideally you should create a small, compilable (unless the problem is that you can't get it to compile) example that demonstrates the trouble you're having and does nothing else.
                • 5. Re: Negative numbers don't work
                  807600
                  Nath5 wrote:
                  The initialize method is pointless i just never got around to removing it, i did trace it by hand and have found the problem however i don't know how to fix it. I have tried several things all leading to varying degrees of failure.
                  So what is the problem? Describe exactly what's going wrong in the method. Then we can help you solve it.
                  • 6. Re: Negative numbers don't work
                    3004
                    Nath5 wrote:
                    The initialize method is pointless i just never got around to removing it, i did trace it by hand and have found the problem however i don't know how to fix it. I have tried several things all leading to varying degrees of failure.
                    At each step in your program, print out the relevant vaules. At some point, one or more ofthose values will differ from their respective counterparts in your manual solution. Once you find that, you will have found the problem.

                    You already have a HUGE hint: When the second input is negative, the sign of the result is the opposite of what it's supposed to be. That practically screams out what the nature of the problem is.
                    • 7. Re: Negative numbers don't work
                      3004
                      hunter9000 wrote:
                      Nath5 wrote:
                      The initialize method is pointless i just never got around to removing it, i did trace it by hand and have found the problem however i don't know how to fix it. I have tried several things all leading to varying degrees of failure.
                      So what is the problem? Describe exactly what's going wrong in the method. Then we can help you solve it.
                      Right. What specific failure did you get for which specific thing that you tried.

                      But seriously, a little diligence, attention to detail, and deductive reasoning from the clues you already have should drop the answer on you like a ton of bricks.
                      • 8. Re: Negative numbers don't work
                        807600
                        The problem happens in this piece of code, and its not really a problem, the code is doing exactly what it should do, the problem is that its not what i need to happen.
                          public static int multiply(int a, int b)
                              {
                              
                                 if (b==0) 
                                    return(tot);
                                 else
                                 {      
                                    tot = add(tot,a); //This is the  where things go wrong because it multiplies by adding up the first number 
                                                           // the second number of times.  However since the first number is positive, the negative is not                                                   
                                                           //considered 
                                    if(b<0)
                                       b=MCH.succ(b);
                                    
                                    else
                                       b=MCH.pred(b);
                                   
                                    multiply(a,b);
                                 }
                                 return (tot);
                                   
                              }*/
                        I can see where the code goes wrong and i have traced it by hand, i just need a suggestion as to how to handle the negative.
                        • 9. Re: Negative numbers don't work
                          3004
                          Nath5 wrote:
                          The problem happens in this piece of code, and its not really a problem, the code is doing exactly what it should do,
                          Obviously it's not.

                          I didn't see any print statements in there which would allow you to see what's happening each step of the way.
                          I can see where the code goes wrong and i have traced it by hand
                          Great! Then you can fix it!
                          i just need a suggestion as to how to handle the negative.
                          Exactly the same as when you do it manually.
                          • 10. Re: Negative numbers don't work
                            3004
                            Nath5 wrote:
                            tot = add(tot,a); //This is the  where things go wrong because it multiplies by adding up the first number 
                            // the second number of times.  However since the first number is positive, the negative is not                                                   
                            //considered 
                            Look, you already know exactly what the problem is: When b is negative, the answer ends up with the wrong sign. Does that plus your statement that this is where things go wrong not suggest anything to you?