poojavb 29 Junior Poster

Is there a function to hightlight some particular word in our comment...as it was earlier green/red???

poojavb 29 Junior Poster

Yes I have set the datatimepicker format to custom and the custom format as HH:mm tt....the value is getting correctly stored in database...but difficult to retrieve....can u please explain in detail....

poojavb 29 Junior Poster

If u want the datagridview to be empty at first set the datasource to nothing ....

i tried the same code but as soon as any value in text box changes it shows me the datagrid with values in database.....check ur connection...is it fine???

poojavb 29 Junior Poster

If u need to find the database table names....use the query which u have used in place of the query what i have used and then save the column names in variable

poojavb 29 Junior Poster

Try this....

Dim i As Integer
i = DataGridView1.CurrentRow.Index
'then use the insert query with the parameters like 

DataGridView1.Item(0, i).Value 'cell value keeps on changing for all cells
poojavb 29 Junior Poster

Date is not stored in the database only the time value is stored because while storing the value in database I am using

DateTimePicker3.Value.ToShortTimeString

so only time value like 1:23 AM is getting stored in the database....

and I want to retrive the same value in datetimepicker....is it possible???

else is there any other way....I have set the datetimepicker custom format to HH:mm tt

poojavb 29 Junior Poster

First declare the variables and then when u will use the select query make use of reader that will read the value and assign it to the variable

eg

Dim docid as String
Dim docfname as String
Dim doclname as String
'connection string
Try
    Dim myCommand As OleDbCommand
    myCommand = New OleDbCommand("SELECT DoctorID,FirstName,LastName FROM DoctorRegister", Connection)
    Dim reader As OleDbDataReader = myCommand.ExecuteReader
    While reader.Read
          docid = reader("DoctorID")
          docfname = reader("FirstName")
          doclname = reader("LastName")
    End While
    reader.Close()
 Catch ex As Exception
    MsgBox("Error Connecting to Database: " & ex.Message)
End Try

Hope this helps u....

poojavb 29 Junior Poster

what does the searchdatas() function do??? it is not mentioned in the code???

try to write the below code in Textbox change event rather than button click and see

open connection first

         Try

            Dim myCommand As New SqlCommand
            With myCommand
                .CommandText = "SELECT * FROM tablename where columnid like '" & Textbox2.Text & "%" + "'"
                .CommandType = CommandType.Text
                .Connection = Connection
            End With
            Dim dt As New DataTable
            dt.Load(myCommand.ExecuteReader)
            With PelangganDataGridView
                .AutoGenerateColumns = True
                .DataSource = dt
            End With
        Catch ex As Exception
            Debug.Print("Exception: ")
            Throw ex
        End Try

check this or put the code in ur button click

poojavb 29 Junior Poster

I am getting an error 'Specified cast not valid'

If the database value is retrieved in a label or variable then how can I get the label or variable value to datetimepicker

poojavb 29 Junior Poster

Hello Friends,

I need help to get the time value from MSSQL database to VB.Net Datetimepicker

I have a datetimepicker but the custom format is set to HH:mm tt so that I can get eg 11:20 AM

this value I have stored in database with the help of Label4.Text = DateTimePicker3.Value.ToShortTimeString

but now if I want to get the same value from database to datetimepicker what shud be done???

please do help me on this

Thanks in advance

poojavb 29 Junior Poster

Library Management System
School Management
Restauarant....

poojavb 29 Junior Poster

first there shud be an insert query to move ur records to the other table and then an update query

eg.insert into newtablename(col1, col2, col3) select col1,col2,col3 from oldtablename

and then an update query based on userid

update oldtablename set count=value1,times=value2 where user_id="STEVE20"

hope it helps u

poojavb 29 Junior Poster

It will be good if ur id in the database had the datatyoe as Integer coz it will help u in incrementing correctly...if u take it as text then u may face some issues while incrementing...

poojavb 29 Junior Poster
Process.Start("exeprocessname","filename")

eg. Process.Start("Notepad.exe","C:\text.txt")

poojavb 29 Junior Poster

This worked fine

Dim date_now As Date
date_now = DateTime.Now
Debug.Print(date_now.ToString("yyyy/MM/dd HH:mm:ss"))
poojavb 29 Junior Poster

When I added ur block of comment in eclipse and tried to execute it ...it showed a lot of errors for variables like total_ot_income is not resolved and many so on.....One closing brace bracket is missing at the end also...try to paste the complete code again and also the error msgs....and what;s in ur text file the employee info??

poojavb 29 Junior Poster

is the value coming from database??? where are u saving the maximum number???

if the value is coming from database use a select query

select max(columnname) from tablename 'columnname shud be the one which will be unique and incrementing

after that whatever value u will get convert it to Integer and increment by 1 and save it in the database

poojavb 29 Junior Poster

so try this instead of

frmviewsdets.txtsnumber.Text = rdr("StudentNumber")

use this

frmviewsdets.txtsnumber.Text = xyz 'which is ur variable
poojavb 29 Junior Poster

Make sure that the xyz = Mid(lstboxstudents.SelectedItem, 1, 8) has atleast 9 characters in it....

Dim con As New OleDbConnection("Provider = Microsoft.Jet.OLEDB.4.0;" & "Data Source = Decisionmaths.mdb")
Dim xyz As String
xyz = Mid(lstboxstudents.SelectedItem, 1, 8)
Dim sqlx As OleDbCommand 
con.Open()
sqlx=New OleDbCommand("SELECT * FROM Student WHERE StudentNumber = '"+xyz+"'",con)
Dim rdr As OleDbDataReader = sqlx.ExecuteReader()
If rdr.Read = True Then
    frmviewsdets.txtsnumber.Text = rdr("StudentNumber")
    frmviewsdets.txtfname.Text = rdr("SFirstName")
    frmviewsdets.txtsname.Text = rdr("SSurname")
    frmviewsdets.txttgroup.Text = rdr("TutorGroup")
    frmviewsdets.txtascore.Text = rdr("ALISScore")
    frmviewsdets.txtgcsemath.Text = rdr("GCSEMathsGrade")
    frmviewsdets.txtattend.Text = rdr("Attendance")
    frmviewsdets.txtclassid.Text = rdr("ClassID")
    frmviewsdets.txtpword.Text = rdr("SPassword")
End If
rdr.Close()
con.Close()
frmviewsdets.btndeletesdets.Hide()
frmviewsdets.btnaddsdets.Hide()
frmviewsdets.btnviewsdets.Hide()
frmviewsdets.Show()
Me.Hide()

Put everything in a try catch block

poojavb 29 Junior Poster

U are not incrementing the value anywhere so it wont show any value....there shud be a database or something that will store the max value and then increment the corresponding value for the combobox item....

poojavb 29 Junior Poster

I have done the connection but by providing modules...check if it helps u...

  1. for ms access

    Imports System.Data.OleDb
    
    Module DBConnection
    
    Public Connection As OleDbConnection = New OleDbConnection()
    Public Function Open_DB_Connection() As String
        Try
            Dim EntireFile As String = Application.StartupPath & "\HMS.mdb"
    
            Connection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0.; " & "Data Source=" & EntireFile
            Connection.Open()
            Return "Success"
        Catch ex As Exception
            Debug.Print(ex.Message & "in DBConnection_Module")
            Return "Fail"
            Exit Function
        End Try
    End Function
    
    Public Function Close_DB_Connection() As String
        Try
            Connection.Close()
            Return "Success"
        Catch ex As Exception
            Debug.Print(ex.Message & "in DBConnection_Module")
            Return "Fail"
            Exit Function
        End Try
    End Function
    
    End Module
    
  2. SQL server

    Imports System.Data.SqlClient
    
    Module DBConnection
    
    Public Connection As SqlConnection = New SqlConnection()
    Public Function Open_DB_Connection() As String
        Try
            Connection.ConnectionString = "Server=.\SQLEXPRESS;" & _
                    "Database=HMS;Trusted_Connection=True"
            Connection.Open()
            Return "Success"
        Catch ex As Exception
            Debug.Print(ex.Message & "in DBConnection_Module")
            Return "Fail"
            Exit Function
        End Try
    End Function
    
    Public Function Close_DB_Connection() As String
        Try
            Connection.Close()
            Return "Success"
        Catch ex As Exception
            Debug.Print(ex.Message & "in DBConnection_Module")
            Return "Fail"
            Exit Function
        End Try
    End Function
    
    End Module
    
  3. I am not sure for Oracle...

Create the module once and when we need to call the open connection just call the function and same for close connection

 Dim Open_DB_Con As String
 Open_DB_Con = Open_DB_Connection()


 Dim Close_DB_Con As String
 Close_DB_Con = Close_DB_Connection()

I know its too long but still worthy....

u can also give success msg if the connection suceeds and also a failure message if it fails after the function is called....

like

    If Open_DB_Con = …
poojavb 29 Junior Poster

What is the issue u r facing in this??? please explain in detail

poojavb 29 Junior Poster

Okkk...after getting the days from the timespan we can apply the condition and get what is required...

poojavb 29 Junior Poster

Does the datetimepicker contain the due date data or the current date???

In the amount text box are u going the caluclate the due amount???

The print and Save button will obvioulsy print the form but where are u saving the data???

poojavb 29 Junior Poster

For 4th query

SELECT distinct first_name,last_name, sum(total_price)
FROM Customer, Order
WHERE Customer. customer_id=Order.customer_id AND customer.customer_id=87162412 
group by first_name,last_name

For 5th query

select Customer.customer_id, first_name,last_name 
from Customer, Order 
WHERE Customer.customer_id=Order.customer_id 
group by customer.customer_id,first_name,last_name 
having sum(total_price)>5000
poojavb 29 Junior Poster

This is just for ur reference / knowledge

I will tell u what I have done....I had to generate a bill report based on Appointment...the column AppointmentDate in my Access database was a date/time datatype...

So to create a paramenter....u have to first make the report set and then

  1. Right click on Parameter Fields in ur Crystal report Field Explorer -> New -> GiveName to parameter and Set the type as Date

this way a parameter will get created....

Now to link the paramaeter with ur database....while setting the report u must have added the table to cyrstal report right???

so know

  1. Right click on the cyrstal report -> Report -> Selection formula -> Record
  2. A Report Selction Formula Editor window will be opened
  3. Map the parameter with the database column...eg in my case {Appointment.ApptDate} = {?fromdate}

where Appointment is tablename, ApptDate is columnname and ?fromdate is the parameter created....

this way u can create parameters for all the three of ur reguirements and call it in the form load or button click event where u want to call the crystal report

Hope it helps u....
If u need any help be free to ask... :)

poojavb 29 Junior Poster

I have used datetime...in this timespan wont be required...right??? coz he just wants the days....

poojavb 29 Junior Poster

Keep a track of the user logged in the application and save the value in database and then u can call the value to ur next form with the help of select query

poojavb 29 Junior Poster

Yes this values shud be stored in database so that u wont miss the data and even in future u would need it....keep a column in database to store the values....

poojavb 29 Junior Poster

I guess u want to display the username from the login form to main form after successful login, am i RIGHT??

if txtUsername has the text for username then while calling the second form u can write as below

'this code is to be written in in form1 before calling form2

Form2.Textbox1.Text = txtUsername.Text
Form2.show()

Guess this is what u want....

poojavb 29 Junior Poster

What issue are u facing now???

poojavb 29 Junior Poster

But shud I ask u y do u need a datatable if u can login without it???

check my below code

 Try
                Dim myCommand As OleDbCommand
                myCommand = New OleDbCommand("SELECT * FROM userlogin where UserName='" & txtUsername.Text & "' and Password='" + txtPassword.Text + "'", Connection)
                Dim reader As OleDbDataReader = myCommand.ExecuteReader
                If reader.Read = True Then
                    If String.Compare(txtUsername.Text, reader("UserName"), False) Or String.Compare(txtPassword.Text, reader("Password"), False) Then 'for case sensitivity
                        MsgBox("Incorrect Credentials")
                        txtPassword.Text = ""
                        txtUsername.Text = ""
                        txtUsername.Focus()
                    Else
                        frmMain.lblWelcome.Text = "Welcome, " + reader("DrName") 'show the main form with the User First Name
                        frmMain.Show()
                        Me.Close()
                    End If
                Else
                    MsgBox("Login Failed. Try Again")
                    txtPassword.Text = ""
                    txtUsername.Text = ""
                    txtUsername.Focus()
                End If
                    reader.Close()
            Catch ex As Exception
                MsgBox("Error Connecting to Database: " & ex.Message)
            End Try

Check if this helps u....

poojavb 29 Junior Poster

What kind of database is it?? Access, MSSQL or MYSQL?

I derived a query in Access
hope ur colname is a datetime field

SELECT *
FROM tablename
WHERE (format(colname,"yyyy")<Year(Now())-4);
poojavb 29 Junior Poster

I would go with u both Mitja and Unhnd but what if we give the code in specific format

like if we tell the user to enter the date suppose yyddmm format and on validating event check and then convert the date....if not possible print error msg and if correct show the format...

like the one below....correct me if I m wrong....i know its waste of time for manual entry since user can enter any garbage value....

this code I have written in textbox validating event.

 Try

        Dim strDate As String = TextBox1.Text
        Dim d As Date = New Date(2000 + strDate.Substring(0, 2), strDate.Substring(2, 2), strDate.Substring(4, 2))
        Label6.Text = d.ToString("yyyy/MM/dd") 'Label6 will display the date

 Catch ex As Exception
        MsgBox(ex.Message)
 End Try

the datetimepicker is the best option to work upon

poojavb 29 Junior Poster

This code shud be placed in the form load event....or the button click if u r generating the report on button click.....

this code shud be placed wherever u r showing the crystal report...

check my below code just for reference

I have a form rptBill in which I have placed the crystal report viewer

On the form load event I am calling the below code...

Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared

Public Class rptBill

    Private Sub rptBill_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim crtableLogoninfos As New TableLogOnInfos
        Dim crtableLogoninfo As New TableLogOnInfo
        Dim crConnectionInfo As New ConnectionInfo
        Dim CrTables As Tables
        Dim CrTable As Table

        Dim cryRpt As New ReportDocument
        cryRpt.Load("cystal report path") 'when any doctor and date is selected


        With crConnectionInfo
            .ServerName = database name
            .DatabaseName =  database name
            .UserID = username
            .Password = password
        End With
        CrTables = cryRpt.Database.Tables
        For Each CrTable In CrTables
            crtableLogoninfo = CrTable.LogOnInfo
            crtableLogoninfo.ConnectionInfo = crConnectionInfo
            CrTable.ApplyLogOnInfo(crtableLogoninfo)
        Next

        'the below code is because I had parameters in my crystal report....

        Dim crParameterFieldDefinitions As ParameterFieldDefinitions
        Dim crParameterFieldDefinition As ParameterFieldDefinition
        Dim crParameterValues As New ParameterValues
        Dim crParameterDiscreteValue As New ParameterDiscreteValue

        crParameterDiscreteValue.Value = frmMain.dtpFromBill.Value.ToString("yyyy-MM-dd")
        crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
        crParameterFieldDefinition = crParameterFieldDefinitions.Item("fromdate")
        crParameterValues = crParameterFieldDefinition.CurrentValues

        crParameterValues.Clear()
        crParameterValues.Add(crParameterDiscreteValue)
        crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)


        crParameterDiscreteValue.Value = frmMain.dtpToBill.Value.ToString("yyyy-MM-dd")
        crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
        crParameterFieldDefinition = crParameterFieldDefinitions.Item("todate")
        crParameterValues = crParameterFieldDefinition.CurrentValues

        crParameterValues.Add(crParameterDiscreteValue)
        crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)

        crParameterDiscreteValue.Value = frmMain.txtPatIDBill.Text
        crParameterFieldDefinitions = cryRpt.DataDefinition.ParameterFields
        crParameterFieldDefinition = crParameterFieldDefinitions.Item("patid")
        crParameterValues = crParameterFieldDefinition.CurrentValues

        crParameterValues.Add(crParameterDiscreteValue)
        crParameterFieldDefinition.ApplyCurrentValues(crParameterValues)

        'show rhe cystal report...

        crvBill.ReportSource = cryRpt
        crvBill.Refresh()
    End Sub
End Class
poojavb 29 Junior Poster

I tried one method....

Assuming u will have a datetimepicker that will show the due date / it can be a label or text box also just to store the value
One label or textbox that will have a due Amount/per day that needs to be paid
last the result box to show the total amount to be paid
One button that will generate the amount

I tried the following method on button click event

 Dim d2 As DateTime 'will have the value for due date
 Dim d3 As DateTime 'will be the current date
 d2 = DateTimePicker2.Value.ToString("MM/dd/yyyy") 'formatting the date
 d3 = Date.Today
 Dim days As Long
 days = DateDiff("d", d2, d3) 'days will contain the date difference from due date to current date
 Label1.Text = days 'just storing the date difference, can comment it if u dont want
 Label4.Text = Integer.Parse(days) * Integer.Parse(Label2.Text) 'will show the result of the due amount to be paid
poojavb 29 Junior Poster

I have done the same thing for username and password...check if it works for u

Why do u write the Item(1) code cant it be just written with reader name and quote brackets column name?
reader("DrName")

if ur case sensitivity code is creating error then check below

     Try
                    Dim myCommand As OleDbCommand
                    myCommand = New OleDbCommand("SELECT * FROM userlogin where UserName='" & txtUsername.Text & "' and Password='" + txtPassword.Text + "'", Connection)
                    Dim reader As OleDbDataReader = myCommand.ExecuteReader
                    If reader.Read = True Then
                        If String.Compare(txtUsername.Text, reader("UserName"), False) Or String.Compare(txtPassword.Text, reader("Password"), False) Then
                            MsgBox("Incorrect Credentials")
                            txtPassword.Text = ""
                            txtUsername.Text = ""
                            txtUsername.Focus()
                            ErrorProvider1.Clear()
                        Else
                            frmMain.lblWelcome.Text = "Welcome, " + reader("DrName")
                            frmMain.Show()
                            Me.Close()
                        End If
                    Else
                        MsgBox("Login Failed. Try Again")
                        txtPassword.Text = ""
                        txtUsername.Text = ""
                        txtUsername.Focus()
                        ErrorProvider1.Clear()
                    End If
                        reader.Close()
                Catch ex As Exception
                    MsgBox("Error Connecting to Database: " & ex.Message)
                End Try
poojavb 29 Junior Poster

while loading the crystal reports pass the database connection along with the username and password and then try to call the crystal report...

 Dim crtableLogoninfos As New TableLogOnInfos

    Dim crtableLogoninfo As New TableLogOnInfo
    Dim crConnectionInfo As New ConnectionInfo
    Dim CrTables As Tables
    Dim CrTable As Table

    Dim cryRpt As New ReportDocument
    cryRpt.Load("Crystal report path goes here") 

           With crConnectionInfo
        .ServerName = databasename
        .DatabaseName = databasename
        .UserID = "your username"
        .Password = "your password"
    End With
    CrTables = cryRpt.Database.Tables
    For Each CrTable In CrTables
        crtableLogoninfo = CrTable.LogOnInfo
        crtableLogoninfo.ConnectionInfo = crConnectionInfo
        CrTable.ApplyLogOnInfo(crtableLogoninfo)
    Next

    'show the crystal report
poojavb 29 Junior Poster

Dim Avail As String = rid.Item(4)
what is Item(4) ...u shud write

Dim Avail As String=rid("columname") and check

poojavb 29 Junior Poster

Yes so instead of displaying the msgbox u can keep a track of the number of years...

Check the scneario what I have done...

2 datetimepicker - 1 with current date and the second that will be derived from datetimepicker2

one label that will give the number of years only if it has completed the year.

Private Sub DateTimePicker2_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker2.ValueChanged

    Dim d1 As DateTime = DateTimePicker1.Value
    Dim d2 As DateTime = DateTimePicker2.Value
    Dim Year1 As Integer
    Dim days As Long
    days = DateDiff("d", d2, d1)
    Debug.Print(days.ToString & " Days")
    If days < 365 Then
        Year1 = 0
    Else
        Year1 = days / 365
    End If
    Label1.Text = Year1.ToString
End Sub

Hope this is what u need

poojavb 29 Junior Poster

Mitja - is this a VB.net code???

poojavb 29 Junior Poster
Dim di As New IO.DirectoryInfo("Your directory path")
                    Debug.Print("di: " + di.ToString)
                    Dim diar1 As IO.FileInfo() = di.GetFiles()
                    Dim dra As IO.FileInfo
                    'list the names of all files in the specified directory
                    For Each dra In diar1
                        lstFiles.Items.Add(dra) 'all files present in the directory are viewed in list box
                    Next

hope it helps u...

Jx_Man commented: VB.Net solution for VB6 ? -3
poojavb 29 Junior Poster

What issue are u facing now??? does ur Sections column in database contain any value??? in which procedure are u writting this code???

poojavb 29 Junior Poster

then first calculate the number of days and check if actually its greater than 365 days then u can use what u want....

 Dim d1 As New DateTime(2010, 12, 31)
        Dim d2 As New DateTime(2012, 1, 1)
        Dim days As Long
        days = DateDiff("d", d1, d2)
        Debug.Print(days.ToString & " Days")
        If days < 365 Then
            MsgBox("Year not completed")
        Else
            MsgBox("Year completed")
        End If
poojavb 29 Junior Poster

paste ur code so that we can check if u are missing out something....

poojavb 29 Junior Poster

for this u will have to make three different reports and based on the input in the crsytal report u can get the output...

eg if u r passing todays date as a parameter it will show the current date report...

for week u need to select a start date and add 6 days to it and then show the report on weekly basis....

same condition will be for monthly report ....

try to create a crystal report then u can ask for how to proceed with it....

poojavb 29 Junior Poster

I had a code for this...but I was having a text box will tells the interval...

Suppose the doctor starts his day at 9 am morning and ends at 6pm evening and the appointment interval is 30 mins then the result will be displayed in one combo box with the interval differnce....but the doctor timings should be stored in the database...

check for the below code....

it shows the data in a 24 hr format

      cboAppTime.Items.Clear()

            Dim starttime As DateTime = FormatDateTime("00:00")
            Dim endtime As DateTime = FormatDateTime("00:00")
             Dim duration As New TimeSpan

                starttime = frmApptSchedule.txtSunST.Text 'contains the complete start time of the doctor i.e. 09:00
                endtime = frmApptSchedule.txtSunET.Text 'contains the complete start time of the doctor i.e. 20:00

               duration = TimeValue(endtime.ToString) - TimeValue(starttime.ToString)
            '   Debug.Print("endtime: " + endtime)
            '     Debug.Print("starttime: " + starttime)
            '     Debug.Print("duration: " + duration.ToString)
            Dim Dur As Integer = duration.Hours
            Dim Dura As Integer = Integer.Parse(txtDuration.Text)
            Do Until starttime >= endtime
                cboAppTime.Items.Add(FormatDateTime(starttime.TimeOfDay.ToString, DateFormat.ShortTime))
                starttime = starttime.AddMinutes(Dura)
            Loop

Hope it helps u

poojavb 29 Junior Poster

Add paranthesis and use the OR instead of AND and see if it works...if u r grouping it means it has to fulfill the condition...

poojavb 29 Junior Poster

The separator value takes the year value as whenever ur will enter any other format for date except for separator as "," it will show the error and the error is at where u have initialized year...

add the try catch block before the initialization as below and check one

import java.util.Calendar;
import java.io.*;

public class DayOfYear 
{
    public static void main(String[] args) throws IOException 
    {
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(isr);
        System.out.print("Enter the date (yyyy,mm,dd): ");
        String date = in.readLine();
        Calendar cal = Calendar.getInstance();
        String[] seperate = date.split(",");
        System.out.println(seperate[0]);
        try 
        {
            int year = Integer.parseInt(seperate[0]);
            int month = Integer.parseInt(seperate[1]) - 1;
            int day = Integer.parseInt(seperate[2]);
            if (year < 1 || month < 0 || month > 12 || day < 0 || day > 31) 
            {
                System.out.println("The date is invalid");
            } 
            else 
            {
                cal.set(year, month, day);
            }
            int dayOfYear = cal.get(Calendar.DAY_OF_YEAR);
            System.out.println("Day of Year :" + dayOfYear);
        } 
        catch (Exception e) 
        {
            System.out.println("The format is invalid");
        }
    }
}
poojavb 29 Junior Poster

I tried the below way....check if it works for u...or u can make some changes

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class NumberGuess{
    public static void main(String[]args){
        Scanner sc = new Scanner(System.in);
        Random rnd = new Random();
        int rndNum = rnd.nextInt(100),
        input = 0,
        tries = 0;
        guessIntro();
        do{
            System.out.println(rndNum);
            input = getInput(sc);
            tries++;
            checkForWin(input,rndNum,tries);
            checkForMatches(input,rndNum,tries);
        }while(checkForExit(input,rndNum));
    }
    public static int getInput(Scanner sc){
        //System.out.println("In getInput");
        System.out.print("Your guess? ");
        String strInput;
        int tempInput = 0;
        strInput = sc.next();
        Pattern p = Pattern.compile( "([0-9][0-9])" );
        Matcher m = p.matcher(strInput);
        if  (m.matches() )
            tempInput = Integer.parseInt(strInput);

        else
        {
            System.out.println("\" "+strInput+"\" is not an integer;"+
            " try again.");
            getInput(sc);
        }
        return tempInput;
    }
    public static void checkForMatches(int input, int rndNum, int tries){
        int matches = 0;
        int flag=0;
        System.out.println("Input: "+input);
        if(input == 0){
            //returns nothing, so there's no incorrect message
            System.out.println("Error understanding number. Please enter again");
            return;
        }
        if(input == -1){
            //returns nothing, so there's no incorrect message
            return;
        }
        if(input%10 == rndNum%10 || input%10 == rndNum/10){
        //  System.out.println("if");
            matches++;
            System.out.println("1st : "+matches);
            flag=1;
        }
        else
        {
            flag=0;
        }
        if(input/10 == rndNum%10 || input/10 == rndNum/10){
            System.out.println("else if");
            matches++;
        //  System.out.println("2nd : "+matches);   
            flag=1;
        }
        else
        {
            flag=0;
        }
System.out.println("Macthes: "+matches);
        if(flag==0){
        //  System.out.println("else");
            matches = 0;
            System.out.println("Incorrect (hint: "+matches+" digits match)");
        }
        else if(flag==1)
        {
            System.out.println("Incorrect (hint: "+matches+" digits match)");
        }
    }

    public static boolean checkForExit(int input, int rndNum){
        if(input==-1){
            System.out.println("My secret number was "+rndNum);
            return false;
        }
        else{
            return true;
        }
    }
    public static void checkForWin(int input, int rndNum, int tries){ …