cgeier 187 Junior Poster

I'm having trouble seeing how to do it with a for loop. Maybe you can provide an example. In my example, "trialCount++" would actually be inserted on line #13, since the trial is only complete when random number = winning number.

PrintWriter outFile = new PrintWriter (new File("bottleCap.txt"));
int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          randomNumber = ((int)(0+ Math.random()* 5));
          rollCounter++;

          if (randomNumber == winningNumber){
               outFile.println(rollCounter);
               //winning number is found, this trial is complete
               trialCounter++;
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

outFile.close ();
cgeier 187 Junior Poster

I think that I would use two "do-while" loops rather than a "for loop", because the trial isn't over until the random number generated = the winning number.

int numberOfTrials = 20;
int winningNumber = 1;
int rollCounter = 0;

do{
     //re-initialize roll counter
     rollCounter = 0;
     do{
          //generate random number here

          rollCounter++;
          if (randomNumber == winningNumber){
              
          }//if
     
     }while (randomNumber !=winningNumber);
}while(trialCounter <= numberOfTrials);

Where do you want to increment the trialCounter? When is a trial considered complete?

cgeier 187 Junior Poster

Looks like you are making good progress. After you get everything working, maybe rather than hard coding the number of trials, you want to prompt the user for this info. From your "Rolling Dice" post, it looks like you know how to use the scanner. Maybe it's too early yet, but as you continue programming, it's a good idea to start adding some "error" checking on user input. Here's an example:

Scanner in;  
in = new Scanner(System.in);
int numberOfTrials = 0;
boolean isValidInteger = false;

do{
       System.out.println("How many trials?: ");

       //check to see if data can be converted to integer
       if (in.hasNextInt()){
            //if data can be converted to integer, read the value
            numberOfTrials = in.nextInt();
            if (numberOfTrials < 1){
                System.out.println("Invalid number. Try again.");
                isValidInteger = false;
            }//if
            else{
                isValidInteger = true;
            }//else
        }//if
        else{
            //get invalid data and dispose of it
            in.next();
            System.out.println("Invalid data. Try again.");
            isValidInteger = false;
        }//else
}while(isValidInteger != true);
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

The problem you faced earlier with:

System.out.println("Total Price is $" + distance/mpg*ppg+parking+tolls );

was because "+" is a String concatenation operator. Do your math operations, store the value in a variable, and then print the variable.

To use printf you can do the following:

double total;

total = distance / mpg * ppg + parking + tolls;

//print to 2 decimal places
//for 3 decimal places, use "%.3f"
System.out.printf("Total Price is %.2f \n", total );
cgeier 187 Junior Poster

Here's an alternative "isInteger" method. In case you are not familiar with regular expressions.

isInteger

private static boolean isInteger(String s){
        char[] myCharArray;
        boolean returnValue = true;

        //convert string to Character array
        myCharArray = s.toCharArray();

        //check each character to see if it is a digit
        //if any character is NOT a digit, set returnValue = false
        for (int i=0; i < myCharArray.length; i++){
  
            //if we find a character that is NOT a digit, 
            //return false
            if (!Character.isDigit(myCharArray[i]) ){
                returnValue = false;
            }
        }//for

        return(returnValue);
    }//isInteger

Here's a regular expression to check if a number is a double:

if (s.length() >= 1){
  return java.util.regex.Pattern.matches("[\\d+]|[\\d]+.[\\d]+", s);
}//if

In the above regular expression, I check to see if the string is made up of all digits OR a series of digits followed by a "." followed by more digits. How could you write it without regular expressions?

cgeier 187 Junior Poster

I made a mistake in one of my previous posts. A simple fix is to split the following line into two else if statements:

else if (option > 2 || isInteger(strOption) != true)

We need to check to see if strOption is only digits before we can parse it to an integer. And we have to parse it to an integer before we can check to see if it is > 2. See the code below:

do {
     strOption = JOptionPane.showInputDialog("Menu options:\n1. Enter Hourly Employee\n2. Enter Salaried Employee\n0. Done\n Please select a menu option: ");

     if (strOption == null){
          //happens when cancel is pressed
          JOptionPane.showMessageDialog(null, "You pressed cancel. Exiting...");

          return; //"exits" the method
     }//if
     else if (isInteger(strOption) != true){
          JOptionPane.showMessageDialog(null, "Sorry, " + (strOption) + " is not a valid option.");
     }//if
     else if (Integer.parseInt(strOption) > 2){
          //value has been validated as an integer above
          //so check to see if value is > 2
          JOptionPane.showMessageDialog(null, "Sorry, " + (strOption) + " is not a valid option.");
     }//else if
     else{
          option = Integer.parseInt(strOption);          
          //we have a valid option so continue with the program


     }//else
} while (option >2 || isInteger(strOption) != true);
cgeier 187 Junior Poster

In the example I posted, you would put it in the main class. It is just for data validation. If you are able to assume that the user enters the "proper" information, you don't need it. In my opinion, though, one should never assume that the user will enter the proper information.

public class Main {
    private static boolean isInteger(String s) {
        if (s.length() >= 1){
            return java.util.regex.Pattern.matches("\\d+", s);
        }
        else
        {
            //return false if string is null
            return false;
        }
    }//isInteger

public static void main(String[] args) {
     //your code goes here
}
cgeier 187 Junior Poster
cgeier 187 Junior Poster

It's not quite clear what the goal of your program is.

Here is an example to calculate the total amount to be paid to all hourly employees:

ArrayList <HourlyEmployee> myHourlyEmployees = new HourlyEmployee();

//To Do: get menu option: 

int menuOption = Integer.parseInt(strOption);

switch (menuOption){
     case 0: 
          //exit method
          return;
     case 1:
          //To Do: get number of employees: strWorker

          int numberOfHourlyEmployees = Integer.parseInt(strWorker);
    
          int count = 0;
          while (count < numberOfHourlyEmployees){
               //create new hEmployee each loop
               HourlyEmployee hEmployee = new HourlyEmployee();

               //To Do: get hourly pay rate: strPay

               double pay = Double.parseDouble(strPay);
               hEmployee.setPayRate(pay);

               //To Do: get number hours per week for employee: strHour

               double hour = Double.parseDouble(strHour);
               hEmployee.setHoursPerWeek(hour);

               //optionally, add "salary" to class HourlyEmployee
               //then: salary = hEmployee.getHoursPerWeek() * hEmployee.getPayRate();
               //and: hEmployee.setSalary(salary);

               //or you could add a method, called "salary" to class HourlyEmployee          

               //add hEmployee to myHourlyEmployees ArrayList
               myHourlyEmployees.add(hEmployee);
          }//while


          double totalHourlyEmployeePay=0.0;
          for (int i = 0; i < myHourlyEmployees.size(); i++){
               //create new hEmployee each loop
               HourlyEmployee hEmployee = new HourlyEmployee();
               hEmployee = myHourlyEmployees.get(i);
               double monthlyEmployeeSalary = hEmployee.getPayRate() * hEmployee.getHoursPerWeek();
               totalHourlyEmployeePay = totalHourlyEmployeePay + monthlyEmployeeSalary;
          }//for     

          JOptionPane.showMessageDialog(null, (totalHourlyEmployeePay));
          break;
     case 2:

          break;
}//switch
cgeier 187 Junior Poster

Here's something to get you started. Create a class called HourlyEmployee for the hourly employees:

HourlyEmployee:

public class HourlyEmployee {
    protected double payRate;
    protected double hoursPerWeek;

    public HourlyEmployee(){

    } //constructor

     public void setPayRate(double newPayRate)
     {
          payRate = newPayRate;
     }

     public double getPayRate()
     {
          return payRate;
     }

     public void setHoursPerWeek(double newHoursPerWeek)
     {
          hoursPerWeek = newHoursPerWeek;
     }

     public double getHoursPerWeek()
     {
          return hoursPerWeek;
     }
}

If you are going to use the user input dialog, you should do something like the following:

isInteger:

private static boolean isInteger(String s) {
        if (s.length() >= 1){
            return java.util.regex.Pattern.matches("\\d+", s);
        }
        else
        {
            //return false if string is null
            return false;
        }
    }//isInteger
do {
     strOption = JOptionPane.showInputDialog("Menu options:\n1. Enter Hourly Employee\n2. Enter Salaried Employee\n0. Done\n Please select a menu option: ");
     if (strOption == null){
          //happens when cancel is pressed
         JOptionPane.showMessageDialog(null, "You pressed cancel. Exiting...");

          //return; //"exits" the method
     }//if
     else if (option > 2 || isInteger(strOption) != true){
          JOptionPane.showMessageDialog(null, "Invalid option: " + strOption);
     }//if
     else{
          option = Integer.parseInt(strOption);
          //we have a valid option so continue with the program


     }//else
} while (option >2 || isInteger(strOption) != true);

Then create an ArrayList of hourly employees.

import java.util.ArrayList;

//create an ArrayList of type HourlyEmployee
ArrayList <HourlyEmployee> myHourlyEmployees = new HourlyEmployee();
HourlyEmployee hEmployee = new HourlyEmployee();

//prompt for pay rate; I'll let you fill in that code
//we'll call it  "strPay"

//convert to double
pay = Double.parseDouble(strPay);
hEmployee.setPayRate(pay);

//prompt for number of hours worked; I'll let you fill in …
cgeier 187 Junior Poster
cgeier 187 Junior Poster

You'll probably find more info on it if you search for "ASP Request.QueryString" and "ASP Request.Form".

C#

string userLocation;
userLocation = Request.QueryString["location"];

C#

string userLocation;
userLocation = Request.Form["location"];
cgeier 187 Junior Poster

It comes from the days of ASP.

The "Request.QueryString" command is used to collect values in a form with method="get".

SimpleForm_1.asp

<form method="get" action="SimpleFormHandler_1.asp">
    <TEXTAREA NAME="location" COLS=33 ROWS=4></TEXTAREA>
    <input type='submit' value='Add Event'>
</form>

SimpleFormHandler_1.asp

<%@ Language=VBScript %>

<%
        Dim userLocation

        'location is the variable name as defined by "NAME="
        'in SimpleForm_1.asp
        userLocation = Request.QueryString("location")
%>

The "Request.Form" command is used to collect values in a form with method="post".

SimpleForm_2.asp

<form method="post" action="SimpleFormHandler_2.asp">
    <TEXTAREA NAME="location" COLS=33 ROWS=4></TEXTAREA>
    <input type='submit' value='Add Event'>
</form>

SimpleFormHandler_2.asp

<%@ Language=VBScript %>

<%
        Dim userLocation

        'location is the variable name as defined by "NAME="
        'in SimpleForm_2.asp
        userLocation = Request.form("location")
%>

See http://www.w3schools.com/ASP/asp_inputforms.asp

cgeier 187 Junior Poster

Guess I forgot to increment "recordCount" in the "switch/case" version. It needs to be added to "case 3:"

switch (lineCount % 4)
{
    case 0:
        //Song Name
        songs[recordCount].title = lineData;
        break;
    case 1:
        //Artist
     
        break;
    case 2:
        //Genre
     
        break;
    case 3:
        //Track Time
        //convert string to integer value
        songs[recordCount].track_time = atoi(lineData.c_str());  

        recordCount ++;   
        break;
}//switch
cgeier 187 Junior Poster

You have some other errors:
while(fin.eof() && count<MAX_SONGS)

It gets to the end of the file before this is true.
Need to change to:
while(!fin.eof() && count<MAX_SONGS)

To do multiple getline's without checking for EOF each time, you could do something like the following:

while(!fin.eof() && count<MAX_SONGS){
    if (getline(fin,songs[i].title))
    if (getline(fin,songs[i].artist))
                    //...and on, and on...
}

Although, it doesn't allow you to check for "empty" lines (lines with no data, only a newline). What if the file has an "empty" line? Try to think about things that a user could do to make your program not work (or return invalid input). If you're just starting to program, I wouldn't get too carried away with this, just do some simple things.

A way to check for an "empty" line might be to see if the length > 0:

string lineData;
while( !fin.eof() && recordCount<MAX_SONGS){
    getline(fin,lineData);

    //bypass empty lines
    if (lineData.length() > 0){
        //this line contains data, so it is ok to use
    }//if 
}//while

Another common thing that one might want to check (to avoid runtime errors), is if the file is open or not.

if (fin.is_open()){
    //we know that the file is open, so we can read from it
    
    string lineData;
    while( !fin.eof() && recordCount<MAX_SONGS){
        getline(fin,lineData);

        //eliminate empty lines
        if (lineData.length() > 0){
            //this line contains data, so it is ok to use

        }//if 
    }//while
}//if

So, now we check to see if the file is open and to see if …

cgeier 187 Junior Poster

Not sure that it is needed to check for a leap year though.

See: http://www.jetcityorange.com/leap-year/
and
http://www.timeanddate.com/date/leapyear.html

Something simple like this should work.

private boolean isLeapYear(int userYear)
{
  
   if (((userYear % 4 == 0) && (userYear % 100 != 0)) || (userYear % 400 == 0))
       return true;
   else
       return false;
}
cgeier 187 Junior Poster

Use "DecimalFormat".

import java.text.DecimalFormat;

private String twoDigitNum(String myNum)
{
    //specifies a 2-digit number
    DecimalFormat num = new DecimalFormat("00");

    //for a 4-digit number use the one below
    //DecimalFormat num = new DecimalFormat("0000");
        
    return (num.format(Double.parseDouble(myNum)));
}
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

**Warning**: This process, if improperly performed, could make your computer unbootable. It is recommended that you back up your files before proceeding.

1. Create a restore point
Control Panel -> Backup and Restore Center -> Create a restore point or change settings (on left side)

2. Open cmd window (right click and select "run as administrator")

3. type: "set USERPROFILE" (note this location)

4. Backup the system store to location above: bcedit /export %UserProfile%\bcdbackup

5. type: bcdedit /enum ACTIVE /v

6. type: bcdedit /default {<Vista identifier>}
ex: bcdedit /default {cbd971bf-b7b8-4885-951a-fa03044f5d71}

7. Look for and note the "identifier" for Windows 7

8. type: bcdedit /delete {<Windows 7 identifier>}
ex: bootcfg /delete {pka287sw-k8k1-5119-247c-wc89383w5a87}


==============================
Alternative method:

1. Create a restore point
Control Panel -> Backup and Restore Center -> Create a restore point or change settings (on left side)

2. Open cmd window (right click and select "run as administrator")

3. type: "set USERPROFILE" (note this location)

4. Backup the system store to location above: bcedit /export %UserProfile%\bcdbackup

5. type bcdedit

6. Look for and note the "identifier" for Vista

7. bcdedit /default {<Vista identifier>}
ex: bcdedit /default {current}

8. Look for and note the "identifier" for Windows 7

9. bcdedit /delete {<identifier>} /f
ex: bcdedit /delete {current} /f

cgeier 187 Junior Poster
cgeier 187 Junior Poster

Has this computer ever been connected to the router with the current configuration? Or did you just install a (new) wireless adapter for it? Do you have the latest driver for the D-link wireless adapter? Do you have the latest firmware installed on your router?

http://www.linksysbycisco.com/US/en/support#

Here are the router reset instructions:

http://www3.nohold.net/noHoldCust56/Prod_6/KnowledgePortal/KPScripts/amsviewer.asp?docid=93bb017280e0407fb2322ac5d4af4166_KB4008_EN_070221_v1.xml&amsstatsid=7199453

"169......" is the default address that is assigned if the computer can't connect to a DHCP server (ie: your router in this case)

cgeier 187 Junior Poster

How is your computer connected? Wireless or wired? What brand router are you using (and what version)? Have you tried reseting your router? Not unplugging and plugging it back in, but following the manufacture's instructions for reseting the router (probably pressing and holding the reset button, unplugging the power and then plugging it back in, and then releasing the reset button). What operating system are you using? Have you restarted your computer?

cgeier 187 Junior Poster

A more simple (and perhaps better) approach would just be to change your declaration in line #6
FROM

private static Scanner keyb = new Scanner(System.in);

TO:

//change delimiter from white space (default) to line terminator
    private static Scanner keyb = new Scanner(System.in).useDelimiter("[\n]|[\r\n]|[\u2028]|[\u2029]|[\u0085]|[\r\n\u2028\u2029\u0085]");;

If you do this, delete any references to "keyb.useDelimiter" in my above postings as well as references to "keyb.reset()". Then it should be unneccessary to add "...nextLine() method call at the end of each of the number related methods..."

cgeier 187 Junior Poster

This should work for typeString. I recommend reading more about "regular expressions".

Here's a start: http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html

public static String typeString(String message)
{
    //String userInputString = new String(" ");
    boolean validInput = false;
    String userInputString = "";

    //keyb.useDelimiter(System.getProperty("line.separator"));
        
    //The default whitespace delimiter used by a scanner is as
    //recognized by Character.isWhitespace
    //change it to check for (all possible) line terminators
    keyb.useDelimiter("[\n]|[\r\n]|[\u2028]|[\u2029]|[\u0085]|[\r\n\u2028\u2029\u0085]");

    do
    {
        try
        {
         System.out.println(message);
         //next reads the next token
         //a token is "terminated" by a delimiter
         //which we changed above
         userInputString = keyb.next();
         validInput = true;
        }
        catch (InputMismatchException e)
        {
            System.out.println("Invalid data type.. try again");
            keyb.next();   // discard the bad input
            validInput = false;
        }

    }while(!validInput);

    //reset the delimiter to the default
    keyb.reset();
    //keyb.close();

    return(userInputString);
}
cgeier 187 Junior Poster

Here is an implementation of what I think llemes4011 was talking about.

See http://java.sun.com/javase/6/docs/api/java/util/Scanner.html
and
http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html

public static char typeChar(String message)
    {

        boolean validInput = false;
        char userInputChar = 0;

        System.out.println(message);
        //don't use this one because it ignores
        //possible user input
        //char userInputChar = keyb.next().trim().charAt(0);
        do
        {
            try
            {
               //use regular expression pattern to limit input
               //to String with length = 1
               //convert to a char array using "toCharArray"

               //throws exception if more than 1 "char" is entered
               char [] userInputCharArray = keyb.next(".").toCharArray();

               //copy our "character" to a char variable
               userInputChar = userInputCharArray[0];
               validInput = true;

            }
            catch (InputMismatchException e)
            {
                System.out.println("Invalid data type.. try again");
                keyb.next();   // discard the bad input
                validInput = false;

            }
        }while (!validInput);
        
        //keyb.close();

        return(userInputChar);
    }
cgeier 187 Junior Poster

I haven't used scanner a lot, but I think that error handling is built in. Below is an example of prompting for 10 integers. If invalid data is entered it prompts again. If "quit" is entered, the program exits.

Scanner input = new Scanner(System.in);

    int x=0;
    while (x<10)
    {

      //prompt for integer
      System.out.print("Enter a number[" + x + "]: ");
      if (input.hasNextInt())
      {
        userData=input.nextInt ();//input next integer
      }
      else if(input.hasNext("quit"))
      {
          System.out.println("Exiting.");
          break;
      }
      else
      {
          //don't do anything with the invalid data;
          // read it and trash it
          input.next();
          System.out.print("Invalid data entered. Enter only integers ");
          System.out.println("(-999,999,999 < x < 999,999,999).");

          //go to next iteration of loop; skipping everything below
          continue;
      }

     

     // enter the rest of your code here

     x = x+1;

}
//close scanner
input.close();
cgeier 187 Junior Poster

This version should work.

void changeDue(float amt)
{
    float denomination[12];
    float amtRemaining; 
    int numberOfDenomination = 0;
   
    //put monetary denominations into array
    denomination[0] = 1000.0;
    denomination[1] = 500.0;
    denomination[2] = 200.0;
    denomination[3] = 100.0;
    denomination[4] = 50.0;
    denomination[5] = 20.0;
    denomination[6] = 10.0;
    denomination[7] = 5.0;
    denomination[8] = 1.0;
    denomination[9] = 0.25;
    denomination[10] = 0.10;
    denomination[11] = 0.05;

    //initialize amtRemaining to amt
    amtRemaining = amt;
    for (int i=0; i<= 11;i++)
    {
         //divide amount by denomination and set it to integer value
        //this leaves us with the number of the denomination we need
        numberOfDenomination = (int)(amtRemaining / denomination[i]);

        if (numberOfDenomination > 0)
        {
          amtRemaining= amtRemaining-(numberOfDenomination*denomination[i]);
			
          cout << denomination[i] << ": " << numberOfDenomination <<endl;

       }
 }
cgeier 187 Junior Poster

This version should work.

void changeDue(float amt)
{
    float denomination[12];
    float amtRemaining; 
    int numberOfDenomination = 0;
   
    //put monetary denominations into array
    denomination[0] = 1000.0;
    denomination[1] = 500.0;
    denomination[2] = 200.0;
    denomination[3] = 100.0;
    denomination[4] = 50.0;
    denomination[5] = 20.0;
    denomination[6] = 10.0;
    denomination[7] = 5.0;
    denomination[8] = 1.0;
    denomination[9] = 0.25;
    denomination[10] = 0.10;
    denomination[11] = 0.05;

    //initialize amtRemaining to amt
    amtRemaining = amt;
    for (int i=0; i<= 11;i++)
    {
         //divide amount by denomination and set it to integer value
        //this leaves us with the number of the denomination we need
        numberOfDenomination = (int)(amtRemaining / denomination[i]);

        if (numberOfDenomination > 0)
        {
            amtRemaining = amtRemaining - (numberOfDenomination*denomination[i]);
			
            cout << denomination[i] << ": " << numberOfDenomination <<endl;

       }
 }
cgeier 187 Junior Poster

I'd do something like the following:

void changeDue(double amt)
{
    double denomination[12];
    double amtRemaining; 
    int numberOfDenomination = 0;
   
    denomination[0] = 1000.0;
    denomination[1] = 500.0;
    denomination[2] = 200.0;
    denomination[3] = 100.0;
    denomination[4] = 50.0;
    denomination[5] = 20.0;
    denomination[6] = 10.0;
    denomination[7] = 5.0;
    denomination[8] = 1.0;
    denomination[9] = 0.25;
    denomination[10] = 0.10;
    denomination[11] = 0.05;


    amtRemaining = amt;
    for (int i=0; i<= 11;i++)
    {
        numberOfDenomination = amtRemaining / denomination[i];

        if (numberOfDenomination > 0)
        {
            amtRemaining = amtRemaining - (numberOfDenomination*denomination[i]);
			
            cout << denomination[i] << ": " << numberOfDenomination;
            cout  << "(" << amtRemaining << ")" << endl;
       }
 }

It doesn't quite work for amounts that end in say $0.55 though. Don't have time to look at it more right now. But it should give you some ideas on how you might continue.

cgeier 187 Junior Poster

Where is your code? What is your question exactly?

cgeier 187 Junior Poster

Ok, I guess the last one was only for the chipset drivers. This one should include the SATA drivers.


Download and run the Intel Chipset Identification Utility:
http://downloadcenter.intel.com/Product_Filter.aspx?ProductID=861


Get Chipset Drivers:

Go to:
[url]http://www.intel.com/support/chipsets/[/url]
and find the link for your chipset. Click on the link.
Under "Drivers and Downloads" look for the column "Intel Chipset Software Installation Utility".
Click on the "Download" link for your chipset.

-Select Operating System you need the drivers for (ex: Windows XP Professional, Windows XP Home, etc...)
-Click "Go"
-Look for "INF Update Utility - Zip Format". Click "Download"
-If you accept the terms and conditions, press "Accept".
-Click the "INF Update Utility - Zip Format" link to download it.
-Extract the  "zip" archive.

Get Storage (SATA) drivers:

Go to:
[url]http://downloadcenter.intel.com/Product_Filter.aspx?ProductID=2101[/url]
-Click "Go"
-Click on "Intel(R) Matrix Storage Manager" to download
-Click on "Download" (English version)
-If you accept the terms and conditions, press "Accept".
-Click "Intel(R) Matrix Storage Manager" to download it.
-Run downloaded file with the following options: -a -p "<location to place files>\"
 ex: iata89enu.exe -a -p "C:\temp\downloads\SATA\"
 *Note: Don't forget the "\" at the end or it may not extract the files.

See [url]http://www.intel.com/support/chipsets/imst/sb/CS-020825.htm[/url] 
and 
[url]http://www.intel.com/support/chipsets/imsm/[/url]
for more info.

- Install "nLite"
-Copy your XP installation CD to your hard drive (ex: C:\Temp\Windows XP CD)

Apply drivers to XP

-Run nLite.
-Browse for copy of your installation CD on your hard drive
(think …
cgeier 187 Junior Poster

Download and run the Intel Chipset Identification Utility:
http://downloadcenter.intel.com/Product_Filter.aspx?ProductID=861

Download Chipset (SATA) drivers.

Go to:
[url]http://www.intel.com/support/chipsets/[/url]

Find the link for your chipset. 
-Click on the link.
-Under "Drivers and Downloads" look for the column "Intel Chipset Software Installation Utility".
-Click on the "Download" link for your chipset.

-Select the Operating System you need the drivers for (ex: Windows XP Professional, Windows XP Home, etc...)
-Click "Go"
-Look for "INF Update Utility - Zip Format". Click "Download"
-If you accept the terms and conditions, press "Accept".
-Click the "INF Update Utility - Zip Format" link to download it.
-Extract the  "zip" archive.

Integrate SATA drivers to XP.

- Install "nLite"
-Copy your XP installation CD to your hard drive (ex: C:\Temp\Windows XP CD)
-Run nLite.
-Browse for copy of your installation CD on your hard drive
(think you have to choose the "I386" folder in your HDD copy of XP)
-click "Next"
-click "Next"
-click "Drivers" 
-click "Next"
-click "Insert"
-select "Multiple driver folder"
-Go to your unzipped "INF Update Utility" folder (ex: infinst_autol) and click on the "All" subfolder
-click "ok"
-click "All"
-click "OK"
-click "Next"
-click "Yes"
-click "Next"
-click "Finish"

If you want to slipstream the latest Service Pack into the installation, do so now.

Download the "Network Installation" version.

-Integrate the service pack into your installation (ex: C:\Temp\Windows XP CD)

  You can use nLite to integrate the service pack.

OR 

   -open a "cmd" window
   -type the name of your service pack …
cgeier 187 Junior Poster

You need to add the following import to use "DecimalFormat":

import java.text.*;

Line #9: add "+" between 0.025 and num.format(monthlySales)
Line #9: num.format requires a number not a string

If monthlySales is declared as String, you need to covert to a number before passing it to format.

String monthlySales
num.format(Double.parseDouble(monthlySales))

Otherwise, if you declare monthlySales as a double you can leave it as is:

double monthlySales
num.format(monthlySales)

line #11 and 14: Are you sure you want these to be integers?
Maybe double:

double value1
value1 = Double.parseDouble(choice1)

Is this supposed to be a console program? If so, you might want to use "java.io.BufferedReader" or "java.util.Scanner" for input. And for output, use "System.out.print" or "System.out.println".

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

Which operating system are you using? Any service packs installed?

Use hard drive diagnostic software to check the drive.
See http://www.hitachigst.com/hdd/support/download.htm

Seagate has a program that works with some other vendor's drives.

http://www.seagate.com/www/en-us/support/downloads/seatools/
Then click on "Download SeaTools for Windows now".

cgeier 187 Junior Poster

Which operating system is currently installed on your computer? What kind of disk are you using to boot with (vendor recovery cd/dvd, Windows installation cd/dvd)? Does your "boot disk" boot on another computer? Is your cd/dvd drive able to read disks (is the drive good)? Some "boot disks" require that you press a key (such as enter) within a certain amount of time to boot from the cd/dvd.

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

Is this project for work or school? What requirements do you have?

cgeier 187 Junior Poster

Where is your "Package" class as called in class PostOffice.

public class PostOffice
{
private Package pkg;
private float cost;

It's not a good idea to use reserved words for your class names Even if you change the case. See http://java.sun.com/docs/books/tutorial/java/nutsandbolts/_keywords.html for a list of reserved words.

cgeier 187 Junior Poster

To get data into the class I know of two methods.
1. Create appropriate constructors and pass the data in that way.
See: http://java.sun.com/docs/books/tutorial/java/javaOO/constructors.html

2. Use set methods.

...
private float cost;
              ...
 
public void setCost(float newCost)
   {    
        cost = newCost;
    } // end setCost

To get data out: return it with the return statement.
You may need to change the access on some of your methods to be able to call them.

See
http://java.sun.com/docs/books/tutorial/java/javaOO/returnvalue.html
and
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html

cgeier 187 Junior Poster

This one handles duplicates and only accepts integers.

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 = 0; // 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
      //check to see if user input is an integer
      if (input.hasNextInt())
      {
        userData=input.nextInt ();//input next integer
      }
      else
      {
          //don't do anything with the invalid data; read it and trash it
          input.next();
          System.out.print("Invalid data entered. Enter only integers ");
          System.out.println("(-999,999,999 < x < 999,999,999).");

          //go to next iteration of loop; skipping everything below
          continue;
      }
      
      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.print("The number '" + userData + "'");
              System.out.println (" was already entered (index: " + y + ")");
              System.out.println("Please choose a different number.");
            }
          }
      }

      if (numberExists == false)
      {
        //this is a unique number, so store it …