VBS script random and switches - random

In the program below r is initialized as a rounded random number and the user is prompted to guess. If the user guesses correctly there is one prompt Else there is another prompt. The code looks right but when ran the Else case is chosen whether the user got the number right or not. Please help I have read over it so many times that it hurts.
Set WshShell = WScript.CreateObject("WScript.Shell")
'This script is designed to create a random number, and have a user guess the number
'If the user guesses the number incorrectly, negatively impact the users system
'if the user guess the number correctly, do nothing
dim InputValue
dim UserInput
'create a random number
dim r
randomize
r = int(rnd * 10)+1
'Allow the user to guess what number is correct
Input = inputbox ("Choose a number from one to ten, and choose wisely ;)", "Type a number.")
InputValue = Input
'Provide the user with feedback as to what his/her choice was and what the number actually was.
UserInput = "You typed " & InputValue & "." & " The number was " & r & "."
'echo the random generated number for test purposes
WScript.Echo r
Select Case InputValue
Case r
WScript.Echo "No action"
Case Else
WScript.Echo "Negative Action"
End Select

The issue is that InputValue is a String type because that's what's returned by the InputBox function and r is an Integer, so when you compare InputValue to r, you're comparing a string to an integer, i.e. apples to oranges.
Proof of concept:
Dim x
x = "5"
Dim y
y = 5
Select Case x
Case y
MsgBox "Yes"
Case Else
MsgBox "No" 'this is what happens.
End select
VBScript is not a strongly-typed language, i.e. it does not know about types really at all -- well, it kind of knows. It treats every variable as one type called a "variant" which itself can then have an affinity to a more specific type but in a very confusing and error-prone way. I'd say you should read this to learn more about it.
You can get into a lot of trouble with this unless you always make sure you know what "types" you're working with.
Try changing it to this:
InputValue = CInt(Input)
Now you're converting the "string" into an "integer" (the variables are both still actually "variants" but they have the same underlying affinity to integer). However, you want to be careful because someone might input a value that is not able to be converted to an integer, e.g. hello, and thus you'll get an error on this line. You will need to do some error checking first before converting it.

Related

How can I get the position of a CAD part via VBscript?

I want to write a VBScript, which outputs the position of a CAD part (x,y,z). The Input should be the partnumber. This is what I tried.
Sub CATMain()
dim pos(11)
for n = 1 to CATIA.Documents.Count
set Dokument = CATIA.Documents.Item(n)
for i = 1 to Dokument.product.products.Count
set InstDokument = Dokument.product.products.item(i)
If InstDokument = "my_part" Then
msgbox InstDokument.Name
InstDokument.Position.GetComponents pos
msgbox "Origin Point: X= " &pos(9) &" Y= " &pos(10) &" Z= " &pos(11)
End If
next
next
End Sub
I got an error in line 8 column 2. The object does not have the property or method.: Dokument.product
How can I solve that?
There are several problems with your code.
At the root is probably this:
set Dokument = CATIA.Documents.Item(n)
The CATIA documents collection will contain many documents which do not have windows and which the CATIA application maintains for it's own various internal purposes. So it is not assured that CATIA.Documents.Item(n) actually contains a CATProduct.
In most cases one is interested in the current active document, and it is retrieved like this:
Set Dokument = CATIA.ActiveDocument
Otherwise you can test for it
Set Dokument = CATIA.Documents.Item(n)
if typename(Dokument) = "ProductDocument" Then ...
Even after that you have problems. You are comparing the Document object to a string... and other things. Also without recursion you may never find your target instance if it is deeper then at the first level. It may also be possible that search may be a better way to find your instance then "Reading the tree".
Once you have corrected all your infrastructure errors your method for getting the transformation matrix is basically correct.

How to create Applescript dynamic variables

I have a script that has an array of terms. I'd like to create variables based on each term. I'm attempting to count how many times each term is chosen by the user and log a number associated with the term (also from user input).
My history with jQuery leads me to want to do something like this:
set term + "_Count" to term + "_Count" + 1
set term + "_Log" to term + "_Log" + inputNum
However, (obviously) that sort of syntax is not possible with AppleScript. Is there a way to concatenate a string onto a variable name?
-- for more reference, I'm trying to avoid listing every term out as I try to set 2 variables related to each term. I've currently got a long If/Then statement to set each one when the user picks a term.
term: "project"
termCount: 3 -- times activated
termLog: 120 --
minutes
I've been searching everywhere but haven't found anything conclusive for my question. Perhaps I just don't know the proper terms to search or maybe my whole approach is incorrect. Any help would be appreciated.
You really don’t. What you want is a dictionary datatype (aka "hash", "map", "associative array", etc), which store and retrieve values using arbitrary keys (most commonly strings). AS doesn’t have a native dictionary type, but for storing simple value types (boolean, integer, real, string) you can use Cocoa’s NSMutableDictionary class via the AppleScript-ObjC bridge:
use framework "Foundation"
set myDict to current application's NSMutableDictionary's dictionary()
myDict's setValue:32 forKey:"Bob"
myDict's setValue:48 forKey:"Sue"
(myDict's valueForKey:"Bob") as anything
--> 32
Short story:
Variable names are evaluated at compile time. Dynamic variables (evaluated at runtime) are not possible.
It's difficult to give an exact answer without seeing all of your code but you can use Concatenation to define new variables.
If you were to save this following code as an application, the item chosen and the amount of times it has been chosen, get stored in the script and the values get updated.
Again, it's difficult to pinpoint exactly what you need but this is an example of Concatenation and defining how many times an item has been chosen
property theUserChose : {"Project_1", "Project_2", "Project_3"}
property term_1_count : 0
property term_2_count : 0
property term_3_count : 0
property minutes : 120
property term : missing value
set resultValue to choose from list theUserChose ¬
with title "Make Your Choice" OK button name ¬
"OK" cancel button name "Cancel" without empty selection allowed
set resultValue to resultValue as string
if resultValue is item 1 of theUserChose then
set term_1_count to term_1_count + 1
set term to resultValue & "_" & term_1_count & "_" & minutes
else
if resultValue is item 2 of theUserChose then
set term_2_count to term_2_count + 1
set term to resultValue & "_" & term_2_count & "_" & minutes
else
if resultValue is item 3 of theUserChose then
set term_3_count to term_3_count + 1
set term to resultValue & "_" & term_3_count & "_" & minutes
end if
end if
end if
display dialog term

Beginners Visual Basic Help: I am to create a simple "game" which prompts a user to enter a number 1-10. That number must be stored

Beginners Visual Basic Help: I am to create a simple "game" which prompts a user to enter a number 1-10. That number must be stored. Then the real game begins, Using a loop have the user try to guess the number stored. Notify if the guess is too high, too low, or correct. Continue loop until correct.
I am very stuck right now; all I have is-
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim mynumber, input As Integer
mynumber = Val(TextBox1.Text)
input = TextBox1.Text
Please Help I Know this is very simple but this class is very complicated for me.
So, to start off I'm going to use your variables and we're going to declare these so the whole of the form can access them.
Dim mynumber As Integer
Dim input As Integer
We're also going to declare a seperate variable which will count the amount of times that the user has tried to guess the number, and also the number that they are going to be guessing which in this case is declared as guessnumber
Dim counter As Integer
Dim guessnumber As Integer
You want to create a button and call it btnNewGame which will start the game playing and this is going to be the code that you'll add to that button:
Dim mynumber As Random
guessnumber = Number.Next(10) + 1
This will create the random number and have it change to a new value when the new game button is clicked, so no game is the same.
We want to initialize the counter now so that whenever a new game is started then the amount of guesses that the user has had is 0 and we also want to initialize the textbox so that it is empty when the new game button is clicked.
counter = 0
txtInput.Text = ""
So now, underneath a separate play button we want to add this code
Dim uni As Integer
uni = CInt(txtInput.Text)
counter = counter + 1
Now lets add in a 'Try' function which will run through until the user has either guessed the number or exceeded the amount of turns which is 3. You can easily alter the amount of turns.
Try
If uni = guessnumber Then
MessageBox.Show("You guessed my Number!")
ElseIf uni < guessnumber Then
MessageBox.Show("Your guess is too low")
ElseIf uni > guessnumber Then
MessageBox.Show("Your guess is too high.")
End If
Catch E1 As InvalidCastException
MessageBox.Show("Please enter a number and try again.")
End Try
Hope this helps you, please let me know how you get on!

Vbscript loop, if then issue

I need some assistance. I am new to vbscript and I have a problem/question.
I am trying to give an end user the ability to start a program over.
I have done research on MSDN and googled various other sites that involve tutorials based on if then statements, subroutines, functions and do,while,until loops
all the loop tutorials or explanations have a program looping through numbers and string lengths. I have developed a common stock transaction program:
'Stock Transaction Program
Option Explicit
Dim stockPrice, commission, stocksBought, stockCommission, stockTotal, totalCost, tryAgain
Wscript.StdOut.Write "Stock price: "
stockPrice = CDbl(Wscript.StdIn.ReadLine)
Wscript.StdOut.Write "Number of stocks bought: "
stocksBought = CDbl(Wscript.StdIn.ReadLine)
Wscript.StdOut.Write "Stock Commission percentage in whole number (i.e 2 for 2%): "
commission = CDbl(Wscript.StdIn.ReadLine)
stockTotal = stockPrice * stocksBought
stockCommission = commission * stockTotal / 100
totalCost = stockCommission + stockTotal
Wscript.StdOut.WriteLine "You payed a total commission of $" & stockCommission & " on the stocks you bought."
Wscript.StdOut.WriteLine "Your total price for you purchasing " & stocksBought & " stocks is $" & totalCost & "."
After this program concludes, I would to give the end user an option to evaluate another stock price..etc.
Wscript.Stdout.Writeline "Would you evaluate another stock price? (i.e y or n): "
tryAgain = lcase(wscript.stdin.readline)
My logic assumes that you would now proceed with an if statement of some kind that basically says: that if tryAgain equals "y" then proceed back to the top, if "n" then exit program with a thank you conclusion, if invalid character then state that the end user entered an invalid response, allowing them the oppurtunity to try again.
I couldn't figure it out. functions and subroutines need arguments (i assume) and subroutines do not give data output. functions do but this code doesnt classify. I was hoping that their was a syntax that would allow the program to start over. I think a loop of some kind is probably the answer but i dont have the knowledge or the experience.
Is their anyone that can assist me???
Thanks
This could be one of the simplest solutions.
Option Explicit
Dim stockPrice, .... , tryAgain
Do
'....
' your stocks code
'....
Wscript.Stdout.Writeline "Would you evaluate another stock price? (i.e y or n): "
tryAgain = lcase(wscript.stdin.readline)
Loop While tryAgain="y"

Applescript Error "can't get end of"

I am trying my hand at Applescript and can't see anything wrong with this.
The Error I get is
error "Can’t get end of {button returned:\"OK\", text returned:\"3\"}." number -1728 from last insertion point of {button returned:"OK", text returned:"3"}
This is my code:
beep
set counter to 0
set tempX to 0
set temp to 0
set counting to 0
set stored to {0}
set input to "How many grades do you wish to enter?" as string
set str to display dialog input buttons {"NEXT"} default button "NEXT" default answer ""
repeat text returned of str times
counting = counting + 1
set grades to display dialog "GRADES: " default answer ""
set stored to grades
end repeat
set rep to the length of stored
repeat rep times
counter = counter + 1
set tempX to the ((end of stored) - counter) as number
set temp to temp + tempX
end repeat
set ln to the length of grades
set average to temp / ln
if text returned of str is 1 then
say "The Average of your grade is " & average using "Zarvox"
else
say "The Average of your grades is " & average using "Zarvox"
end if
get "AVERAGE: " & average
So, before I begin: I'd strongly recommend that you teach yourself how to use the Javascript interface to Apple Events, rather than the Applescript language itself. Applescript is a really weird language, and its quirks are largely unique; learning it is going to be frustrating, and won't help you learn other languages.
That being said, let's dive into your code:
set stored to {0}
This would start you out with one grade that's always present and set to zero. You probably want to just initialize this to an empty list:
set stored to {}
Next:
set grades to display dialog "GRADES: " default answer ""
This sets grades to a result object, not just the answer. What you probably want here is actually the text returned of the result:
set grades to text returned of (display dialog "GRADES: " default answer "")
(This is what's creating the really weird-looking object in your error message.)
Next, you overwrite stored with this result object:
set stored to grades
What you probably want here is to insert this element into the list. Because Applescript is a strange and obnoxious language, this is somewhat more cumbersome than you're thinking:
set stored to stored & {grades}
Finally, there's some logical issues with your averaging; you're adding the end of stored (that is, the last grade input) to the temp variable each time. A much simpler approach would be:
set temp to 0
repeat with n in stored
set temp to temp + n
end repeat
set average to sum / (count of stored)
With these changes all made, your script should work correctly.

Resources