cgeier 187 Junior Poster

Probably a database lock issue. Make sure you are closing your connection after using it. Better yet, use a "using" statement.

Also, make sure you don't have the file open in Access. Access is not a DBMS, it is a database file and doesn't support multiple connections--it is single-user. When the database is in use, you will see a ".laccdb" file in the directory. 'l' stands for lock.

using (OleDbConnection  CONN = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Vendors.accdb;"))
{

                       ....

}
cgeier 187 Junior Poster

Here is a post that fills a combobox from a database. This may work for you.

Fill combobox from database

cgeier 187 Junior Poster

Where are you clearing the items? It should be

OleDbDataReader CMBRdr = DBcmd.ExecuteReader();           

//add it here
PhoneCombo.Items.Clear();

while (CMBRdr.Read())
{
GagaCode commented: that did get the job done +0
cgeier 187 Junior Poster

Try clearing the PhoneCombo combobox before adding the items.PhoneCombo.Items.Clear()

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Use a keyboard hook. Click Here for an article about mouse hooks and keyboard hooks.

cgeier 187 Junior Poster

You probably aren't going to receive many responses without posting your code.

cgeier 187 Junior Poster

You probably need to add this after line 23:

cmd = New SqlCommand()

so your code will be:

conn = New OleDbConnection(Get_Constring)
conn.Open()

cmd = New SqlCommand()
cmd.Connection = conn

but it is hard to know for sure because you didn't post the rest or your variable declarations.

Also, add this to your Try-Catch:

Catch ex As System.Data.OleDb.OleDbException
    MsgBox(ErrorToString)
cgeier 187 Junior Poster

This post may help you: Click Here

cgeier 187 Junior Poster

I think Reverend Jim found your error. An update to my post. I incorrectly converted to decimal. Line 7 in "Usage" should be Decimal.TryParse(TextBox1.Text, myVal1) instead of myVal1 = Convert.ToDecimal(TextBox1).

Also, you may consider doing some error handling:

    Dim sqlText as String
    Dim sqlCmd As SqlCommand

    Try

        .......

        sqlText = @"INSERT INTO myTable(col1, col2) VALUES(@myVal1, @myVal2)"

        .......

    Catch ex As System.Data.SqlClient.SqlException
            Console.WriteLine(ex.Message + " (SQL: " + query + ")")

            'if using OleDb
    Catch ex As System.Data.OleDb.OleDbException
        Console.WriteLine(ex.Message + " (SQL: " + sqlText + ")")

    Catch ex As Exception
        Console.WriteLine(ex.Message + " (SQL: " + sqlText + ")")
    Finally
        sqlCmd.Dispose()
    End Try
cgeier 187 Junior Poster

I left out some things in my previous post. Try this:

Add Imports System.Data.SqlClient

    Private Sub insertMyTable(ByRef conn As SqlConnection, ByVal myVal1 As Decimal, ByVal myVal2 As String)

        Dim sqlCmd As SqlCommand
        Dim sqlText As String

        If (conn.State <> System.Data.ConnectionState.Open) Then
            conn.Open()
        End If

        sqlCmd = New SqlCommand()

        sqlText = @"INSERT INTO myTable(col1, col2) VALUES(@myVal1, @myVal2)"
        sqlCmd.Connection = conn
        sqlCmd.CommandText = sqlText

        Dim paramName0 As SqlParameter
        paramName0 = New SqlParameter()

        paramName0.SqlDbType = SqlDbType.Decimal
        'paramName0.SqlDbType = SqlDbType.Float
        'paramName0.SqlDbType = SqlDbType.Int
        'paramName0.SqlDbType = SqlDbType.Money
        paramName0.Direction = ParameterDirection.Input
        paramName0.Value = myVal1
        sqlCmd.Parameters.Add(paramName0)

        Dim paramName1 As SqlParameter
        paramName1 = New SqlParameter()
        paramName1.SqlDbType = SqlDbType.VarChar
        paramName1.Direction = ParameterDirection.Input

        If (myVal2 Is Nothing) Then
            paramName1.Value = DBNull.Value
        Else
            paramName1.Value = myVal2
        End If

        sqlCmd.Parameters.Add(paramName1)

        sqlCmd.ExecuteNonQuery()
    End Sub

Usage:

        Dim conn As SqlConnection
        conn = New SqlConnection("Server=GEN-PC;Data Source=GEN-PC\SQLEXPRESS;Initial Catalog=Brgy;Integrated Security=True;")

        Dim myVal1 As Decimal
        Dim myVal2 As String

        myVal1 = Convert.ToDecimal(TextBox1)
        myVal2 = TextBox2.Text

        insertMyTable(conn, myVal1, myVal2)

Alternatively you could use sqlCmd.Parameters.AddWithValue("@myVal1", myVal1). The important thing is to make sure "myVal1" is the correct data type before passing it to the statement. This version may cause implicit data conversions during insert which may cause performance issues.

cgeier 187 Junior Poster

You're still passing "string" data.

    Private Sub insertMyTable(ByRef conn As SqlConnection, ByVal myVal1 As Decimal, ByVal myVal2 As String)

        Dim sqlCmd As SqlCommand

        Dim sqlText As String

        sqlCmd = New SqlCommand()

        sqlText = @"INSERT INTO myTable(col1, col2) VALUES(@myVal1, @myVal2)"

        Dim paramName0 As SqlParameter
        paramName0 = New SqlParameter()

        paramName0.SqlDbType = SqlDbType.Decimal
        'paramName0.SqlDbType = SqlDbType.Float
        'paramName0.SqlDbType = SqlDbType.Int
        'paramName0.SqlDbType = SqlDbType.Money
        paramName0.Direction = ParameterDirection.Input
        paramName0.Value = myVal1
        sqlCmd.Parameters.Add(paramName0)

        Dim paramName1 As SqlParameter
        paramName1 = New SqlParameter()
        paramName1.SqlDbType = SqlDbType.VarChar
        paramName1.Direction = ParameterDirection.Input
        paramName1.Value = myVal2
        sqlCmd.Parameters.Add(paramName1)

        sqlCmd.ExecuteNonQuery()
    End Sub
cgeier 187 Junior Poster

I'm not an expert in this, but have you checked "Local Security Policy?

  • Control Panel
  • Administrative Tools
  • Local Security Policy
  • Security Settings
  • Local Policies
  • Security Options (and perhaps "User Rights Assignment")

Check the event logs:

  • Control Panel
  • Administrative Tools
  • Event Viewer
  • Applications and Services Log
  • Microsoft
  • Windows
  • NTLM
  • Operational

and

  • Control Panel
  • Administrative Tools
  • Event Viewer
  • Windows Logs
  • Security

Can you be more specific as to what you are clicking on?

cgeier 187 Junior Poster

Does your database use constraints? Do you have a database diagram?

cgeier 187 Junior Poster
  • Click "Start"
  • Select "Control Panel"

If "View by" is "Category":

  • Click "Network and Internet"
  • Click "Network and Sharing Center"
  • Click on "Set up a new connection or network"

If "View by" is "Large icons" or "Small icons":

  • Click "Network and Sharing Center"
  • Click on "Set up a new connection or network"

or

  • Click "Start" and type "vpn" in the "search programs and files" box.
cgeier 187 Junior Poster

Also, you may Click Here to see about checking if the column allows nulls ("AllowDBNull"). It didn't seem to work for an Access db when I tried it though--AllowDBNull always seemed to be true.

cgeier 187 Junior Poster

If you have the ability to modify the database, you could change "Required" to "false" for the column, or assign a default value.

Alternatively, you could programmatically assign a default value. See below for an example:

*Note: Need using System.Data.OleDb; statement.

private static OleDbConnection dbConn = null;
static string connectStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Vendors.accdb;";




    public static void InsertAddressBookMainTbl(ref OleDbConnection dbConn, string Country, string State)
    {
        OleDbCommand sqlCmd = null;
        string sqlText = string.Empty;
        string msg = string.Empty;

        try 
        {
            if (dbConn == null)
            {
                dbConn = new OleDbConnection(connectStr);
            } //if 

            if (dbConn.State != System.Data.ConnectionState.Open)
            {
                dbConn.Open();
            } //if 

            sqlCmd = new OleDbCommand();
            sqlText = @"INSERT INTO AddressBookMain(Country, State)
                            VALUES(@Country, @State)";

            sqlCmd.CommandText = sqlText;
            sqlCmd.Connection = dbConn; 

            OleDbParameter paramName0 = new OleDbParameter();
            paramName0.ParameterName = "@Country"; 
            paramName0.OleDbType = OleDbType.VarChar; 
            paramName0.Direction = ParameterDirection.Input; 
            //paramName0.Value = (object)Country ?? DBNull.Value; 

            //if the value is null or empty
            //the value will be "unavailable"
            paramName0.Value = (object)Country ?? "unavailable"; 
            sqlCmd.Parameters.Add(paramName0); 

            OleDbParameter paramName1 = new OleDbParameter();
            paramName1.ParameterName = "@State"; 
            paramName1.OleDbType = OleDbType.VarChar; 
            paramName1.Direction = ParameterDirection.Input; 
            //paramName1.Value = (object)State ?? DBNull.Value; 

            //if the value is null or empty
            //the value will be "unavailable"
            paramName1.Value = (object)State ?? "unavailable"; 
            sqlCmd.Parameters.Add(paramName1); 

            sqlCmd.ExecuteNonQuery();
        } //try
        catch(System.Data.OleDb.OleDbException ex)
        {
            msg = "ERROR: InsertAddressBookMainTbl: " + ex.Message + System.Environment.NewLine + System.Environment.NewLine;
            Console.WriteLine(msg);
            throw ex;
        } //catch
        catch(Exception ex)
        {
            msg = "ERROR: InsertAddressBookMainTbl: " + ex.Message + System.Environment.NewLine + "SQL:" + sqlText + System.Environment.NewLine;
            Console.WriteLine(msg);
            throw ex;
        } //catch
        finally
        {
            if (sqlCmd != null)
            {
                sqlCmd.Dispose();
            } //if
        } //finally
    } //InsertAddressBookMainTbl
GagaCode commented: a great answer i did not use the same function but it really helped me alot to find the answer thank you for the second time +0
cgeier 187 Junior Poster

Are you trying to detect these events on your form? If so, here's an example:

To use the example:

  • Add a MenuStrip named: menuStrip1
  • Add a ToolStripMenuItem named: File
  • Add a ToolStripMenuItem named: Close

  • Add "MouseDown" and "MouseUp" events

        private void closeToolStripMenuItem_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Console.WriteLine("Left mouse down.");
            }//if
        }
    
        private void closeToolStripMenuItem_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                Console.WriteLine("Left mouse up.");
            }//if
        }
    
cgeier 187 Junior Poster

On your combobox, use either event "SelectedValueChanged" or "SelectedIndexChanged".

SelectedValueChanged

        private void EMP_CB_SelectedValueChanged(object sender, EventArgs e)
        {
            Console.WriteLine("ValueMember A: " + EMP_CB.ValueMember.ToString() + " DisplayMember A: " + EMP_CB.DisplayMember.ToString());

            //---------------------------
            //Get data for selected item
            //---------------------------
            DataRow selectedDataRow = ((DataRowView)EMP_CB.SelectedItem).Row;
            int empId = Convert.ToInt32(selectedDataRow["EMPCODE"]);
            string empName = selectedDataRow["EMPNAME"].ToString();

            Console.WriteLine("empId A: " + empId + " empName A: " + empName);
            Console.WriteLine();
        }

SelectedIndexChanged

        private void EMP_CB_SelectedIndexChanged(object sender, EventArgs e)
        {
            Console.WriteLine("ValueMember B: " + EMP_CB.ValueMember.ToString() + " DisplayMember B: " + EMP_CB.DisplayMember.ToString());

            //---------------------------
            //Get data for selected item
            //---------------------------
            DataRow selectedDataRow = ((DataRowView)EMP_CB.SelectedItem).Row;
            int empId = Convert.ToInt32(selectedDataRow["EMPCODE"]);
            string empName = selectedDataRow["EMPNAME"].ToString();

            Console.WriteLine("empId B: " + empId + " empName B: " + empName);
            Console.WriteLine();
        }

The code is the same inside both.

Taken from: Here and Here

GagaCode commented: that One Answered it +0
cgeier 187 Junior Poster

Where is the output? Were you required to make all of those items menu items? It doesn't seem very user-friendly.

cgeier 187 Junior Poster

Read more about classpath. classpath Documentation

From the documentation:

...Multiple path entries are separated by semi-colons....

The default class path is the current directory. Setting the CLASSPATH variable or using the -classpath command-line option overrides that default, so if you want to include the current directory in the search path, you must include "." in the new settings.

Classpath entries that are neither directories nor archives (.zip or .jar files) nor '' are ignored.

Also, I think that in your first post, the colon in -classpath should be a semi-colon

cgeier 187 Junior Poster

My C++ is a bit rusty, but I think that it may be because you are comparing a character array to a character. Which means that it will point to the first position in the array (I think). Line 4 should probably be

while(buffer[a] != '\0')
cgeier 187 Junior Poster
cgeier 187 Junior Poster

Because it's not a TimeSpan. Use DateTime.Now.TimeOfDay. That is if ts1 is of type TimeSpan.

cgeier 187 Junior Poster

Which "Java" did you install? The JRE or the JDK? I think that the JDK includes the JRE, but I'm not sure. You can also try to install the JRE.
http://java.sun.com/javase/downloads/index.jsp

Look for "Java SE Development Kit (JDK)".
It looks like the current one is "JDK 6 Update 16".

Make sure to choose "Platform: Windows x64".

After installing Java JDK and JRE, reboot and then re-install TextPad.

Something else you might check is to make sure that the "Java JDK" is in your Windows path.

cgeier 187 Junior Poster

Did you install the Java JDK before installing textpad? I would recommend using NetBeans, it's a free download and can save a lot of programming time.

cgeier 187 Junior Poster

Check out the documentation for the scanner class.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html

It will throw "NoSuchElementException" if no line was found. If you don't haven't learned about exception handling yet, I would use "hasNext".

int myInt = 0;
String myString = "";

Scanner in = new Scanner(System.in);
in.useDelimiter("\n");

if (in.hasNextInt()){
     //read in int value
     myInt = in.nextInt();
}//if
else if (in.hasNext()){
     //read in String value
     myString = in.next();
}//else if
cgeier 187 Junior Poster

Just change the delimiter.

Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
cgeier 187 Junior Poster

Here's a possible solution. Not sure what you are trying to accomplish, but this sounds like it should do it. There are probably better options.

int i;
String myNumberAsString;
myNumberAsString = Integer.toString(i);

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#toString(int)

Then you can use the String function "charAt".

int indexNumber;
char desiredDigit;
String myDigitStr;
int myDigitInt;

desiredDigit = myNumberAsString.charAt(indexNumber);
//optional: convert back to an int
//convert back to String first
myDigitStr = Character.toString(desiredNumber);
//then, convert String back to int
myDigitInt = Integer.parseInt(myDigitStr);

System.out.println(desiredDigit);
jen140 commented: Thanks =) +1
cgeier 187 Junior Poster

The documentation for BufferedReader states the following ..."Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached." When you reach the end of the file, the value is "null".

http://java.sun.com/j2se/1.5.0/docs/api/java/io/BufferedReader.html#readLine()

As Agni said, tmp is null which is why you are getting the NullPointerException. It happens because you try to do the following when tmp = null:

int letters = tmp.length();

You can use an "if" statement as Agni mentioned or just combine lines 31 and 32 as follows:

while ((tmp=br.readLine()) != null){
cgeier 187 Junior Poster

Change the following line from:

Scanner number = new Scanner ( System.in );

To:

static Scanner number = new Scanner ( System.in );

OR better yet, just move it inside of the main method:

public static void main(String[] args)
{
     Scanner number = new Scanner ( System.in ); 
     int firstValue;

     System.out.print( "Please enter time in hours:" );
     firstValue = number.nextInt();
}

See my some of my posts in the following article on how to do error checking with scanner:
http://www.daniweb.com/forums/post998852.html#post998852

Also see the following article about using "static":
http://java.sun.com/docs/books/tutorial/java/javaOO/classvars.html

Teethous commented: Super helper. +1
cgeier 187 Junior Poster

You almost got it. You just need to get rid of a bunch of the following statements:

randomNumber = ((int)(0+ Math.random()* 11));

It really should only exist in one place. You can get rid of the rest of them.

for(int counterTrials = 0; counterTrials < numberOfRolls; counterTrials++)          
{            
     randomNumber = ((int)(0+ Math.random()* 11));

     if (randomNumber == 1)                
     {                    
          counter1++;
     }             

     if (randomNumber == 2)                
     {                    
          counter2++;                 
     }    

      ....
}

Or better yet, change to "else-if" statements. There's no need to check 11 "if" statements each time. If you use "else if", it only checks until it finds the one that satisfies the expression.

for(int counterTrials = 0; counterTrials < numberOfRolls; counterTrials++)          
{            
     randomNumber = ((int)(0+ Math.random()* 11));

     if (randomNumber == 1)                
     {                    
          counter1++;
     }             

     else if (randomNumber == 2)                
     {                    
          counter2++;                 
     }    

     else if (randomNumber == 3)                
     {                    
          counter3++;                 
     }

      ....
}

I guess this could be considered a nested statement (obviously not a nested for loop though), because you could re-write it as:

for(int counterTrials = 0; counterTrials < numberOfRolls; counterTrials++)          
{            
     randomNumber = ((int)(0+ Math.random()* 11));

     if (randomNumber == 1)                
     {                    
          counter1++;
     }//if             

     else{         
          if (randomNumber == 2)                
          {           
               counter2++;
          }//if                 
          else 
          {
               if (randomNumber == 3)                
               {           
                    counter3++;
               }//if 

                  .....
          }//else
     }//else    

     
}
VernonDozier commented: Good posts on this thread. +28
cgeier 187 Junior Poster

Another problem you have though, is that the only for loop that is ever executed is the first one because counterTrials = numberOfRolls after the first loop is finished.

Check it out:

int counterTrials = 1;

for(int side1 = 0; counterTrials <= numberOfRolls; counterTrials++)
{
     //it doesn't matter what we do in here because counterTrials will still be incremented
}

for(int side2 = 0; counterTrials <= numberOfRolls; counterTrials++)
{
     //it doesn't matter what we do in here because counterTrials will still be incremented
}

Also, "int side1 = 0" is supposed to be an initialization value for the loop. It doesn't really do anything after the first iteration though.

for(int side1 = 0; side1 <= numberOfRolls; side1++)
{
     //it doesn't matter what we do in here because counterTrials will still be incremented
}

In your code, it doesn't do anything except take up memory. You may as well write it as follows:

for(; counterTrials <= numberOfRolls; counterTrials++)
{
     //it doesn't matter what we do in here because counterTrials will still be incremented
}

So if we specify numberOfRolls = 1000, we get the following:
I'm going to substitute in the values for the variables,

For loop 1 (side1):
            counterTrials   numberOfRolls    increment counterTrials
Round 1:    for (1   <=    1000;                     1+1)
Round 2:    for (2   <=    1000;                     2+1)
Round 3:    for (3   <=    1000;                     3+1)

                                 ...
Round 999: for (999    <=    1000;            999+1)
Round 1000: for (1000  <=    1000;        1000+1)

After for loop 1 completes, counterTrials …

cgeier 187 Junior Poster

FYI: Indenting for loops does not make them nested. In order to be nested, one for loop must be inside another. If you look at VernonDozier's example you see a nested for loop. Here's another example with 3 for loops that are nested. Notice how one for loop is contained inside the other.

//for loop 1
for (int i = 0; i < 10; i++)
{
     //for loop 2
     for (int j=0; j < 10; j++)
     {
          //for loop 3
          for (int k=0; k < 10; k++)
          {

          }//end for loop 3
     }//end for loop 2
}//end for loop 1

To fix the problem of printing 0.0%, you need to change your print statements.

Original:

System.out.print("\n1s " + "                      " + (double) (counter1/numberOfRolls * 100) + "%");

Change to:

System.out.print("\n1s " + "                      " +  (double)counter1/(double)numberOfRolls * 100.0 + "%");

Notice how I cast each variable to double and change "100" to "100.0".
I don't think that it is a good idea to get into a habit of doing math inside print statements though. If you ever try to do addition you are going to run into problems, because "+" is also a String concatenation operator. Instead do the following:

double myValue;
myValue = (double)counter1/(double)numberOfRolls * 100.0;
System.out.print("\n1s " + "                      " +  myValue + "%");
cgeier 187 Junior Poster

You received this error because you used "x", but haven't yet assigned it a value.

int x;

//x is being used, but hasn't been assigned a value yet
selectedJava = x;

. Your code has other issues though. It throws a "ClassCastException" (thrown "if the search key in not comparable to the elements of the array").

See http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#binarySearch(int[],%20int)

for more info.

The code below should work.

import java.util.*;
import javax.swing.*;

public class JavaArray
{
 public static void main(String[] args)
 {
  String[] topJava = {"Challenging", "Fun", "Computer stuff",
"Learning new stuff", "Interesting", "Make my own programs",
"Solve my own problems", "Have jgrasp to help", "Lots of books to help", "Tutorials online to help"};
  int[] choices = {1,2,3,4,5,6,7,8,9,10};
  String strSelectedJava;
  int selectedJava;
  int x;
  
  strSelectedJava = JOptionPane.showInputDialog(null,"Choose a number between 1 and 10");
  selectedJava = Integer.parseInt(strSelectedJava);

  //sort the choices array to prepare for search
  Arrays.sort(choices);
  x = Arrays.binarySearch(choices, selectedJava);

  if(x >= 0 && x < selectedJava)
  {
    //don't forget to specify the array index: topJava[x]
    JOptionPane.showMessageDialog(null, "One reason I like Java is:\n" + topJava[x]);
  }
  else
  {
    JOptionPane.showMessageDialog(null,"Sorry - That number is not between 1 and 10");
  }

  System.exit(0);
 }
}
cgeier 187 Junior Poster

The other version I posted will work too. Here's the implementation using the code from your original post.

Dim con As New OleDb.OleDbConnection
 
con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\data\YayaDB.mdb"

con.Open()

Dim query = "UPDATE Rooms SET Rooms.Customer_Name = @Name, Rooms.CheckIn_Date = @Date, Rooms.Time_In = @TimeIn, Rooms.Time_Out = @TimeOut, Rooms.Price = @Price WHERE Rooms.Room = @RoomNo"
            
Dim cmd = New OleDbCommand(query, con)
cmd.Connection = con

cmd.Parameters.AddWithValue("@Name", txtName.Text)
cmd.Parameters.AddWithValue("@Date", txtDate.Text)
cmd.Parameters.AddWithValue("@TimeIn", txtTimeIn.Text)
cmd.Parameters.AddWithValue("@Price", txtPrice.Text)
cmd.Parameters.AddWithValue("@TimeOut", txtTimeOut.Text)
            
'It appears that variables in the where clause need to be
'listed last. Follow the order that you list the parameters in 
'your update statement and it should be ok
            
cmd.Parameters.AddWithValue("@RoomNo", txtRoom.Text)

' cmd.ExecuteNonQuery()

Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
Dim retVal = MsgBox("RowsAffected: " & rowsAffected, MsgBoxStyle.Information + MsgBoxStyle.OkOnly)

'Console.WriteLine("RowsAffected: {0}", rowsAffected)
cgeier 187 Junior Poster

Ok, I think I figured out why your code doesn't work. For some reason, it seems that the order your parameters are listed in matters. At least for the one in the where clause (@RoomNo needs to be listed last). It's probably a bug and you should open a case with MS.

Change your code FROM:

cmd.Parameters.AddWithValue("@RoomNo", txtRoom.Text)
            cmd.Parameters.AddWithValue("@Name", txtName.Text)
            cmd.Parameters.AddWithValue("@Date", txtDate.Text)
            cmd.Parameters.AddWithValue("@TimeIn", txtTimeIn.Text)
            cmd.Parameters.AddWithValue("@TimeOut", txtTimeOut.Text)
            cmd.Parameters.AddWithValue("@Price", txtPrice.Text)

TO:

cmd.Parameters.AddWithValue("@Name", txtName.Text)
            cmd.Parameters.AddWithValue("@Date", txtDate.Text)
            cmd.Parameters.AddWithValue("@TimeIn", txtTimeIn.Text)
            cmd.Parameters.AddWithValue("@TimeOut", txtTimeOut.Text)
            cmd.Parameters.AddWithValue("@Price", txtPrice.Text)
            cmd.Parameters.AddWithValue("@RoomNo", txtRoom.Text)

Notice that the following line is now the last parameter added:
cmd.Parameters.AddWithValue("@RoomNo", txtRoom.Text)

cgeier 187 Junior Poster

There are actually quite a different ways to connect to a database. I haven't figured out why your's doesn't work yet, but below is one that should work.

I'm assuming that you've already added a Reference to "System.data" (or added "Imports System.Data.OleDb" above your class definition).

Private Sub updateDB()


        Try
            Dim ConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source==..\data\YayaDB.mdb;"
            Dim con As OleDb.OleDbConnection = New OleDb.OleDbConnection(ConnectionString)

            Dim cmd As OleDbCommand = con.CreateCommand()

            cmd.CommandText = "UPDATE Rooms SET Rooms.Customer_Name = @Name, Rooms.CheckIn_Date = @Date, Rooms.Time_In = @TimeIn, Rooms.Time_Out = @TimeOut, Rooms.Price = @Price WHERE Rooms.Room = @RoomNo"

            cmd.Parameters.AddWithValue("@Name", txtName.Text)
            cmd.Parameters.AddWithValue("@Date", txtDate.Text)
            cmd.Parameters.AddWithValue("@TimeIn", txtTimeIn.Text)
            cmd.Parameters.AddWithValue("@TimeOut", txtTimeOut.Text)
            cmd.Parameters.AddWithValue("@Price", txtPrice.Text)
            cmd.Parameters.AddWithValue("@RoomNo", txtRoom.Text)


            con.Open()
            Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
            ' cmd.ExecuteNonQuery()

            'Console.WriteLine("RowsAffected: {0}", rowsAffected)
            Dim retVal = MsgBox("RowsAffected: " & rowsAffected, MsgBoxStyle.Information + MsgBoxStyle.OkOnly)

            con.Close()
        Catch ex As Exception
            'Console.WriteLine(ex.Message)
            Dim retVal = MsgBox("Error: " & ex.ToString(), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly)
        End Try

    End Sub
cgeier 187 Junior Poster

Add some error handling to your code. Also double check the data types in the database. I think that if you use ".AddWithValue" it is assumed that you are passing the correct data types.

Ex: if "CheckIn_Date" in the database is of type Date/Time then you probably need to pass it a variable of that type.

Dim CheckIn_Date As DateTime
cmd.Parameters.AddWithValue("@Date", CheckIn_Date)

Instead of:
cmd.Parameters.AddWithValue("@Date", txtDate.Text)
This is probably passing a String (char/varchar).

Likewise with some of your other columns.
Also, it's probably not a good idea to be using reserved words as variables names (such as "Date").

See the following:
http://support.microsoft.com/kb/321266
http://support.microsoft.com/kb/286335
http://msdn.microsoft.com/en-us/library/ms714540(VS.85).aspx

Try
Dim con As New OleDb.OleDbConnection
        con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=..\data\YayaDB.mdb"
        con.Open()
        Dim query = "UPDATE Rooms SET Rooms.Customer_Name = @Name, Rooms.CheckIn_Date = @Date, Rooms.Time_In = @TimeIn, Rooms.Time_Out = @TimeOut, Rooms.Price = @Price WHERE Rooms.Room = @RoomNo"
        Dim cmd = New OleDbCommand(query, con)
        cmd.Connection = con
        cmd.Parameters.AddWithValue("@RoomNo", txtRoom.Text)
        cmd.Parameters.AddWithValue("@Name", txtName.Text)
        cmd.Parameters.AddWithValue("@Date", txtDate.Text)
        cmd.Parameters.AddWithValue("@TimeIn", txtTimeIn.Text)
        cmd.Parameters.AddWithValue("@TimeOut", txtTimeOut.Text)
        cmd.Parameters.AddWithValue("@Price", txtPrice.Text)

       ' cmd.ExecuteNonQuery()

        Dim rowsAffected As Integer = cmd.ExecuteNonQuery()
        Console.WriteLine("RowsAffected: {0}", rowsAffected)

        con.Close()
Catch ex As Exception 
   Console.WriteLine(ex.Message) 
  'Dim retVal = MsgBox("Error: " & ex.ToString(), MsgBoxStyle.Critical + MsgBoxStyle.OkOnly)
End Try
cgeier 187 Junior Poster

You should be able to do something similar to below. I've trimmed down the code a little bit, so hopefully I didn't omit anything necessary. But it should give you a jumpstart on how to use ASP to add data to a database.

event.asp

<%@ Language=VBScript %>
<HTML><HEAD><TITLE>Add Event</TITLE>
<BODY>

<TABLE height="100%" cellSpacing=0 cellPadding=0 width=100% align=center border=0>
   <TBODY>

      <form action = "addEvent.asp" method=POST>

       <TR>
         <TD colspan=2>
           <select name="start_month">
             <option value=''></option>
             <option value='January'>January</option> 
             <option value='February'>February</option>
             <option value='March'>March</option> 
             <option value='April'>April</option>
             <option value='May'>May</option>
             <option value='June'>June</option>
             <option value='July'>July</option>
             <option value='August'>August</option>
             <option value='September'>September</option>
             <option value='October'>October</option>
             <option value='November'>November</option>
             <option value='December'>December</option>
           </select>
      </TR>
      
      <TR>
        <TD colspan=2>
          <TEXTAREA NAME="location" COLS=33 ROWS=4></TEXTAREA>
        </TD>
      </TR>

       <TR>
         <TD>
           <input type='submit' value='Add Event'>
            &nbsp;
           <input type='reset' value='Reset'>
         </TD>
       <TR>

     </TBODY>
   </TABLE>
</BODY>
</HTML>

addEvent.asp

<%@ Language=VBScript %>
<HTML><HEAD><TITLE>Add Event</TITLE>
<BODY>
<%

 ' on error resume next

Dim start_month
Dim start_date
Dim location
Dim strConnection

Dim i
Dim field_array(2)
Dim value_array(2)

start_month            = Request.form("start_month")
location                   = Request.form("location")


'strConnection = 

'start_date = start_month & " " & start_day & ", " & start_year 
start_date = start_month

if (start_month =  "") then
      Response.Write "Start date has not been selected."
      Response.Write "Start Date: " & start_date & "<BR>"
      Response.Write "Press the ""Back"" button on your browser to  continue.<BR>"
      Response.End

end if

field_array(0)  = "start_date"
field_array(1)  = "location" 

if (start_date <> "") then
   value_array(0) = chr(35) & start_date & chr(35)
else
   value_array(0) = "NULL"
end if

value_array(1)  = "'" & location & "'"

i=0
for each val in value_array
   if (val = "" or …
sknake commented: You do not assemble queries dynamically to stop injections -1
stephen_4 commented: right +0
cgeier 187 Junior Poster

Use ASP with ADO. If .NET framework is installed, you could also use ASP .NET
http://www.w3schools.com/asp/asp_intro.asp
http://www.w3schools.com/asp/asp_ado.asp
http://www.w3schools.com/ado/ado_intro.asp

For connection strings see:
http://www.connectionstrings.com/

Madaxe commented: Helpful suggestion and excellent links +2
cgeier 187 Junior Poster

Below is an example of how to use 4 variables. It's only been tested with the defined integer array. I'm not saying whether it's the best way to do it or not, I worked with what you had. I did it quickly so double check that it works for all cases. Remember array indexes in Java start with "0".

If you use an array and sort it from lowest to highest, the 2nd smallest integer index will always be "1" (with 2 or more integers) No "testing" required. It just always is.

public class SecondSmallest {
 	public static void main(String[] args) {
 		System.out.println("Næstmindste værdi i arrayet har indexnr.: " +(indexOfSecondSmallest(new int[] {44,35,62,5,22,66})));
	}
	public static int indexOfSecondSmallest(int[] values) throws IllegalArgumentException {
		if (values.length < 2) {
			throw new IllegalArgumentException("Der skal være mindst to værdier i arrayet af typen int");
		}
 			int min;// declare variable
			int secondMin;// declare variable
            int minIndex;
            int secondMinIndex;
			// Estblish relation between min and secondMin in the array
			if (values[0] < values[1]) {
		        min = values[0];
                                        //take index from above '0' (min = values[0]) and save as minIndex
                                        minIndex = 0;

		        secondMin = values[1];
                 //take index from above '1' and save as minIndex
                secondMinIndex = 1;

		    }// end of if
			else {
		        min = values[1];
                minIndex = 1;
		        secondMin = values[0];
                secondMinIndex = 0;
		    }// end of else

 			for (int i = 0; i < values.length; i++) {
		        if (values[i] <= min) {
		            secondMin = min;
                    secondMinIndex = minIndex;
		            min = values[i];
		        }
		        else …
cgeier 187 Junior Poster

javaAddict's method is probably the best. If you are going to want additional numbers/indexes--like the 3rd or 4th smallest--you may just want to sort your array. Then the "smallest" numbers will have index of "n-1". Second smallest will have index of "2-1 = 1". Third smallest will have index of "3-1 = 2". Smallest will have index of "1-1 = 0"...etc. Guess it depends on your goal.

cgeier 187 Junior Poster

Prevent user from entering the same number twice (duplicates).

Largest.java

import java.util.Scanner;

class Largest//finds largest value
{
    
  //constructor
  public Largest(){

  } //end constructor
  
  //finds the largest integer
  public void findLargest()
  {
  //create Scanner to input
  Scanner input = new Scanner(System.in);

  //set variables
  int [] numbers = new int [10]; //number of integers
  int x; //counter
  int largestNumber; //largest integer
  int userData; // integer entered by user
  boolean numberExists = false;

  //initialization phase
  largestNumber = 0;//initilize

  //processing phase
    
    System.out.println("You will be prompted for 10 numbers.");
    //initialize counter "x"
    x=0;
    while (x<10)
    {

      System.out.print("Enter a number[" + x + "]:");//prompt for integer
      userData=input.nextInt ();//input next integer
      
      for (int y=0; y<=x;y++)
      {
          //see if the integer already exists in the array
          //we only need to check up to the last number entered
          //by the user so we say "y<=x"

          //don't need to check if this is the first number
          if (x !=0)
          {
            if (numbers[y] == userData)
            {
              numberExists = true;
              
              System.out.println("This number was already entered: " + userData);
              System.out.println("Please choose a different number.");
            }
          }
      }

      if (numberExists == false)
      {
        //this is a unique number, so store it in the array
        numbers[x] = userData;

        //initialize largestNumber to first number entered by user
        if (x == 0)
        {

          largestNumber = numbers[0];
        }

        //if any other numbers are larger than the 1st one entered
        //replace with the new largest number
        if (numbers[x] > largestNumber)
        {
          largestNumber = numbers[x];
        }

        x = x + 1;
      }
      else
      {
          //reset numberExists to false …
cgeier 187 Junior Poster

You probably want to do something like the following. Remember to keep track of your variable names and data types. Also, don't name any of your variable names the same as the class name. This version does not prevent duplicates or prevent strings from being entered--error handling is a more "advanced" topic.

Largest.java

import java.util.Scanner;

class Largest //finds largest value
{
    
  //constructor
  public Largest(){

  } //end constructor
  
  //finds the largest integer
  public void findLargest()
  {
  //create Scanner to input
  Scanner input = new Scanner(System.in);

  //set variables
  int [] numbers = new int [10]; //array of integers
  int x; //counter
  int largestNumber; //largest integer

  //initialization phase
  largestNumber = 0;//initilize

  //processing phase
    
    System.out.println("You will be prompted for 10 numbers.");
    
    for (x=0; x<10; x++)
    {
      //prompt for integer
      System.out.print("Enter a number[" + x + "]:");
      numbers[x]=input.nextInt ();//input next integer
    
      //initialize largestNumber to first number entered by user
      if (x == 1)
        largestNumber = numbers[0];

      //if any other numbers are larger than the 1st one entered
      //replace with the new largest number
      if (numbers[x] > largestNumber)
        largestNumber = numbers[x];

    }//for loop ends

    //print out largest number
    System.out.printf("The largest number is %d \n", largestNumber);
  }//end method findlargest


} //end class Largest

LargestTest.java

public class LargestTest
{
  public static void main(String[] args )
  {
    Largest myLargest = new Largest();
    myLargest.findLargest();
  //myLargestTest.displaylargestTest();
  }//end main
}//end class LargestTest
cgeier 187 Junior Poster

Don't think you can do this:

....
//set variables
int [] counter = new int [10]; //number of integers

//processing phase
while([] counter <= 10);//loop 10 times
{ 
.....

I've never seen anyone try to write a statement like that. Don't think that is valid syntax:

while([] counter <= 10);

Also, you are trying to compare an array to an integer. You can't compare an entire array to a single integer. You could however compare an array element to an integer:
while (counter <=10)

Probably not what you are trying to achieve. You probably just need to do the following:

int counter; //number of integers
....
while (counter <= 10)
{
...

counter = counter + 1; //increment counter
}

cgeier 187 Junior Poster

Looks like you've made progress. There are many ways to accomplish a task. Here's something that may help. Use what you can for ideas. Sorry about the formatting.

import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JOptionPane;

    //create array list of type StudentClass
    ArrayList<StudentClass> studMasterArray = new ArrayList<StudentClass>();

    ArrayList<StudentClass> studTransArray = new ArrayList<StudentClass>();

    //used to keep track of record number when pressing "previous" or "next"
    int recordNumber = 0;

    //used to keep track of how many array elements/students we have
    int recordCount = 0;

   //used to keep track of order
   String orderBy = "";

    public void addDefaultData() {
        String[] defaultNames = {"Alvin Du", "Ryan Gosden", "Michelle Dowling", "Toni Dowling", "Romeo Jones"};
        int[] defaultID = {153679, 417950, 234512, 762903, 200120};

        //clear array of any previous data
        studMasterArray.clear();
       

        for (int i = 0; i < defaultNames.length; i++) {
            recordCount = recordCount + 1;

            //need to create new Nstudent for each loop
            //otherwise all data will = the last student entered

            StudentClass Nstudent = new StudentClass();

            Nstudent.setStudentID(defaultID[i]);
            Nstudent.setStudentName(defaultNames[i]);

        
            studMasterArray.add(Nstudent);


           // tranList.addElement(defaultNames[i] + "     " + defaultID[i]); //adds arrays to JList
        }

        displayData(studMasterArray,masterJlist);
        
        statusLbl.setText("Default Records Loaded!");

    }

    //------------------------------------------------------------------

    public void orderRecordsByID(){
        statusLbl.setText("Sorting by id...");
        //set global variable value so we can keep track how newMasterJlist 
        //is ordered
        orderBy = "id";
 
        displayData(bubbleSort(studMasterArray,orderBy),newMasterJlist);
    }
    //------------------------------------------------------------------

    public void orderRecordsByName(){
        statusLbl.setText("Sorting by name...");
        //set global variable value so we can keep track how newMasterJlist 
        //is ordered
        orderBy = "name";

        displayData(bubbleSort(studMasterArray,orderBy),newMasterJlist);
    }
    //------------------------------------------------------------------
   

    private ArrayList<StudentClass> bubbleSort(ArrayList<StudentClass> arrayToSort, String sortBy)
      {
           //create a new arrayList to hold the sorted values
           ArrayList<StudentClass> sortedList …
cgeier 187 Junior Poster

You need to follow your code--execute your code on paper. Follow line by line and write down on paper what the values are for the variables. For example: if (i <= day). You set i=1. So unless the user enters a value for day of "0" this will always get executed. If a someone worked "0" days, then there is no reason to run this program. No work = no pay.

I didn't look through/correct all of your code, but I've modified your code a bit to help you along.

#include <stdio.h>

int main()
{
    int day;
    int i = 1;
    //wHours should be float because people work partial hours sometimes
    float wHours;
    //hRate should be float because people aren't paid only in whole dollar amounts 
    float hRate;
    float total = 0.0;
    float cTax,gross,salary,nSalary,aTotal;
    float tax = .12;
    
    printf("Enter Hourly Rate: ");
    scanf("%f",&hRate);
    printf("Enter number of days you've worked: ");
    scanf("%d",&day);
    

    while (i <= day)
    {
        printf("\nEnter number of hours you worked in  Day %d:  ",i);
        scanf("%f",&wHours);

        if (wHours > 8.0)
        {
             //what do you want to do if wHours > 8 ???

        }
        else
        {
             salary=wHours*hRate;
        }

        printf("\nYour salary for  day %d is %.2f  \n",i,salary);
        i=i+1;
        total=total+salary;
         
    }
   

    aTotal = total;
    printf("\nYour weekly gross salary is %.2f", aTotal);  
    cTax =tax*total;                
    printf("\n\n the tax is %.2f",cTax );
    gross=aTotal-cTax;
    printf("\n\n weekly net salary is %.2f", gross);
    
    
    getchar();
    getchar();
}
cgeier 187 Junior Poster

Please post more information about the requirements for your program. Also more about how the data should look during different stages of the program execution as well as explanations as to why the data should look that way. It'd also be nice if you could show how the data is supposed to look (or how you think it looks) inside the arraylist (including data types).

cgeier 187 Junior Poster

Sorry about the code formatting. You have multiple things going on:

In "addDefaultData" you give the impression that "studTranArray" is a record.
Ok, records/struct don't really exist in Java so you can use a class to
try to achieve something similiar.

You do the following:

String [] defaultNames = {"Alvin Du","Ryan Gosden","Michelle Dowling","Toni Dowling"};
int [] defaultID = {153679,417950,234512,762903};

Nstudent.setStudentName(defaultNames);
Nstudent.setStudentID(defaultID);

studTranArray.add(Nstudent);


------------------------------------------------------------------------------
You declare "studTranArray" as follows:
ArrayList studTranArray = new ArrayList();

----------------------------------------------------

then in "addRecord", you do the following:
studTranArray.add(iD.getText());
studTranArray.add(nameSur.getText());

you are mixing what should probably be integer data (ID) with
String data (name). You need to keep your id's separate from
the names. Looks like you started to do this in "addDefaultData".
----------------------------------------------------
in "sDemoButtonActionPerformed" you call:
sort.bubbleSort(studTranArray );

but you declare "bubbleSort" as follows:

static int bubbleSort(ArrayList <Integer> sortedList)

------------------------------------------------------
Looks like you added "String" data to the array list and told
bubblesSort that you were going to pass it an "Integer" array list.

Even if you remove "<Integer>" from your bubbleSort declaration,
you can't compare String data with ">" or "<". You have to use
"compareTo" or "compareToIgnoreCase".

-------------------------------------------------------
I would recommend creating a separate class that separates the student data:


package assignment2009;

public class StudentClass {

        public StudentClass() {
    }


    protected String studentName;
    protected int …