Largest word in an Array - arrays

Hey i'm having problems creating a simple button for a programme which finds the largest word in an array and puts it into a textbox. I've done most of the coding (I hope) was wondering if somebody could help me actually with the code that finds the largest text in the array as I am struggling the most with that.
Private Sub btnLongName_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLongName.Click
Dim LongName As String
Dim LengthOfLongestName As Integer
Dim UltimateName As String
For i As Integer = 0 To 5
LongName = Members(i).Name
LengthOfLongestName = Len(LongName)
If Members(i).Name.Length > LengthOfLongestName Then
End If
Next i
txtResult.Text = "The longest name is " & UltimateName & " ."
End Sub
End Class
Thanks for your time - its for college homework, struggling big time on it :(
edit: I've edited the code

Since this is homework, I won't write the code for you; instead I'll try to give you some hints that will point you in the right direction.
Declare a variable of an appropriate type to hold the <longest value so far>, initialize it with the "shortest" value for that type.
Loop through all the values in the array (perhaps with a For or For Each loop)
Pseudo-code for the inside your loop:
If the Length of <the value being checked> exceeds _
the Length of the <longest value so far> Then
Assign <the value being checked> to the <longest value so far>
End If
When the loop finishes, the <longest value so far> will be the longest value in the array.
Notes
You can use MSDN as a reference on how to use a For loop or a For Each loop (If you haven't learned For loops yet, you can also use a Do Loop)
<the value being checked> will be different on each iteration through the loop; it should correspond to each consecutive value in your array. You can verify that this is working by setting a breakpoint.
You can get the length of a string by saying myString.Length
If you've learned about Functions, consider writing a function that takes an array as a parameter, and returns the longest value in the array.
There are certainly ways you could do this with LINQ, but I don't think that is the goal of the assignment ;-]
In response to Edit 1:
Your If statement needs to be inside of some sort of loop (For, For Each, Do, etc) I think this is the key concept that you are missing.
Instead of comparing LongName.Length to LengthOfLongestName, you need to compare the length of an entry in your array to LengthOfLongestName
You're on the right track with Members(0).Name.Length, but you can't just check element 0; you have to check every element in the array.
Given your current code, you'll probably be assigning <An entry in your array>.Name to LongName
The last index in a one-dimensional array is <array>.Length - 1 or <array>.GetUpperBound(0).
The following doesn't really address anything in your assignment, but I hope it will give you some ideas on how to go through all the items in your list:
' A For loop that does a message box for each of the numbers from 0 to 5 '
For i as Integer = 0 To 5
MessageBox.Show(i)
Next i
' Code that does a message box with the names of the 2nd, 3rd and last '
' entries in Members '
' (Remember that the first item is at 0, the second item is at 1, etc...) '
MessageBox.Show(Members(1).Name)
MessageBox.Show(Members(2).Name)
MessageBox.Show(Members(Members.GetUpperBound()).Name)
In response to Edit 2:
You're getting warmer...
You should only update LongName and LengthOfLongName if the current value is the longest you've seen so far (i.e. they should be assigned inside of the If statement)
You have to go to the last index of the array, not 5. See above (the response to your first edit) on how to get that last index.
You don't really need the UltimateName variable; you can just use LongName ;-]
You might want to use <stringVariable>.Length instead of Len(<stringVariable>) to be consistent.

What you are missing is a loop that checks each member, and putting the If statement inside it and make it compare the length of the name to the longest name that you have found so far. If the name is longer, put it in the variable for the longest found, and update the length variable.
You can either initialise the variables with the name of the first member and loop from the second member and on, or you can initialise the variables with an empty string and loop all the members. Personally I prefer the latter one.

Related

Visual Basic 2D Array Issue

I currently am having some trouble trying to get my program to work with a 2D array. I had it working earlier with a 1D array but I am totally lost now that I have to make these changes.
Below is what I currently have as my 2D array and the code that I thought would work for spitting out a letter grade but does not give me anything. Would anyone be able to tell me what I'm doing wrong?
Private strGrades(,) As String = {{"900", "A"},
{"815", "B"},
{"750", "C"},
{"700", "D"},
{"0", "F"}}
Dim strGradeSearch As String
Dim intRow As Integer
strGradeSearch = txtGrade.Text
For intRow = 0 To 4
If intRow > strGrades.GetUpperBound(0) Then
strGrades(0, intRow) = strGradeSearch
intRow += 1
End If
Next intRow
If intRow <= strGrades.GetUpperBound(0) Then
lblLetter.Text = strGrades(intRow, 0)
End If
Please take all the following as positive comments :-)
OK. looking at your code, there are tbh several issues. You're trying to treat strings as numbers. While a string can contain what looks like a number, it only contains a string of characters that happen to be numbers. They make sense to use, but to a computer, they aren't. There is often stuff that VB does in the background to try and make life easier, but to be honest, it can be a pain.
When comparing something like grades, you need to compare actual numbers, not strings that contain numbers. You'll potentially get unexpected results. You need to get the computer to convert the string to a number. See below.
Your loop wont actually do anything because the If statement will never execute the code inside it because intRow will never be greater than the last element of the array. Anyhow.. Onwards.
A way to convert strings to numbers is to user the Val function, though this "old" VB. The current way is to use Integer.Parse. Have a look at this link for some basic information about it.
Lets walk through what you want to do.
Get the string in the textbox.
Convert the string to a number.
Loop through the array and for each element, get the number stored as a string and convert it to a number and then compare it to the grade number.
If the grade is greater than any of the values, make a note of the
letter linked to the grade and stop searching through the loop.
Assign the letter that was found to the label.
The following code should do this
Dim strGrades(,) As String = {{"900", "A"},
{"815", "B"},
{"750", "C"},
{"700", "D"},
{"0", "F"}}
Dim intGradeSearch As Integer
Dim strGradeLetter As String = ""
intGradeSearch = Integer.Parse(TxtGrade.Text)
For i As Integer = 0 To 4
If intGradeSearch >= Integer.Parse(strGrades(i, 0)) Then
strGradeLetter = strGrades(i, 1)
Exit For
End If
Next
LblLetter.Text = strGradeLetter
End Sub
You dont need to check intRow after the loop has finished, because in this case, at some point in the loop, a grade letter will always be found if the number in the textbox is greater than or equal to a number in the array.
If you have any questions, please don't hesitate to ask.

Are my arrays incompatible?

I am trying to loop through an array that contains split strings, done via this line:
repHolder() = Split(rep, ",")
That's all fine and good, however, when I try to loop through this repHolder() array via a for loop, I am met each time with a subscript out of range error.
This makes no sense to me. When I step through the array it fails on the first element every time; this line:
If repHolder(j) = counter Then
I tried setting j to 0 and 1, both of which failed on the first sequence of the loop. This suggests to me because the array doesn't have a defined size; that I cannot loop through it this way, but that still makes little sense to me as it is still filled with elements.
Here is the entire code block of what I am trying to do:
Dim repHolder() As String
Dim strHolder() As String
Dim counter As Variant
Dim j As Integer
For Each rep In repNames()
repHolder() = Split(rep, ",")
Next rep
For Each rangeCell In repComboRange
k = 1
Do
If rangeCell.Value = repCombos(k) Then 'At this point, if rangecell = repcombos(k)
Range(rangeCell, rangeCell.End(xlToRight)).Copy
strHolder() = Split(rangeCell.Value, "/")
For Each counter In strHolder()
Stop
For j = 1 To 17
If repHolder(j) = counter Then
You are looping through repNames() and setting this new array via split (over and over again for each repName element...)
For Each rep In repNames()
repHolder() = Split(rep, ",")
Next rep
Every iteration of this loop resets repHolder() to a split of the rep element dropping whatever values were just set in that array in the previous iteration. So once it's done only the last element of RepNames() has been split into the repHolder() array.
For instance, if RepNames() looks like:
Element 0: "james,linda,mahesh,bob"
Element 1: "rajesh,sam,barb,carrie"
Element 2: ""
Then after all this iterating your repHolder array is going to be empty because there is nothing in the final element.
Stick a breakpoint (F9) on you For Each rangeCell In repComboRange line and look at your Locals pane in VBE. Check out the values that are stored in your repHolder() array at that point in time. I suspect there will be nothing in there.
The other oddball here is that you are looping 1 through 17. repHolder() will be a 0-based array so that should be 0 through 16. But... even that is nonsense since this really only makes sense as a For Each loop (or to use the uBound(repHolder) to determine how many times to loop:
For Each counter In strHolder()
Stop
For each repHolderElem in repHolder
If repHolderElem = counter Then
....
Next repHolderElem

Subscript out of range when trying to get last item of an Array

For example, I have a string A-456-BC-123;DEF-456;GHI-789. And I need to search for second part:DEF-456 with keyword 456. The potential problem here is that the first part A-456-BC-123 also has the keyword 456. Currently my logic is that, split the string first using ;, split each of it again using -, get the last item of this Array, search keyword 456. Another thing is that I don't want to do a full keyword match like DEF-456, I only want to use 456 as keyword to locate DEF-456, in other words, 456 should be the last segment of the string I want.
Here are my codes:
FirstSplit= split("A-456-BC-123;DEF-456;GHI-789",";")
For each code in FirstSplit
SecondSplit = split(FirstSplit,"-")
'get Array Count
Count = Ubound(SecondSplit)
'get the last item in Array
If SecondSplit(Count-1) = "456" Then
'doing something
End if
Next
Currently, an error will generate at SecondSplit(Count-1), saying that "Subscript out of range: '[number: -1]'"
Could someone tell me how to fix it?
The real problem is here:
SecondSplit = Split(FirstSplit, "-")
You should be splitting your element which you've stored in variable code from your For Each loop. By trying to split an array you should be getting a Type Mismatch error, but perhaps vbscript is forgiving enough to attempt and return a 0 element array back or something. Anyway:
SecondSplit = Split(Code, "-")
Also, to look at the last element just use:
If secondSplit(Ubound(SecondSplit)) = "456" Then
Subtracting 1 from the ubound would get you the second to last element.
You don't need to split it twice - what you're looking for is Right():
FirstSplit = split("A-456-BC-123;DEF-456;GHI-789",";")
For each code in FirstSplit
If Right(code, 3) = "456" Then
' do something
End If
Next
Though this would also match an entry like ABC-1456. If the - symbol is a required delimiter, you'd have to say If Right(code, 4) = "-456".

Display content of cell array corresponding to another cell array with Matlab

I have a dataset stored in SUBJ{s}.,and then fields SUBJ.WORDS{w} and SUBJ.RECALL{r}. I tried to create a loop that finds when SUBJ.RECALL corresponds to 1 (1=word remembered, 0 not remembered). After that I want to have displayed the words that correspond to the positions where SUBJ.RECALL is 1. Say
SUBJ{1}.WORDS{1}={‘Apple’, ‘Melon’, ‘Cheese’ ,’Pancakes’,Tomatoes’}% words presented.
`SUBJ{1}.RECALL{1}=[1 0 0 1 1]% 1=word recalled 0=word non recalled.
What I want is to display the words that have been recalled, meaning the words that correspond to 1 in SUBJ.RECALL.
I have done this:
for s=1:length(SUBJ)
for w=1:length(SUBJ.WORDS)
for r=1:length(SUBJ.RECALL)
if SUBJ{s}.RECALL{r}==1
disp(SUBJ{s}.WORDS{(SUBJ.RECALL{r}==1)})
end
end
end
end
Error: Attempt to reference field of non-structure array.
for s=1:length(SUBJ)
for w=1:length(SUBJ.WORDS)
for r=1:length(SUBJ.RECALL)
find(SUBJ{s}.RECALL{r}==1)
disp(SUBJ{s}.WORDS{(SUBJ.RECALL{r}==1)})
end
end
end
Error: Attempt to reference field of non-structure
Thanks in advance for any comment!
You probably do not need this many for-loops, as you can process the cell element contents using find. I included a sample code below. This works for your sample data, but might fail with whole dataset as i don't know the structure.
for s=1:length(SUBJ)
% Store in variables to make code more readable
words = SUBJ{s}.WORDS{1};
hits = SUBJ{s}.RECALL{1};
if max(hits) == 1 % Only print when hits
disp(words(find(hits)))
end
end

QTP - lbound() and ubound()

I'm having some troubles doing something easy: checking the most recent date in an array. I create an array of webelements. There are some dates in this array in "fixed" places and I want to take the most recent of them.
This is what I'm doing:
Set cc = Description.Create
cc("micclass").value="WebElement"
cc("name").value="arrow_down"
Set collcc=Browser("Br").Page("Page").ChildObjects(cc)
For i=lbound(collcc) to ubound(collcc)
Msgbox collcc(x).getroproperty("innertext")
x =x +9
Next
The problem is that the script stops at the beginning of the for, saying that there is a "wrong number of arguments or invalid property assignment ubound" (and the same happens with lbound.
What am I doing wrong?!
Just from memory, but i think ChildObjects does not return an array. Try with
for i = 0 to collcc.Count - 1
....
next
Child object is the collection of objects so you needs to loop through "for each " Snippet given below
for each col in collcc
Msgbox col.getroproperty("innertext")
Next
Thanks
Sai

Resources