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

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

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

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

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

Remove line 81 to 88( the write code)
Edit line where u write to file as

outputStream.println(seatList.get(count)?1:0);

Here is the complete code of your ReservationSystem

package airlinereservationsystem;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.io.PrintWriter;
import java.io.FileNotFoundException;
import java.util.ArrayList;



public class ReservationSystem extends JFrame implements ActionListener
{
    private int SC = 12;
    private JLabel userInstructions = new JLabel("Click the button" +
            " representing the seat you want " +
        "to reserve the seat");
    private JButton[] buttonArray = new JButton[12];
    private JButton exitButton = new JButton("Click to Exit");
    private ArrayList<Boolean> seatList = new ArrayList<Boolean>(SC);
    String fileName = "c:/temp/projectData.text";



    public ReservationSystem()
    {
        super("Air Maybe Airline Reservation System");
        //addWindowListener(new WindowDestroyer( ));
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = getContentPane( );
        contentPane.setLayout(new BorderLayout( ));
        JPanel InstructionsPanel = new JPanel( );
        JPanel buttonPanel = new JPanel( );
        JPanel exitPanel = new JPanel( );
        //add listener to the exit button
        exitButton.addActionListener(this);


        InstructionsPanel.add(userInstructions);
        contentPane.add(InstructionsPanel, BorderLayout.NORTH);
        buttonPanel.setLayout(new GridLayout(4,3));


        for (int i=0;i<SC;i++)
        {
            buttonArray[i] = new JButton("Seat " + (i+1));
            buttonArray[i].addActionListener(this);
            buttonPanel.add(buttonArray[i]);
            seatList.add(i, true);
        }
        contentPane.add(buttonPanel,BorderLayout.CENTER);
        exitPanel.add(exitButton);
        contentPane.add(exitPanel,BorderLayout.SOUTH);
        pack();

    }

    @SuppressWarnings("static-access")
public void actionPerformed(ActionEvent e)
{
    String confirm = "Are you sure you want to book this seat?";
        int write;


    for (int i = 0; i < SC; i++)
    {
       if (e.getActionCommand( ).equals("Seat " +(i + 1)))
           {
               int choice = JOptionPane.showConfirmDialog(null, confirm, "Confirm",
                JOptionPane.YES_NO_OPTION);
               if(choice == JOptionPane.YES_OPTION)
               {
                   buttonArray[i].setText("Booked");
                   seatList.set(i, false);

                }

           }
       if (e.getActionCommand( ).equals("Booked"))
           {

                JOptionPane.showMessageDialog(null, "This seat is already booked. Please …
TotalHack commented: Very helpful. Solved my issue. +0
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