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

Where is the sale and purchase of Inventory happening ?

gunjannigam 28 Junior Poster

hi
I have a problem regarding calling print() method through main().It asks to pass arguments but i already done so using constructors.Any help in missing statement.

public class ElectricityBill {
	public static void main(String args[]){
    current c1=new current(500,"January");
    current c2=new current(1600,"February");
    
    c1.print(double total,String month);//this is the place i wanna know,how to call print()
    
    
	}
}

class current{
	int usage;
	String month;
	double total;
	
	current(int u,String m){
		usage = u;
		month=m;
	}
	double calculate(int usage){
		double u1=12.50;
		total=usage*u1;
		return total;
	}
	void print(double total,String month){
		System.out.println("Your bill for month "+month+" is "+total);
	}
}

Declare and Initialize total and month that you are passing as argument.

double total=500;
String month = "January";
c1.print(total,month);
gunjannigam 28 Junior Poster

Well I got it done by this code

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author gunjan
 */
public class ShutDown {
    public static void main(String[] args)
    {
        try {
            Runtime.getRuntime().exec("shutdown -h 0");
        } catch (IOException ex) {
            Logger.getLogger(ShutDown.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}

But the problem is that I need to run this code as root or superuser. Is there a way to login as root using Java and then run this code

gunjannigam 28 Junior Poster

I am using Ubuntu 9.04. I want to shutdown my PC using Java, when some Event is called. Please suggest what could be done.

gunjannigam 28 Junior Poster

I am not sure but probably the class you are using isnt defined in your classpath. You might have installed some file which would had only be installed for Eclipse. You might need include the jar file in jre\lib\ext to so that the class is recognized by your command promt

gunjannigam 28 Junior Poster

I have RGB information about the pixels in a line. I need to draw the images in JPEG or PNG or BMP format using these information from the pixels.I dont know how to do this in java. Somebody help me out on how to start solving it out

gunjannigam 28 Junior Poster

alright. My program is like really long but most of the stuff are duplicated so I hope you don't get to confused... scroll them to the button (it's where my new buttons/frames are created.

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

public class RestaurantFirstPage1 {
  final static String LABEL_TEXT = "Welcome to the restaurant rating website";
  /* Frames */
  JFrame frame;
  JFrame homepageFrame;
  JFrame signinFrame;
  JFrame signupFrame;
  JFrame tacobellFrame; 
  JFrame mcdonaldFrame; 
  JFrame arbysFrame;
  JFrame subwayFrame; 
  JFrame burgerkingFrame; 
  JFrame wendysFrame;
  JFrame harveysFrame; 
  JFrame dairyqueenFrame; 
  JFrame newyorkfriesFrame; 
  JFrame pizzapizzaFrame; 
  JFrame kfcFrame;
  /* Panel */ 
  JPanel contentPane;
  JPanel contentPanel; 
  JPanel contentPanel2; 
  /* label */ 
  JLabel label;
  /* first page buttons */ 
  JButton enter; 
  JButton signIn;
  JButton signUp;
  JButton exit;
  /* homepage buttons */ 
  JButton homepage; 
  JButton tacobellButton;
  JButton mcdonaldButton;
  JButton arbysButton; 
  JButton subwayButton; 
  JButton burgerkingButton; 
  JButton wendysButton; 
  JButton harveysButton; 
  JButton dairyqueenButton; 
  JButton newyorkfriesButton;
  JButton pizzapizzaButton; 
  JButton kfcButton;
 
  /*
   * the main page
   */ 
  
  public RestaurantFirstPage1() {
    frame = new JFrame("Restaurant First Page");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    /* Creates the first frame */ 
    contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
    contentPane.setBorder(BorderFactory.createEmptyBorder(50,20,30,20));
    contentPane.setBackground(Color.white);

    label = new JLabel(LABEL_TEXT);
    label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    label.setBorder(BorderFactory.createEmptyBorder(20,50,20,50));
    contentPane.add(label);
    
    /* enter button */ 
    enter = new JButton("Enter");
    enter.setActionCommand("Enter");
    enter.addActionListener(new NextPage());
    enter.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    contentPane.add(enter); 
    
    
    /* sign in button */ 
    signIn = new JButton("Sign In");
    signIn.setAlignmentX(JButton.CENTER_ALIGNMENT);
    signIn.setActionCommand("Sign In");
    signIn.addActionListener(new NextPage());
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    contentPane.add(signIn);
    
    /* sign up button */ 
    signUp = new JButton("Sign Up");
    signUp.setActionCommand("Sign Up");
    signUp.addActionListener(new NextPage());
    signUp.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    contentPane.add(signUp);

    /* exit button */ 
    exit = new JButton("Exit");
    exit.setAlignmentX(JButton.CENTER_ALIGNMENT);
    exit.addActionListener(new Terminate());
    contentPane.add(Box.createRigidArea(new Dimension(0, …
gunjannigam 28 Junior Poster

oh no wonder.. but if i don't use the layout manager would it still display the buttons?

Yaa it will display all the buttons. FlowLayout is already defined as default so if you dont use it still be setting components as per FlowLayout

gunjannigam 28 Junior Poster

oh wait, yeaa ive tried that keep it the same panel but it gives me this error:

1 error found:
[line: 105]
Error: C:\Documents and Settings\HP_Administrator\My Documents\RestaurantFirstPage.java:105: contentPane1 is already defined in firstFrame()

paste your code.

gunjannigam 28 Junior Poster

You are comparing the two string name using == operator. You should use String.equals(); to compare two string. == operator will compare the two string object and will result true only when both the string objects are same.

gunjannigam 28 Junior Poster

What do you mean in one panel? Don't I have it all in one panel? :S

so i guess this layout/code doesn't work with the layouts or do i just have to add some codes to it.

tacobellButton = new JButton("Taco Bell");
      tacobellButton.setActionCommand("TacoBell");
      tacobellButton.addActionListener(this); 
      contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
      JPanel contentPanel = new JPanel(); 
      contentPanel.add(tacobellButton);
      homepageFrame.add(contentPanel);

I your code where you added two buttons you added the second button McDonald to different panel. Add both to same panel. This will show all the buttons. To show where they should be visible, you need to use LayoutManger

gunjannigam 28 Junior Poster

First of all you need to all the buttons in one panel. And then you will get to see all of them
To make it vible at the center you need to use LayoutMangers. Try going through this tutorial. Hope it will help you a lot in future also

gunjannigam 28 Junior Poster

I changed it to JFrame and when i compile there are no errors, but when i run it the error message is exception in thread main java.lang.NoSuchMethodError: main.

Well its working fine for me. TRy to catch the exception using printStackTrace() and then tell which line you are getting exception

gunjannigam 28 Junior Poster

thanks. you are welcome :)

gunjannigam 28 Junior Poster

ahh I don't get it.
sorry D:

can you give me that code?

contentPane = new JPanel(); contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS)); contentPane.setBorder(BorderFactory.createEmptyBorder(50,20,30,20));

something like that? :

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

public class RestaurantFirstPage1 {
  final static String LABEL_TEXT = "Welcome to the restaurant rating website";
  JFrame frame;
  JFrame firstFrame;
  JFrame secondFrame;
  JPanel contentPane;
  JLabel label;
  JButton showButton;
  JButton signIn;
  JButton signUp;
  JButton exit;
  JButton exit2;

  public RestaurantFirstPage1() {
    frame = new JFrame("Restaurant First Page");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
    contentPane.setBorder(BorderFactory.createEmptyBorder(50,20,30,20));
    contentPane.setBackground(Color.white);

    label = new JLabel(LABEL_TEXT);
    label.setForeground(Color.black);
    label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    label.setBorder(BorderFactory.createEmptyBorder(20,50,20,50));
    contentPane.add(label);

    signIn = new JButton("Sign In");
    contentPane.add(signIn);
    signIn.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    signIn.setActionCommand("Sign In");
    signIn.addActionListener(new NextPage());

    signUp = new JButton("Sign Up");
    contentPane.add(signUp);
    signUp.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    signUp.setActionCommand("Sign Up");
    signUp.addActionListener(new NextPage());

    exit = new JButton("Exit");
    contentPane.add(exit);
    exit.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    exit.addActionListener(new Terminate());

    frame.setContentPane(contentPane);

    frame.pack();
    frame.setVisible(true);
  }

    private static void runGUI() {
      JFrame.setDefaultLookAndFeelDecorated(true);

      RestaurantFirstPage1 firstPage = new RestaurantFirstPage1();
    }

    class NextPage implements ActionListener {

    public void actionPerformed(ActionEvent event) {
      String eventName = event.getActionCommand();

      if(eventName.equals("Sign In")) {
        firstFrame();
        frame.dispose();
        frame = null;


      }
      else if(eventName.equals("Sign Up")) {
        secondFrame();
        frame.dispose();
        frame = null;

      }
    }

    private void firstFrame() {
      firstFrame = new JFrame("SignIn");
      firstFrame.setSize(350, 320);
      firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      firstFrame.setVisible(true);

      showButton = new JButton("button testing");
      showButton.setActionCommand("button testing");
      showButton.addActionListener(this);
      JPanel contentPane1 = new JPanel();
      contentPane1.add(showButton);
      firstFrame.add(contentPane1);

    }
    private void secondFrame() {
      secondFrame = new JFrame("SignUp");
      secondFrame.setSize(350, 320);
      secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      secondFrame.setVisible(true);

    }
    }

    class Terminate implements ActionListener {
      public void actionPerformed(ActionEvent event) {
      System.exit(0);
    }
    }


    public static void main(String[] args) {
      javax.swing.SwingUtilities.invokeLater(new Runnable() { …
StarZ commented: helpful thanks +2
gunjannigam 28 Junior Poster

how do I re-edit thread? o_o
anyways this is the code I meant to ask for help:

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

public class RestaurantFirstPage1 {
  final static String LABEL_TEXT = "Welcome to the restaurant rating website";
  JFrame frame;
  JFrame firstFrame;
  JFrame secondFrame;
  JPanel contentPane;
  JLabel label;
  JButton showButton;
  JButton signIn;
  JButton signUp;
  JButton exit;
  JButton exit2; 
  
  public RestaurantFirstPage1() {
    frame = new JFrame("Restaurant First Page");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    contentPane = new JPanel();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
    contentPane.setBorder(BorderFactory.createEmptyBorder(50,20,30,20));
    contentPane.setBackground(Color.white); 
    
    label = new JLabel(LABEL_TEXT);
    label.setForeground(Color.black); 
    label.setAlignmentX(JLabel.CENTER_ALIGNMENT);
    label.setBorder(BorderFactory.createEmptyBorder(20,50,20,50));
    contentPane.add(label);
    
    signIn = new JButton("Sign In");   
    contentPane.add(signIn);
    signIn.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    signIn.setActionCommand("Sign In");
    signIn.addActionListener(new NextPage()); 
                          
    signUp = new JButton("Sign Up");
    contentPane.add(signUp);
    signUp.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    signUp.setActionCommand("Sign Up");
    signUp.addActionListener(new NextPage());
    
    exit = new JButton("Exit");
    contentPane.add(exit);
    exit.setAlignmentX(JButton.CENTER_ALIGNMENT);
    contentPane.add(Box.createRigidArea(new Dimension(0, 15)));
    exit.addActionListener(new Terminate());
  
    frame.setContentPane(contentPane);
    
    frame.pack();
    frame.setVisible(true);
  }

    private static void runGUI() {
      JFrame.setDefaultLookAndFeelDecorated(true);
      
      RestaurantFirstPage1 firstPage = new RestaurantFirstPage1();
    }
    
    class NextPage implements ActionListener { 

    public void actionPerformed(ActionEvent event) {
      String eventName = event.getActionCommand();
      
      if(eventName.equals("Sign In")) {
//        firstFrame(); 
        frame.dispose(); 
        frame = null; 
   
        
      }
      else if(eventName.equals("Sign Up")) {
        secondFrame(); 
        frame.dispose(); 
        frame = null; 

      } 
    } 
    
    private void firstFrame() { 
      firstFrame = new JFrame("SignIn"); 
      firstFrame.setSize(350, 320); 
      firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      firstFrame.setVisible(true);

      showButton = new JButton("button testing"); 
      showButton.setActionCommand("button testing");
      showButton.addActionListener(this); 
      contentPane.add(showButton); 


    } 
    private void secondFrame() { 
      secondFrame = new JFrame("SignUp"); 
      secondFrame.setSize(350, 320); 
      secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      secondFrame.setVisible(true); 
      
    }    
    }
    
    class Terminate implements ActionListener {   
      public void actionPerformed(ActionEvent event) {
      System.exit(0);
    }
    }
    

    public static void main(String[] args) {
      javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          runGUI();
        }
      });
    }
  }

Still you are not adding …

gunjannigam 28 Junior Poster

You are extending/subclassing your class to JApplet class which doesnt have the method used by you. You need to extend JFrame to use

frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gunjannigam 28 Junior Poster

In your firstFrame() and SecondFrame() you havent added any buttons.You added buttons only in frame.When you dispose your frame, your it buttons are lost and there are no buttons any firstFrame and SecondFrame() so they wont showup.
You need to add all the buttons to your new frame firstframe() and secondframe() also.
A alternative slotion as I already told before will be to use different panels. You can have one buttonpanel which is always visible and others panels are swapped and made visible accordingly. In this case you wont need to add buttons everytime

gunjannigam 28 Junior Poster

in Your ActionListener class simply set this frame.setVisble(false) and your other page frame.setVisble(true).

Another option will be to add many panels and make setVible for this panel(false) and setVisible(true) for other panel

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

Hi,

I'm having troubles with my JMenuItems and Jframe. I want that when you click on a JMenuItem the previous JPanel dissapears and the one you clicked for at the JMenuItem will appear. Now, I don't really know how to accomplish this.

Someone said to me I should use the observer design pattern, but I don't know if this will work or not. I did read about the observer pattern and understand what is about. So can this pattern solve my pattern? And how?

Grtz

Use CardLayout or either add all your JPanel in your frame and setVisible false for all and use MenuListener to make the required JPanel visible

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

Plzz Can u explain me in detail !!

I will personally recommend to use JFreeChart API. Its open source, easy and versatile API. U can develop so many types of chart using it. ANd there so many options to categorize your chart. You can get demo source code of JFreeChart line chart online and customize your chart.

But still if you want dont want to use any API than you can write your own small code. Fix the size of your panel. Use Java Graphics2D. Draw a horizontal and a vertical Line as your Axis.Now fix the scale of your graph depending upon your input data and your drawing area. Now if you want a static graph(read all data and display it one go), Simply keep on reading each line from the file and make a line between 2 points between 2 points. If you want a dynamic graph, u can read one line from the file each time, draw a line between 2 this and the previous points and keep on dumping then in a arraylist. Then wait for as much time u want call the repaint method and draw a line between all the points in your arraylist after dumping the new point read from the file

gunjannigam 28 Junior Poster

I am trying to Draw a graph which can read data values from Text files.
In which i want to consider 1st column as X-axis and 2nd as Y-axis.

You can use a charting API. There are many like JFreeChart (my personal favourite), JMathTool, JChart, etc.

You can also develop your own basic code. You need to draw a Axis(just 2 lines) and then map your graph area to pixels. And then reading after each point u simply need to draw a line between points. You need to store all the previous points in some ArrayList and then paint the ArrayList including the newly added points.

gunjannigam 28 Junior Poster
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class cal extends JFrame implements ActionListener
{
	JMenuBar mb;
	JMenu file, help;
	JMenuItem esc, about;
    JButton btn[];
    JLabel lab1 = new JLabel("0");
	JPanel pan1;
	int i;
	final int MAX_INPUT_LENGTH = 20;
	final int INPUT_MODE = 0;
	final int RESULT_MODE = 1;
	final int ERROR_MODE = 2;
	int displayMode;

	boolean clearOnNextDigit;
	double lastNumber;
	String lastOperator;
	
	public cal()
	{
      		super("Calculator");
      		setLayout(new BorderLayout());

           	//creating the menu bar
      		mb = new JMenuBar();
      		setJMenuBar(mb);
      		
      		file = new JMenu("File");
      		esc = new JMenuItem("Exit");
      		file.add(esc);
      		
      		help = new JMenu("Help");
      		about = new JMenuItem("About");
      		help.add(about);
      		
      		mb.add(file);
      		mb.add(help);
      		
      		esc.addActionListener(this);
       	    about.addActionListener(this);
            
		    lab1.setBackground(Color.WHITE);
	        lab1.setOpaque(true);
		    add(lab1,BorderLayout.NORTH);
		    
		    pan1 = new JPanel(new GridLayout(5,4,2,3));
		    btn = new JButton[20];
			     
		    // Create numeric Jbuttons
		    for(i = 0; i < 10 ; i++)
		    {
		    	btn[i] = new JButton(String.valueOf(i));
		    }
		    btn[10] = new JButton("+/-");
		    btn[11] = new JButton(".");
		    btn[12] = new JButton("=");
		    btn[13] = new JButton("/");
		    btn[14] = new JButton("*");
		    btn[15] = new JButton("-");
		    btn[16] = new JButton("+");
		    btn[17] = new JButton("BS");
		    btn[18] = new JButton("C");
		    btn[19] = new JButton("CE");
		    
		    for (i=0; i < btn.length; i++)
		     {
			// set each Jbutton label to the value of index
		      btn[i].addActionListener(this);
		      pan1.add(btn[i]);
		     }
		     add(pan1,BorderLayout.CENTER);
		     
		     for(i=0 ; i < btn.length; i++)
		     {
		     	if(i < 10)
		     	{
		     		btn[i].setBackground(Color.LIGHT_GRAY);
		     		btn[i].setForeground(new Color(64,128,128));
		     	}
		     	else
		     	{
		     		btn[i].setBackground(Color.GRAY);
		     		btn[i].setForeground(Color.BLACK);
		     	}
		     }
		//Add buttons to keypad panel starting at top left
		// First row BS,CE,C,Equal
		     pan1.add(btn[17]);
	       	 pan1.add(btn[19]);
		     pan1.add(btn[18]);
		     pan1.add(btn[12]);
		//second row 1,2,3,Plus
		     for(i=1; i<=3; i++)		
			  {
			    pan1.add(btn[i]);
		      }
		     pan1.add(btn[16]);
		     for(i=4; i<=6; i++)
		      {
			   pan1.add(btn[i]);
		      }
		       pan1.add(btn[15]);
		// Third row 4,5,6,Subtract
		     for(i=7; …
gunjannigam 28 Junior Poster

Maybe you can try this to read your file

File fil = new File(FileName);
FileInputStream fis = null;
    BufferedInputStream bis = null;
    DataInputStream dis = null;

    try {
      fis = new FileInputStream(fil);

      // Here BufferedInputStream is added for fast reading.
      bis = new BufferedInputStream(fis);
      dis = new DataInputStream(bis);

      //Then you can write your code
      fis.close();
      bis.close();
      dis.close();
}catch(Exception e){e.printStackTrace();}

Or you can try this to read

FileInputStream fstream = null;
        try
        {
            File fil = new File(FileName);
            fstream = new FileInputStream(fil);
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader out1 = new BufferedReader(new InputStreamReader(in));

//Write your code

out1.close();
in.close();

}catch (Exception ex) {ex.printStackTrace();}

And check if still there is a problem of ?? in ouput

gunjannigam 28 Junior Poster

I have one more question:
How to change this code so I could name the table:
For example create a table: "Table1", because here the table is already named.

// the 1st case: create a table
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable);
String tableName = "Table1";

Also how to add your own data into the table, not random numbers like in this code.
and this:

// second case: enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }

Help with a little example code please?
THANK YOU!!!!

for(int i=0; i<25; i++)
            {
              int id = 123; // Here you can assign whatever ID you want
              String strid =  String.valueOf(id); 
              String name = "Ram"; //Here you can assign whatever name you want
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     strid + ", '" + name + "')";
              s.execute(addRow);
            }
gunjannigam 28 Junior Poster

I have a code in Java 3D through which I can draw a static(all verticies are known before hand) 3D curve.
But I want to draw a dynamic(vertices specified at they at run time) curve, and the number of vertices keeps on adding up.

This is the code for static curve.

public Shape3D createCurve(){

    int steps = 200;
    
    Point3d[] coords = new Point3d[steps];
    for (int i = 0; i < coords.length; i++) {
        coords[i] = new Point3d(x,Math.sin(x*10),Math.cos(x*10));
        x += 0.01;
    }
    int[] strip = {steps};
    LineStripArray lsa = new LineStripArray(steps, LineStripArray.COORDINATES|LineStripArray.COLOR_3, strip);
    Color3f colors[] = new Color3f[steps];        //array of colors
      for(int v = 0; v < steps; v++)
      {            //set the remaining colors
          colors[v] = new Color3f(Color.ORANGE);
      }
    lsa.setColors(0, colors);
    lsa.setCoordinates(0, coords);
    Appearance app = new Appearance();
    app.setLineAttributes(new LineAttributes(1.5f, LineAttributes.PATTERN_SOLID, true));

        return new Shape3D(lsa, app);
    }

This curve is added to a BranchGroup() and then the group is compiled. For dynamic curve, I thought of increasing the no of steps using Timer and than generating new curve and then remove old from the TransformGroup and adding the new one.But that gives an exception

Exception in thread "AWT-EventQueue-0" javax.media.j3d.RestrictedAccessException: Group: only a BranchGroup node may be removed
        at javax.media.j3d.Group.removeChild(Group.java:350)

Please explain how to draw dynamic curve in Java 3D

gunjannigam 28 Junior Poster

Is it possible to output a variable and/or a string to a text file?

Yes you can easily do it.
http://java.sun.com/docs/books/tutorial/essential/io/
http://www.roseindia.net/java/beginners/java-write-to-file.shtml

gunjannigam 28 Junior Poster

Could you post the rest of your code? I compiled this myself and it seemed to work, mind you it only read/printed the first line of the file.

Sorry I dont have java currently installed at my home.So cant check it right now. I am posting it now just compile it and check and still if some error is there will get back to you by monday after weekend

public static void main(String[] args) 
	{
		try
		{
			Scanner amostra=new Scanner(new File ("file"));
			while(amostra.hasNext())
			{
				String linha =amostra.nextLine();
				String[] ar = linha.split(" ");
				for(int i=0;i<ar.length;i++)
					System.out.println(ar[i]);
			}
		}catch(Exception e){e.printStackTrace();}
			
	}
gunjannigam 28 Junior Poster

Hi everyone.
So I get the code going now the question is:
How to make a menu in Java code?
For example:
1.create table
2.insert into table
3.select fro table
4.delete table...
Which will you choose: ex.1
and creates table
I mean like switch case in C++

import java.sql.*;

public class dbAccess
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            String database = 
              "jdbc:odbc:Driver:myDB";
            Connection conn = DriverManager.getConnection(database, "", "");
            Statement s = conn.createStatement();
            
            // the 1st case: create a table
            String tableName = "myTable" + String.valueOf((int)(Math.random() * 1000.0));
            String createTable = "CREATE TABLE " + tableName + 
                                 " (id Integer, name Text(32))";
            s.execute(createTable); 
            
            // second case: enter value into table
            for(int i=0; i<25; i++)
            {
              String addRow = "INSERT INTO " + tableName + " VALUES ( " + 
                     String.valueOf((int) (Math.random() * 32767)) + ", 'Text Value " + 
                     String.valueOf(Math.random()) + "')";
              s.execute(addRow);
            }
            
            // this should be third case:Fetch table
            String selTable = "SELECT * FROM " + tableName;
            s.execute(selTable);
            ResultSet rs = s.getResultSet();
            while((rs!=null) && (rs.next()))
            {
                System.out.println(rs.getString(1) + " : " + rs.getString(2));
            }
            
            // this should be the 4: drop the table
            String dropTable = "DROP TABLE " + tableName;
            s.execute(dropTable);
            
            // close and cleanup
            s.close();
            conn.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

Help anyone???

If you want a command line based menu, its similar to C++
Use print staements as you do in C++ and take the input
by …

gunjannigam 28 Junior Poster

This case can have 2 cases.
1) Delete all the occurence of given word
2)Delete only a given occurence(mostly first) of given word

You have to split the input sentence using String.split() method. It will result into a array of Sring, containing all your words. Now compare all your words with the given input word. If a match is not there append the word into a StringBuilder along with a space. This will remove all the occuerence. If you want to delete a particular instance. Count the no of instance and break from the loop accordingly

gunjannigam 28 Junior Poster

Sorry i m here again.... I am using JApplet in program.
While writing i mentioned it as applet but in program I am using JApplet.

Figured out that your buttons TE1, TE2, TE3 are not listening
Sorry cant get what the actual problem in your code. But just by hit n trail by using Buttons instead of JButtons all your buttons are Listening

gunjannigam 28 Junior Poster

Use Buttons instead of JButtons as you are using an applet

gunjannigam 28 Junior Poster

Thanks for your help but still the buttons are not working. Now i am creating each button separately (removed array) still buttons are not working.
my code is too large to post. what do i do?
Need help.

thanking you.

public void first_te(Graphics g22, int i){
		
		JButton te1 = new JButton("TE1");
		getContentPane().add(te1);
		setLayout(null);
		te1.setBounds(250,600,80,40);
		te1.addActionListener(wave.this);
		te1.setActionCommand("TE1");
		System.out.print("first_te");
	}

public void actionPerformed(ActionEvent e){
    		 try{
    				
 				if(e.getActionCommand().equals("TE1")){
 					System.out.print("first_te");
 					cnt=4;	
 			 	
    	 }
    		 }catch(Exception ae){ ae.printStackTrace();}
    	 }

		    	 }
    	 );

my applwt contains two panels
1. "getContentPane()" panel
2. fieldPanel(which contains label and textfield) with grid layout.

If you want you can attach your code here.
Secondly just wondering what is this wave? You are adding wave.this to the actionListener

gunjannigam 28 Junior Poster

public class example{
This is what i have, I am just throwing things together to try and make it work...


public class Movie
{

private int rank;
private String title;

public Movie(int rank, String title)
{
this.rank = rank;
this.title = title;
}

}
public void main (String [] args)
{

Movie movie[] = new Movie[5];
movie[0] = new Movie(5, "Top Gun");
movie[1] = new Movie(4, "Boondock Saints");
movie[2] = new Movie(3, "School Of Rock");
movie[3] = new Movie(2, "Old School");
movie[4] = new Movie(1, "Full Metal Jacket");

}
private void printArray(movie[] inventory){
for (int i = 0; i < inventory.length; i++){
System.out.println(inventory);
}
}
public void sortIntArray (int [] movie)
{


int rating;

int tem;

for (int a = 0; a < movie.length - 1; a++)
{
for (rating = 0; rating < movie.length - 1; rating++)
{
if (movie [rating] > movie [rating + 1])
{
tem = movie [rating];
movie [rating] = movie [rating + 1];
movie [rating + 1] = tem;
}
}
}
}
}

Stop Spamming the forum by creating 3 threads for one problem.

Now the algo which you are using for sorting has time complexity of n^2, therefore it is not advised. If you still want to use it for your case then …

gunjannigam 28 Junior Poster

Hey guys,

I have this assignment due soon and need some help with it. I don't want the solution handed to me, but I also don't want some extremely vague answers either. I want to learn from this.

Basically, what I am making is a simple applet, that has 3 buttons across in the NORTH section of a BorderLayout, and a Panel in the CENTER section.

The buttons are as follows:

  • Paint Brush
  • Line Tool
  • Rectangle Tool

It is a paint program as you have guessed. Now, I have gotten it to work only so far. I can click on one of the buttons, and then I can use the tool described, and then when I click on another different button, I can use that tool, but the drawing already there goes. Like a repaint or something.

Here is the code I have so far, I know what the problem is, I just don't know how to get around it. The problem is that I am creating instances of the tools class, and then adding it to the panel after I remove the others. It doesn't work otherwise.

import java.applet.Applet;
import java.awt.*;
import java.awt.Event;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JavaDraw extends Applet implements ActionListener {

	private Button paintBrush;
	private Button lineTool;
	private Button rectangleTool;
	private BorderLayout layout = new BorderLayout();								// Declaring the layout of the app
	private Panel buttonsMenu = new Panel(); 										// Creat a new panel for the buttons
	private Panel drawingPanel = new …
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

hi
Thanks for your reply. but i m here again to trouble you more...
Please check am I doing it correctly......
because it is giving me error as "Syntax error, insert ";" to complete ClassBodyDeclarations" Please help me ... Its very urgent for me
Thanking you...

for(int k=1, j = 0;k<=temode;k++,j++){
	    	  msg="TE"+k;
	    	 //JPanel fieldPanel = new JPanel(new GridLayout(1,2));
	    	 //JButton k1;
	    	 JButton[] buttons= new JButton[temode];
	    	 buttons[j]=new JButton(msg);
	    	 getContentPane().add(buttons[j]);
	    	 buttons[j].setBounds(50+(100*k),600,80,40);
	    	 setLayout(null);//(new GridBagLayout());
	    	 //buttons[j].addActionListener(wave.this);
	    	 buttons[j].addActionListener(new ActionListener(){ public void actionperformed{
	    		 cnt=3+k;
	    	 }}
	    	 );
	    	 
	    	 
	    	 buttons[j].setActionCommand(msg);
	    	 
		 }

Line no 11 should be

buttons[j].addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){
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

scanner seems too complex. pls let me know how to do it in the simplest form.

Scanner is just to take the input from the user the no of lines required. If you want it to do in a simple way without scanner you can fix the no of lines such as 5.

int num = 5;//No of Lines
        for(int i=0;i<num;i++)
        {
            for(int j=0;j<i;j++)
                System.out.print(" "); 
            for(int j=0;j<(2*(num-i)-1);j++)
                System.out.print("*");
            System.out.println();
        }
gunjannigam 28 Junior Poster
System.out.println("Enter Number of rows you want.");
        Scanner br = new Scanner(System.in);
        int num = br.nextInt();
        for(int i=0;i<num;i++)
        {
            for(int j=0;j<i;j++)
                System.out.print(" ");
            for(int j=0;j<(2*(num-i)-1);j++)
                System.out.print("*");
            System.out.println();
        }
gunjannigam 28 Junior Poster

The toBinaryString and the other methods are static, so you don't need to create a new Integer object. What's the point of using the object created if you are going to pass as parameter the number used to create it?

Thnks. So the code should be

Scanner br = new Scanner(System.in);
        int num = br.nextInt();
        System.out.println(Integer.toBinaryString(num));
        System.out.println(Integer.toOctalString(num));
        System.out.println(Integer.toHexString(num));