8 Replies Latest reply: Jan 8, 2008 5:17 PM by 807603 RSS

    Regex and complex numbers

    807603
      Hi community ,
      I made a small program using simple regex.
      I can't figure out why I cannot input a complex number
      in a format like
      (     Re{z},Im{z}     )
      i.e. I don't know why
      the brackets can't be separated with the white spaces?
      Thnx in advance,
      Nikola

      Here is the code :
      /**
       * @author Nikola Radakovic 
       */
      
      import java.util.*;
      import java.util.regex.Pattern;
      
      // complexni number
      
      class ComplexNo { 
           private float x,y;
      
           public float getX() {
                return x;
           }
      
           public void setX(float x) {
                this.x = x;
           }
      
           public float getY() {
                return y;
           }
      
           public void setY(float y) {
                this.y = y;
           } 
           
           public ComplexNo sumarize(ComplexNo drugi){
                this.x = this.x + drugi.getX();
                this.y = this.y + drugi.getY(); 
                return this; 
           }     
      }
      
      
      public class Complex {
           
           public static void main(String [] args){
                
                ComplexNo no1; 
                   ComplexNo result = new ComplexNo(); 
                     
                Scanner sc = new Scanner(System.in); 
           
                boolean flag = true; 
                
                Pattern pattern = Pattern.compile("\\(\\s*\\d*\\.?\\d*,\\d*\\.?\\d*\\s*\\)"); 
                     
                while(flag){
                System.out.println("Input a complex number in format (Re{z},Im{z}) : ");
                
                while(sc.hasNext(pattern))
                {
                     
                     
                     String str = sc.next().replaceAll("\\(|\\)","");
                     Scanner float_scan = new Scanner(str);
                     float_scan.useDelimiter(","); 
                     
                     // get a float number 
                     while(float_scan.hasNextFloat()){ 
                          no1 = new ComplexNo();
                          no1.setX(float_scan.nextFloat());
                          no1.setY(float_scan.nextFloat());
                          System.out.println("Inputed number "+no1.getX()+","+no1.getY());
                          result.sumarize(no1); 
                     }
                }
                flag = false; 
                }
                
                System.out.println("The result is  "+result.getX()+","+result.getY()); 
                
           }
      }
      Edited by: EqAfrica on Jan 8, 2008 7:29 PM

      Edited by: EqAfrica on Jan 8, 2008 7:30 PM