Going through a tutorial but I cannot figure out how to do this. It wants me to have the program display all 10 names previously entered after the quit sub. I've experimented with some stuff but cannot figure out how to do this.
'ARRAYS.BAS
'List handling with arrays
dim names$(10) 'set up our array to contain 10 items
[askForName] 'ask for a name
input "Please give me your name ?"; yourName$
if yourName$ = "" then print "No name entered." : goto [quit]
index = 0
[insertLoop]
'check to see if index points to an unused item in the array
if names$(index) = "" then names$(index) = yourName$ : goto [nameAdded]
index = index + 1 'add 1 to index
if index < 10 then [insertLoop] 'loop back until we have counted to 10
'There weren't any available slots, inform user
print "All ten name slots already used!"
goto [quit]
[nameAdded] 'Notify the name add was successful
print yourName$; " has been added to the list."
goto [askForName]
[quit]
end
Insert this code between [quit] and end:
for I = 0 TO 10
print names$(I)
next I
That'll work ;)
Related
I'm using an Excel userform to push data entered on the form into a Word Document. The Word document has several tables and the data from the form textbox controls needs to go into specific cells on the Word document. There are 15 checkboxes with 15 matching textboxes on the Excel form, so I figured the easiest way to handle it is with an array so I could loop through it.
Addressing the checkboxes (the Program array) isn't an issue because they're named "chkbox1-chkbox15" and there are matching Content Controls in the Word table tagged chkbox1-chkbox15, so that loop works properly.
The problem is with the textboxes' text. The cells the data needs to go in is kind of all over the place and I don't have the luxury of altering the table layout. So I figured I'd create a 15-element array that contains the row & column location of the target cell.
Here's the relevant part of my code:
Dim ImpactCells(15) As String
'Specify Form cell locations for specific programs
ImpactCells(0) = "4,2" 'Program 1
ImpactCells(1) = "5,2" 'Program 2
ImpactCells(2) = "6,2" 'Program 3
ImpactCells(3) = "4,4" 'Program 4
ImpactCells(4) = "5,4" 'Program 5
ImpactCells(5) = "6,4" 'Program 6
ImpactCells(6) = "7,2" 'Program 7
ImpactCells(7) = "10,2" 'Program 8
ImpactCells(8) = "11,2" 'Program 9
ImpactCells(9) = "12,2" 'Program 10
ImpactCells(10) = "13,2" 'Program 11
ImpactCells(11) = "10,4" 'Program 12
ImpactCells(12) = "11,4" 'Program 13
ImpactCells(13) = "12,4" 'Program 14
ImpactCells(14) = "13,4" 'Program 15
For i = 0 To 14 'Count of Programs Array
If Programs(i) <> "" Then 'If array element is not blank
Set cc = .SelectContentControlsByTag("Program" & i + 1).Item(1) 'Select the Content Control with the Program(array index) tag
cc.Checked = True 'Check it
End If
If ImpactCount(i) <> "" Then
'Code to populate cells here
.Tables(9).Cell(ImpactCells(i)).Range.Text = Me.Controls("txtImpact" & i + 1).Text
End If
Next
The line thats causing an error is:
.Tables(9).Cell(ImpactCells(i)).Range.Text = Me.Controls("txtImpact" & i + 1).Text
It says: Compile Error: Argument not optional and highlights the word cell. The code works when I put specific cell locations instead of ImpactCells(i).
Any help would be appreciated. Suggestions for a more efficient way of doing this would also be great, keeping in mind that I can't modify the way the Word table is laid out.
Cell requires a row and a column argument (both numeric). You're passing a single String argument.
You could try something like this:
Dim arr
'...
'...
If ImpactCount(i) <> "" Then
'Code to populate cells here
arr = split(ImpactCells(i),",") 'convert to array
.Tables(9).Cell(arr(0), arr(1)).Range.Text = _
Me.Controls("txtImpact" & i + 1).Text
End If
I have been reading a text file a object and create a list with the contents.
textfile:
Activity Time Location
Football 8-9 Pitch
Basketball 9-10 Gym
Lunch 11-12 Home
Read 13-14 Library
Swim 14-15 Pool
openTime = 6
closeTime = 15
come = int(input('When do you want to come?'))
leave = int(input('When do you want to leave?'))
# endtime_of_activity and startTimeofactivity is equal to the startingtime
# of each activity and the end time of each activity in the textfile
# (taken from a list that I have been splitting).
for i in range(len(my_list)):
item = my_list[i]
if (i == 1):
continue
if closeTime <= come <= endtime_of_activity and startTimeofactivity < leave <= closeTime:
print(item.activities)
My question: As you can read in the textfile there are some activities appering on different times. For example football between 8 and 9. With the code I want to be able to skip the second element (basketball) as the code is doing, however, I want the if statement under "continue" to work. If i type that im coming 8 and leaving at 12 I want all the activities (excluding the second one) to show. This works for me when I'm doing a regular for-loop without skiping the second activity, like when im just writing: for i in my_list, then adding on the condition, but when Im doing the code above it shows me all the activites (except basketball) independeltly of when I chose to come and leave. What have I missed? How could I write the code better?
If you want to skip a certain activity, simply test if the activitiy to be printed is the same and skip it if it is:
with open("f.txt","w") as f:
f.write(("Activity Time Location\nFootball 8-9 "
"Pitch\nBasketball 9-10 Gym\nLunch 11-12"
" Home\nRead 13-14 Library\nSwim 14-15"))
data = []
with open("f.txt") as f:
for line in f:
act, time, what = (line.strip().split(" ") + ["","",""])[:3]
if data:
try:
time=list(map(int, time.split("-")))
except ValueError:
continue # invalid time: skip row
data.append([act,time,what])
header,*data = data
openTime = 6
closeTime = 15
come = 9
leave = 12
skip=set(["Basketball"])
fmt = "{:<15}"*len(header)
print(fmt.format(*header))
for act,(start,stop),what in data:
if act in skip:
continue
if start >= come and stop <= leave and openTime <= come and closeTime >= leave:
print(fmt.format(act, f"{start}-{stop}", what))
Output:
Activity Time Location
Football 8-9 Pitch
Lunch 11-12 Home
I was wondering if there was a way to tell excel not to display some variables if the VLookup function couldn't find anything.
Here's roughly what my code does: take some numbers in another excel workbook by looking them up, compare that value from the previous year and take the difference, display that difference in another spreadsheet, all in one big merged cell.
Some excerpts from my code:
cashO = Val(Application.VLookup("cash" & "*", Workbooks("creditreport.csv").ActiveSheet.Range("A1:F199"), 4, False))
Then the difference cash = Round(cashN - cashO, 0)
Then the Display: MergedCell.Value = "Cash increased by" & cash
But I dont want to display cash if it couldnt find cash in the first place (if this is the case, cash = 0 both when cash couldnt be found and when the change is null).
I was thinking of creating an array with all my variables (cash, ...) and then loop through it. But I couldn't find anything online on "if not found dont display anything".
Best,
You can use an if else statement to check the value of cash and write the value if cash has a value and some other message like "no change" or "no previous value" if that's the case.
if cash = 0
MergedCell.Value = "No Change"
Else
MergedCell.Value = "Cash increased by" & cash
End If
Or you could just check if the function returns an error:
if iserror(Application.VLookup("cash" & "*", Workbooks("creditreport.csv").ActiveSheet.Range("A1:F199"), 4, False)) then
cash = 0
else
cashO = Val(iserror(Application.VLookup("cash" & "*", Workbooks("creditreport.csv").ActiveSheet.Range("A1:F199"), 4, False))
....other statements for whatever...
end if
I hope I understood you, that you mean that VLookup didn't find a match for "cash" , if that's the case you need error-handling.
If that's the case, try the code below:
Sub VLookup_Test()
On Error Resume Next
cashO = Val(Application.VLookup("cash" & "*", Workbooks("creditreport.csv").ActiveSheet.Range("A1:F199"), 4, False))
If Err.Number <> 0 Then
MsgBox "cashO not found" '
' Do your actions if cashO not found with VLookup
End If
On Error GoTo 0
End Sub
I'm creating a method where the user puts in a "PIN" number to access different methods.. Yes it's an ATM..
I'm trying to figure out how to make it so that the user gets a specific amount of tries until the program exit's..
After a bunch of research I haven't very well found anything useful.. The only thing I've found is to use .to_s.split(//) in order to add the number of the try into an empty array. Which doesn't make sense to me because why would you make an integer into a string..?
So my question is, how do you make it so that users only have a certain amount of tries, 3, until they get kicked out of the program?
Main source:
#!/usr/bin/env ruby
################
#ATM Rewrite
#
#Creator Lost Bam Not completed yet.
#
#11/19/15
##################
require_relative 'checking.rb'
require_relative 'savings.rb'
require_relative 'exit.rb'
require_relative 'loan.rb'
require_relative 'transfer.rb'
require_relative 'redirect.rb'
class ATM
attr_accessor :name, :checking_account, :savings_account, :pin_number, :transfer, :loan
def initialize( name, checking_account, savings_account )
#name = name
#checking_account = checking_account
#savings_account = savings_account
#pin_number = pin_number
end
end
##############
def pin
x = []
puts "Enter PIN Number:"
input = gets.chomp.to_i
if input == 1234
menu
else
x += 1.to_s.split(//) #<= This is what I found to convert integer to Array
puts "Invalid PIN, try again:"
input = gets.chomp
if x == 3
bad_pin
end
end
end
############
def menu #add #{name} on line 41
puts <<-END.gsub(/^\s*>/, ' ')
>
>Welcome thank you for choosing Bank of Bam.
>You may choose from the list below of what you would like to do
>For checking inquiries press '1'
>For savings account information press '2'
>To transfer funds press '3'
>To either apply for a loan, or get information on a loan press '4'
>To exit the system press '5'
>
END
input = gets.chomp
case input.to_i
when 1
checking_information
when 2
savings_information
when 3
transfer_funds
when 4
loan_info
when 5
exit_screen
else
puts "Invalid option please try again"
menu
end
end
def bad_pin
abort('Invalid PIN exiting sytem..')
exit
end
pin
Tried something new:
def pin
x = 3
puts "Enter PIN(#{x} attempts left):"
pin_num = gets.chomp
case pin_num.to_i
when 1234
menu
else
puts "Invalid PIN"
x -=1
return pin
if x == 0
bad_pin
end
end
end
It doesn't increment the number down it just keeps saying 3 tries left:
Enter PIN(3 attempts left):
4567
Invalid PIN
Enter PIN(3 attempts left):
45345
Invalid PIN
Enter PIN(3 attempts left):
6456
Invalid PIN
Enter PIN(3 attempts left):
4564
Invalid PIN
Your problem is that every time you recall the method the value of x resets again. You need to have a loop inside the pin method that'll keep track of attempts.
def pin
x = 3
while (x > 0) do
puts "Enter PIN(#{x} attempts left):"
pin_num = gets.chomp
case pin_num.to_i
when 1234
menu
else
puts "Invalid PIN"
x -=1
puts "no tries left" if x == 0
break if x == 0
end
end
end
Stay in the method. Recalling the method starts you back at three attempts.
EDIT:
Ok I got how arrays work and that part seems to work. Im still having a problem with the functions. I do not understand how functions work correctly. I need to put something in the ( ) obviously but I dont understand what. You can see I have
search=findmonth()
Im not sure if that is even a good code to use I then have it where it calls up the function but of course because I dont know how to do functions it doesnt work. If someone can explain how functions work that would be great. All the information I have makes it really confusing and doesnt show real examples that explain anything.
This is the assingment, put it in code just so its smaller
Create two arrays
1. Monthname$(12) This array contains month names such as “January”, “February”, etc
2. MilesDriven(12) ‘ This array contains the miles driven for the month.
Notice that the MonthNames$(12) array is a string array while MilesDriven(12) is numeric array.
• Write a program to display the menu with the following options and ask for the user input.
Type P to populate miles and month name.
Type S to search for Month.
Type M to search for Month name with smallest Miles
Type L to search for MonthName with Largest Miles
Type E to exit.
• • If the user types P.
o Populate all the arrays.
• • If the user types S then:
o Ask the user for the Month Name.
o Search the array for that Month Name and find its position in the Monthname array.
o Display the MonthName$, and MilesDriven at the position found during the above search.
• • If the user types M then:
o Search the array for the smallest miles in MilesDriven array and find its position.
o Display the MonthName$, and MilesDriven at the position found during the above search.
• • If the user types L then:
o Search the array for the largest Miles in MilesDriven array and find its position.
o Display the MonthName$, and MilesDriven at the position found during the above search.
• If the user types E. then:
o Terminate the program.
• If the user types any other option:
o Display the message “Invalid Choice. Try again” and go back and display the menu.
PS: You program must keep displaying the menu until the user types the option E, to exit the program."
This is the code I have so far.
Dim MonthNames$(12)
MonthNames$(1) = "January"
MonthNames$(2) = "Febuary"
MonthNames$(3) = "March"
MonthNames$(4) = "April"
MonthNames$(5) = "May"
MonthNames$(6) = "June"
MonthNames$(7) = "July"
MonthNames$(8) = "August"
MonthNames$(9) = "September"
MonthNames$(10) = "October"
MonthNames$(11) = "November"
MonthNames$(12) = "December"
Dim MilesDriven(12)
Search=Findmonth()
E=0
While E = 0
Print "Press P to populate miles and month name"
Print "Press S to search for Month"
Print "Press M to search for Month name with smallest Miles"
Print "Press L to search for MonthName with Largest Miles"
Print "Press E to exit"
Input Answer$
Select Case Answer$
Case "P", "p"
For position = 1 to 12
Print "Enter the amount of miles driven in "; MonthNames$(position)
Input MilesDriven(position)
Next
Case "S", "s"
Function Findmonth()
Print “Please enter a month you want to search for”
Input Month$
For position = 1 to 12
If (Month$ = MonthName$(position)) then
Print "You have driven "; MilesDriven(position); " "; "in the month of " MonthNames$(position)
Exit for
End if
Next
If (position > 12) then
Print “Please enter a valid month”
End if
End function
Case "M", "m"
Case "L", "l"
Case "E", "e"
E=1
Case Else
Print "You made a wrong selection. Please enter again"
End Select
Wend
For position = 1 to 12
Print MonthNames$(position)
Print MilesDriven(position)
Next
Print "Goodbye"
End
There is no need to populate the miles into the month array, rather you have two arrays side by side, such that Monthnames$(i) is the month name and MilesDriven(i) is the miles for that month.
Note that, reading your assignment's instructions, this "populating" should only happen when the user types "P", so move the initialising of your arrays into your Select statement like this:
Dim Monthnames$(12)
Dim MilesDriven(12)
E = 0
While E = 0
Print "Press P to populate miles and month name"
Print "Press S to search for Month"
Print "Press M to search for Month name with smallest Miles"
Print "Press L to search for MonthName with Largest Miles"
Print "Press E to exit"
Input Answer$
Select Case Answer$
Case "P", "p"
Monthnames$(1) = "January"
Monthnames$(2) = "February"
Monthnames$(3) = "March"
Monthnames$(4) = "April"
Monthnames$(5) = "May"
Monthnames$(6) = "June"
Monthnames$(7) = "July"
Monthnames$(8) = "August"
Monthnames$(9) = "September"
Monthnames$(10) = "October"
Monthnames$(11) = "November"
Monthnames$(12) = "December"
MilesDriven(1) = 10
MilesDriven(2) = 20
MilesDriven(3) = 30
MilesDriven(4) = 40
MilesDriven(5) = 50
MilesDriven(6) = 60
MilesDriven(7) = 70
MilesDriven(8) = 80
MilesDriven(9) = 90
MilesDriven(10) = 100
MilesDriven(11) = 110
MilesDriven(12) = 120
Case "S", "s"
Rem - put search by name here
Case "M", "m"
Rem - put search by for smallest miles here
Case "L", "l"
Rem - put search by for largest miles here
Case "E", "e"
E=1
Case Else
Print "You made a wrong selection. Please enter again"
End Select
Wend
Print "Goodbye"
End