gunjannigam 28 Junior Poster

I have made a few change in your BigInteger class.
Probably this might not be the most efficient way, but its working perfectly fine. I will try to make it better on weekend

package pkg;



import java.util.Scanner;


    public class BigInteger {



        private int[]  NumC;
        private int[]  NumD;
        private int[] result;

        public BigInteger(){

            NumC   = null;
            NumD   = null;
            result = null;

        }//Assessor


        public void Input(){

            Scanner keyboard = new Scanner(System.in);
            String aa;
            String bb;
            System.out.println();
            System.out.print("Enter First Number: ");
            aa = keyboard.nextLine();
            NumC = convertArray(aa);
            setNumC(NumC);


            System.out.print("Enter Second Number: ");
            bb = keyboard.nextLine();
            NumD = convertArray(bb);
            setNumD(NumD);


            System.out.println();
            System.out.print("   ");
            print(NumC);
            System.out.print(" + ");
            print(NumD);
            System.out.print(" = ");
            Add(NumC,NumD);




        }// Input


        public BigInteger(int[] a,
                          int[] b,
                          int[] c){

            this.NumC   = a;
            this.NumD   = b;
            this.result = c;

        }//Constructor

        public void setNumC (int[] a){

            NumC = a;


        }//Mutator NumC


        public void setNumD (int [] b){

            NumD = b;


        }//Mutator NumD

        public void setResult (int[] c){

            result = c;

        }//Mutator NumC

        public static int[] convertArray(String b){

            int[]arr = new int[b.length()];
            
                for (int i = 0; i < b.length(); i++){

                arr[i] = Character.digit(b.charAt(i),10);

		}

            return arr;


          }//end of toArray

        public static void flipArray(int[] b) {
            int left  = 0;
            int right = b.length-1;

            while (left < right) {

                int temp = b[left];
                b[left]  = b[right];
                b[right] = temp;

                left++;
                right--;
            }
        }//FilpArray

        public void Add (int[]a,int[]b){

            int sum = 0;
            //Swap(a,b);// makes b[] the smaller array
            flipArray(a); // filps array
            flipArray(b); // 123 becomes 321
            int[] arr1,arr2;
            if(a.length<b.length)
            {
                arr1 = …
gunjannigam 28 Junior Poster

I fixed the swap method, but even tho what you had correct the additional number, it doesn't carry the one to the next number.

Output:

Enter First Number: 99999
Enter Second Number: 1
99999 + 1 = 99990

Enter First Number: 9
Enter Second Number: 11111
9 + 11111 = 11110

Well it runs perfectly on my system. The carrry part is happening. Please post your complete code so that I can look what is happening

gunjannigam 28 Junior Poster

It didnt work. My output now is:

Enter First Number: 123456789
Enter Second Number: 1
123456789 + 1 = 1234567810

Enter First Number: 1
Enter Second Number: 123456789
1 + 123456789 = java.lang.ArrayIndexOutOfBoundsException: 1

Ok I got the mistake for 1st part
The code should be

public void Add (int[]a,int[]b)
{

            int sum = 0;
	    if(a.length<b.length)
	         Swap(a,b);// makes b[] the smaller array
          
            flip(a); // filps array
            flip(b); // 123 becomes 321
            

            int[] c = new int[a.length];
	    int[] d = new int[a.length];
	    for(int i=0;i<b.length;i++)
			d[i]=b[i];
	    for(int i=b.length;i<a.length;i++)
			d[i]=0;
            int diff = 0;

            for (int i = 0; i<a.length; i++){

                sum = a[i] + d[i]+ diff;
                diff = 0;
                    if (sum > 9 && i <=a.length-2){
                        sum -= 10;
                        diff = 1;
                    }

                c[i] = sum;

            }
                flip(c);
                printArray(c);
}

This will print the correct result. For second part, i.e. ArrayIndexOutofBoundException, I think you have a problem in Swap method. Kindly check your Swap method that it swaps the two array if the length of array1<array2.

MaxWildly commented: Everything Offered has been very helpful. +1
gunjannigam 28 Junior Poster

I am not getting the correct output for this method. I have looked at the BigInteger class, and even tried to implement, after rewriting for my instance variable, but it did not carry the numbers over to the next digit, or bring down the remainders.

Thanks in advance.

public void Add (int[]a,int[]b){

           
            int sum = 0;
            Swap(a,b);// makes b[] the smaller array


            flip(a); // flips array
            flip(b); // 123 becomes 321

            int[] c = new int[a.length]; // variable to hold Answer....
            int diff = 0;

            for (int i = a.length-1; i >=0; i--){

                sum = a[i] + b[i] + diff;
                diff = 0;

                    if (sum > 9 && i > 0){
                        sum -= 10;
                        diff = 1;
                    }

                c[i] = sum;  
            }
            
                flip(c);
                print(c);

Output:
Enter First Number: 123456789
Enter Second Number: 123456
123456789 + 123456 = 0005791416

Enter First Number: 123456789
Enter Second Number: 123456789
123456789 + 123456789 = 2468035719

Enter First Number: 123456
Enter Second Number: 123456789
123456 + 123456789 = .....
(ArrayIndexOutOfBoundsException)

This is what you need to do

public void Add (int[]a,int[]b)
{
        
            int sum = 0;
	    if(a.length<b.length)	
	         Swap(a,b);// makes b[] the smaller array

            

            flip(a); // filps array
            flip(b); // 123 becomes 321

            int[] c = new int[a.length];
	    int[] d = new int[a.length];
	    for(int i=0;i<b.length;i++)
			d[i]=b[i];
	    for(int i=b.length;i<a.length,i++)
			d[i]=0;
            int diff = 0;

            for (int i = a.length-1; i >=0; i--){

                sum = a[i] + d[i]+ diff;
                diff = 0;
                    if (sum > 9 && i > 0){ …
gunjannigam 28 Junior Poster

I modified the Add method so it would flip the array, and add correctly. Only now, it is not returning the remaining numbers. Hopefully you will be able to understand after reviewing the code.

public void Add (int[]a,int[]b){

            flip(a);
            flip(b);
            int sum = 0;
            int[] temp;
            
            if(a.length < b.length){
                temp = b;
                b = a;
                a = temp;
                
            }

            int[] c = new int[b.length];
            int diff = 0;

            for (int i = b.length-1; i >=0; i--){

                sum = a[i] + b[i]+ diff;
                diff = 0;
                    if (sum > 9 && i > 0){
                        sum -= 10;
                        diff = 1;
                    }

                c[i] = sum;
                
            }
                flip(c);
                print(c);

        }

Output:
Enter First Number: 67890
Enter Second Number: 2

67890 + 2 = \*missing the rest of the numbers "6789"*\ 2

The logic you used two errors. First of all you are not summing up the remaining digits of a, so you are not getting it in output. Secondly when you will add no like 4567+42 in give result like 109(leaving the remaining numbers).

For solution, I guess After flipping array b. Create a new array(say d) of length larger array(a). Equate starting indexes with array b, and fill up the remaining with zeros. And instead of running the loop for smaller array length, run it for the larger array length(i.e. a). And add array, new array d and the diff. This will solve both the problem, probably...

gunjannigam 28 Junior Poster

I am not sure what you intend to do. Why do u need to create an array of Integers from one String. As far as I think one String will correspond to one Integer. Why do you need an array. For converting one string to an Integer value you can use Integer.parseInt() method.

What your output suggest is you are adding the two arrays address, instead of adding the content in that array

gunjannigam 28 Junior Poster

Hello, I have a school assignment to build a 2 minute countdown timer in java. Gunjannigam managed to assist me in creating the functions. My code for secondCount, I have built a function so that I can adjust secondCount to a number and it will change the timer. When secondCount is at 25, the timer is displayed as 00:15:000 in mm:ss:sss format. When secondCount is at 200, the timer is displayed as 02:00:000 in mm:ss:sss format.

However, the problem i am having is when the timer counts down to zero. at 00:00:000, the timer instantly resets to 59:59:000 and continues to count down from there. How would i go about fixing my code so that i can get the timer to stop when it gets to zero instead of continuing. In the final product of this program, it is my goal to get it to play a buzzer sound so it can act as a sports timer.

...forgive me, i am a very new programmer to java ( about two months of java practise )

//***************Import java files necessary for this project********************//
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
//*********************************************************************//
public class Stopwatch extends JFrame implements ActionListener, Runnable
{
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss : SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
     {
         public void run()
         {
             displayElapsedTime(Stopwatch.this.startTime - System.currentTimeMillis());
         }
     };
//************************Action Performed Function***********************//
     public void actionPerformed(ActionEvent ae)
     { …
gunjannigam 28 Junior Poster

If you want to navigate thru different pages, add all the componentss of 1 page in 1 panel each. Now add all the panels to your JFrame .
You can either use CardLayout to swap between the panels or panel.setVisible() method to make the required panel visible.
You can implements method with your buttons ActionListener. You will have to add back buttons on all panels and then call each ActionListener respectively

gunjannigam 28 Junior Poster

Gunjannigam, thanks for your help!

It works great now that it will count down.

However, it seems to start at 13 minutes for some reason. When I let it run, it will count down a minute perfectly but as soon as the minute is up, instead of changing from 12:00:000 to 11:59:999 it resets automatically back up to 13 minutes. Also how would we go about changing this to 2:00:0 instead of the 13?

Thanks.

Sorry in Line No 8 should be

private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("mm : ss : SSS");

And this will adjust the time as per your time zone.
If your time zome is like 5hours 30 minutes ahead of GMT, then you might have to subtract 30 minutes from startime so that it set to zero.
You can do this by making line 37 as

startTime= 2*60*1000+System.currentTimeMillis()-30*60*1000;
gunjannigam 28 Junior Poster

This will Reset Your button to two minutes everytime you pressed it and it will count backwards.

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;

public class Stopwatch extends JFrame implements ActionListener, Runnable
    {
     private long startTime;
     private final static java.text.SimpleDateFormat timerFormat = new java.text.SimpleDateFormat("MM : ss : SSS");
     private final JButton startStopButton= new JButton("Start/stop");
     private Thread updater;
     private boolean isRunning= false;
     private final Runnable displayUpdater= new Runnable()
         {
         public void run()
             {
             displayElapsedTime(Stopwatch.this.startTime - System.currentTimeMillis());
         }
     };
     public void actionPerformed(ActionEvent ae)
         {
         if(isRunning)
             {
             long elapsed= startTime - System.currentTimeMillis() ;
             
             isRunning= false;
             try
                 {
                 updater.join();
                 // Wait for updater to finish
             }
             catch(InterruptedException ie) {}
             displayElapsedTime(elapsed);
             // Display the end-result
         }
         else
             {
             startTime= 2*60*1000+System.currentTimeMillis();
             isRunning= true;
             updater= new Thread(this);
             updater.start();
         }
     }
     private void displayElapsedTime(long elapsedTime)
         {
         startStopButton.setText(timerFormat.format(new java.util.Date(elapsedTime)));
     }
     public void run()
         {
         try
             {
             while(isRunning)
                 {
                 SwingUtilities.invokeAndWait(displayUpdater);
                 Thread.sleep(50);
             }
         }
         catch(java.lang.reflect.InvocationTargetException ite)
             {
             ite.printStackTrace(System.err);
             // Should never happen!
         }
         catch(InterruptedException ie) {}
         // Ignore and return!
     }
     public Stopwatch()
         {
         startStopButton.addActionListener(this);
         getContentPane().add(startStopButton);
         setSize(100,50);
         setVisible(true);
     }
     public static void main(String[] arg)
         {
         new Stopwatch().addWindowListener(new WindowAdapter()
             {
             public void windowClosing(WindowEvent e)
                 {
                 System.exit(0);
             }
         });
     }
}
gunjannigam 28 Junior Poster

I'm hoping someone out there can help me.
i have to use a 2nd class to create a JMenuBar to attach to a JFrame
i get an error :49: incompatible types
found : javax.swing.JFrame
required: java.lang.String
return aTestFrame;

(i have also tried something else and got a static/non static error)

here's the code thanks for any help!


import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;

public class Driver{
public static void main(String[] args) {
TheWindowObject aTestFrame = new TheWindowObject ("test");

}
}
class TheWindowObject{

TheWindowObject(String title){
CreateWindow () ;
}
TheWindowObject(String title, int height, int width){
}

JFrame CreateWindow (){

String title ="test";
int height =200 ;
int width=400 ;
JFrame aTestFrame= null;

aTestFrame =new JFrame("test");
aTestFrame.setSize (width, height);
aTestFrame.setVisible (true);
aTestFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
return aTestFrame;
}}
class MenuFactory {
String MenuFactory (String menuInput){

JFrame aTestFrame= null;
JMenuBar generate= null;
JMenu createMenu;
JMenuItem createMenuItem;
// File Menu, F - Mnemonic
createMenu = new JMenu("File");
createMenu.setMnemonic(KeyEvent.VK_F);
generate.add(createMenu );

// File->New, N - Mnemonic
createMenuItem = new JMenuItem("New", KeyEvent.VK_N);
createMenu.add(createMenuItem);
aTestFrame.setJMenuBar (generate );

return aTestFrame;
}
}

First of all The constructor of the class doesn't return. Secondly in line no 48 you have declared the method as return type String and then you are returning a string. I have altered your code to do what you …

nyny11211 commented: great help-thanks1 +0
gunjannigam 28 Junior Poster

First of all always use Code tags.
If you only want to hide your frame and dont want to close your application you can use frame.setVisible(false) in your done button ActionListener so that you application wont exit only the frame will be hidden

gunjannigam 28 Junior Poster

help me plz i need to sort ip address, am try to sort
in java.util.Arrays.sort() but it not correct for eg

String st[]={"10.4.23.16","10.4.23.9"};
java.util.Arrays.sort(st);
for(int i=0;i<st.length;i++){
System.out.println(st[i]);
}

the out put is
10.4.23.16
10.4.23.9
plz give idea

The Algo which you a using will sort the string array. For comparing strings it will compare each compare starting from 1st character. Now for the eg given both string are same until 8 characters(start counting from 1), i.e '.' . Now for second IP 9th character is 9 and for 1st IP its 1 so as 9 is bigger the bigger number is at the bottom of list.
So if you want to still use this algo u can stuff your IPaddress with extra zeros, such that their three digits after each '.'
Or you can construct your own comparator which will separate the all the no after "." then compare all the nos accordingly.

gunjannigam 28 Junior Poster

Thanks, will try the SAVE_DIALOG advice immediatly.

I'm talking about the "Open" and "Cancel" buttons.

There is a checkbox in properties controlButtonsAreShown. You can uncheck it to remove the buttons

gunjannigam 28 Junior Poster

I am using the netbeans gui builder.

I dragged a filechooser onto my frame, and it does almost everything I want it to do.

How do I remove the buttons? I dont need them - the user just has to select a file, or type in a file name, the buttons are unused.

Also, if a user types in a file name in the "File name" Text field, how do I get that file name?

I tried "fileChooser.getSelectedFile()" but that only returns a value if the user has actually highlighted an existing file. The idea is to get the file name the the user entered and create a new file with that name.

Anyone have an idea?

Which buttons are you talking about?
If you want to create a new File with given name then You need to use the SAVE_DIALOG mode (which can be set in Dialog type in properties of that fileChooser) to create a file with the given name

gunjannigam 28 Junior Poster

Hi guys, I'm returning this, it is similar to how you percieve dollars, $"32.95" etc. I calculate it in cents which is an int, but the problem is the second half cuts off the 10s of cents part if the number is less than that. eg/ 32.08. Any ideas ? i know i need an if but i cant think how to write it.

public String toString()
     {  
         return (cents / 100)+ "." + (cents % 100);
     }

You can either do it by using if then else statement by using this

if((cents%100) < 10)
    return (cents / 100)+ "." + "0"+(cents % 100);
else
    return (cents / 100)+ "." + "0"+(cents % 100);

You can also you use a Numberformat class.

import java.text.*;
NumberFormat formatter = new DecimalFormat("0.00");
return (formatter.format(cents/100.0));
gunjannigam 28 Junior Poster

Call paintComponent constructor
Use this as the 1st line of code in paintComponent method

super.paintComponent(g);
gunjannigam 28 Junior Poster

As per my knowledge if you want to import an external API than that API should be present at \jre\lib\ext jar so that the classes are recognised by the javac or g++ compiler.

gunjannigam 28 Junior Poster

Hi,

I am trying Serial Port Communication in Linux using Javacomm API and RxTx. I'm configured RxTx as per the documentation. But I received an error as follows,

Exception in thread "main" java.lang.UnsatisfiedLinkError:com.sun.comm.SunrayInfo.isSessionActive()Z.

Would you help me please..

Did u configure it using this link http://www.agaveblue.org/howtos/Comm_How-To.shtml

I also tried this link and probally got the same message as error.
Which version of Linux are you using. I will suggest that you only use Rxtx API,(instead of using both JavaComm and Rxtx). For installation of that u can dowlnoad the binary from http://rxtx.qbang.org/pub/rxtx/rxtx-2.1-7-bins-r2.zip
and copy RXTXComm.jar to your jre/lib/ext folder and libRxtxSerial.so and libRxtxParallel.so in your jre/lib/i386 folder
This jre folder must be inside your jdk folder.

Also import gnu.io.* instead of javax.comm.* in your code

gunjannigam 28 Junior Poster
gunjannigam 28 Junior Poster

Well Couldnt get completely what you wanted.
Do u want to create a Panel with this image and Radio Button on it?
You can use the paintComponent to paint the image and setBounds method to translate your Button to the exact coordinte you want. But remember for using setBounds method your Layout should be set to null

gunjannigam 28 Junior Poster

(1)You can make you own Color Using Color Class Constructor with RGB Values. Search for Exact Color value you want
You can use new Color(100,149,237); or adjust these values as per your requirement

(2) You can use paint method to paint your image
maybe this can help

import java.awt.*;
import javax.swing.*;
class loginScreen extends JFrame
{
  public loginScreen()
  {
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    ImagePanel panel = new ImagePanel("test.gif");
    panel.add(new JButton("OK"));
    getContentPane().add(panel);
    pack();
    setLocationRelativeTo(null);
  }
  class ImagePanel extends JPanel
  {
    Image img;
    public ImagePanel(String file)
    {
      setPreferredSize(new Dimension(600, 400));
      try
      {
        img = javax.imageio.ImageIO.read(new java.net.URL(getClass().getResource(file), file));
      }
      catch(Exception e){}//do nothing
    }
    public void paintComponent(Graphics g)
    {
      super.paintComponent(g);
      if(img != null) g.drawImage(img,0,0,getWidth(),getHeight(),this);
    }
  }
  public static void main(String[] args){new loginScreen().setVisible(true);}
}
Ezzaral commented: Helpful +25