Using multiple else if statements - vbscript

I was trying to make a calculator in VBScript to test my skill, but came across an error. My program uses multiple else if statement to test what the user has input.
Here is my code below:
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans
head = "Calculator"
msg1 = msgBox("Ruan's Vbscript calculator",0,head)
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
num1 = inputBox("Enter your first number",head)
num2 = inputBox("Enter your second number",head)
if (input1 = vbcancel) then
wscript.quit()
else if (input1 = "+") then
ans = num1 + num2
else if (input1 = "-") then
ans = num1 - num2
else if (input1 = "*") then
ans = num1 * num2
else if (input1 = "/") then
ans = num1 / num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
msgAns = msgBox "Your answere is: " + head
When I run the program, the error says: "Expected end of statement". I don't see the problem here, as I have end if after all those else if statements.

Remove the space between else and if and make it elseif. Like this:
if (input1 = vbcancel) then
wscript.quit()
elseif (input1 = "+") then
ans = num1 + num2
elseif (input1 = "-") then
ans = num1 - num2
elseif (input1 = "*") then
ans = num1 * num2
elseif (input1 = "/") then
ans = num1 / num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
With the additional space between else and if you start a new if statement nested in the else branch rather than continuing the first if statement. The nested if statements require end ifs of their own, which is why you're getting the error.

Minimal improvements to make it work:
Option Explicit
Dim head
Dim msg1, msgErr, msgAns
Dim input1, num1, num2
Dim ans
head = "Calculator"
msgBox "Ruan's Vbscript calculator", 0, head
input1 = inputBox("How do you want to calculate? You can type (+ - * /)",head)
If Not IsEmpty(input1) Then
num1 = CDbl(inputBox("Enter your first number",head))
num2 = CDbl(inputBox("Enter your second number",head))
if input1 = "+" then
ans = num1 + num2
elseif input1 = "-" then
ans = num1 - num2
elseif input1 = "*" then
ans = num1 * num2
elseif input1 = "/" then
ans = num1 / num2
elseif input1 = "\" then
ans = num1 \ num2
else
msgErr = msgBox("Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces","Error")
end if
msgBox "Your answere is: " & ans
else
msgBox "Aborted"
end if
Type and range checks for the operants left as execise.

A Select Case is usually a simpler/clearer construction for selecting operations based on a single variables value
Select Case input1
Case vbCancel
wscript.quit()
Case "+"
ans = num1 + num2
Case "-"
ans = num1 - num2
Case "*"
ans = num1 * num2
Case "/", "\" '//multiples
ans = num1 / num2
Case Else
msgBox "Make sure you type '+' or '-' or '*' or '/' with no extra letter or spaces", , "Error"
End Select

Related

Ruby Number Guessing Game

I have tried to make a number guessing game using ruby but it seems to be looping all over again after the user gets the correct answer, here's my code and thanks in advance!
require './input_functions'
def check (rno,input)
x = 1
while (x == 1)
y = 0
if (rno > input)
puts("Try a bigger number")
input = gets.chomp.to_i
y = y + 1
x = 1
else
if (rno < input)
puts("Try a smaller number")
input = gets.chomp.to_i
y = y + 1
x = 1
else
if(rno == input)
puts("Bingo!")
x = 0
end
end
end
end
return
end
def main
rno = rand(100)
input = read_integer("Enter an integer between 0 and 100: ")
check(rno,input,y)
times = check(rno,input,y)
puts ("You have tried " + times.to_s + " times.")
end
main
The main problems are:
You call check method two times within main method, you need to remove the first one.
You need to move y = 0 out of while loop to be able to return it.
Tried to simplify your code a bit, and you could try to improve it even more.
def check(rno, input)
x = 1
y = 0
while x == 1
if rno == input
puts "Bingo!"
x = 0
else
if rno > input
puts "Try a bigger number"
else
puts "Try a smaller number"
end
input = gets.chomp.to_i
y = y + 1
end
end
return y
end
def main
rno = rand(100)
input = read_integer("Enter an integer between 0 and 100: ")
times = check(rno, input)
puts ("You have tried " + times.to_s + " times.")
end

Program Doesn't Finish Whole Script

I am starting a program in which you have to pick a mode, operation, and then it will calculate it for you. It is still a work in progress.
However, I am running into a problem where it works if you input "A" or "B", and it also works when you input the "sign" or operation. However after the user inputs a sign it finishes the program and exits the code.
I need some feedback on this situation:
My end goal is for the program to also ask the user for input of the numbers they want to calculate, but the program doesn't ask the user for their input. I feel as if this problem has to deal with the float (inputs, elifs'(if then else), or how it is stuck in the parameters of the function.
import fractions
print("Welcome to Advanced Calculator Version 1.01")
module = input("Enter a mode, for example; 1NUMBER_OPERATIONS [A], or 2NUMBER_OPERATIONS [B]")
if module == "A":
operation = input('Enter an operation, for example; sq_rt,fraction,percent,round')
elif module == "B":
operation = input('Enter an operation, for example; -,+,*,/,^')
def doublecheck():
#OPERATION|||MODESA
if operation == "-":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 - num2
print(result)
elif operation == "+":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 + num2
print(result)
elif operation == "*":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 * num2
print(result)
elif operation == "/":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 / num2
print(result)
elif operation == "^":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1^num2
print(result)
elif operation == "sq_rt":
num1 = float(input("Enter a number: "))
num_sqrt = num1 ** 0.5
print('The square root of %0.3f is %0.3f' % (num1,num_sqrt))
elif operation == "fraction":
num1 = float(input("Enter a number: "))
str(fractions.Fraction(num1))
elif operation == "percent":
num1 = float(input("Enter a number: "))
v = 100
percent= num1 * v
print(percent + "%")
elif operation == "round":
num1 = float(input("Enter a number: "))
round(num1)
return 0
You need to call your function too. Check the last line. Also indent your return 0 statement.
import fractions
print("Welcome to Advanced Calculator Version 1.01")
module = input("Enter a mode, for example; 1NUMBER_OPERATIONS [A], or 2NUMBER_OPERATIONS [B]")
if module == "A":
operation = input('Enter an operation, for example; sq_rt,fraction,percent,round')
elif module == "B":
operation = input('Enter an operation, for example; -,+,*,/,^')
def doublecheck():
#OPERATION|||MODESA
if operation == "-":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 - num2
print(result)
elif operation == "+":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 + num2
print(result)
elif operation == "*":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 * num2
print(result)
elif operation == "/":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1 / num2
print(result)
elif operation == "^":
num1 = float(input("Enter a number: "))
num2 = float(input("Enter another number: "))
result= num1^num2
print(result)
elif operation == "sq_rt":
num1 = float(input("Enter a number: "))
num_sqrt = num1 ** 0.5
print('The square root of %0.3f is %0.3f' % (num1,num_sqrt))
elif operation == "fraction":
num1 = float(input("Enter a number: "))
str(fractions.Fraction(num1))
elif operation == "percent":
num1 = float(input("Enter a number: "))
v = 100
percent= num1 * v
print(percent + "%")
elif operation == "round":
num1 = float(input("Enter a number: "))
round(num1)
return 0
doublecheck()

Fibonacci Series using classes and methods

I have written a fibonacci series method and tried calling it. It works fine with the following code:
module Fibonacci
class Operation
def fibonacci(n)
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
res.fibonacci(n)
end
But I want to have a seperate method for accepting input within the class and calling it.
module Fibonacci
class Operation
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
end
def fibonacci(n)
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
res.input
res.fibonacci(n)
end
Getting an Error!..I'm a newbie, Would be helpful if I get a support..Thank You
As it stands, your code doesn't use the return value of your input function; it disappears into the ether, and your caller has an undefined n it's attempting to access. If you write your calling code as:
res = Operation.new
res.fibonacci(res.input)
Then you pass the return value from res.input into res.fibonacci and your immediate problem is resolved.
Beyond this, I believe there are noteworthy design issues in your code which you may consider. Functions should be modular and avoid side-effects such as printing, which severely limit their usefulness and flexibility. What if you wish to generate Fibonacci numbers and use them for something else in your program? You have to rewrite the whole function again. If you write it once to populate and return an array, you let the caller decide whether to print the output, save it in a database, send it through a socket, reverse it, send it into another function (you get the idea).
Seek to avoid hard-coded values like string and numbers. Your input function can't work for anything but collecting Fibonacci numbers. What if you let the caller decide what the message is? Then, when you add more math functions to your Operation class, you can reuse the same input routine.
I would also contend that a function like input doesn't belong in an Operator class. I can see it used as a utility function in that class, but it's independent of Operator-like stuff and is too small to warrant its own function in any case.
Here's a re-write that somewhat mitigates these issues:
module Fibonacci
class Operation
def input(message)
puts message
gets.chomp.to_i
end
def fibonacci(n)
num1 = 0
num2 = 1
result = []
while num2 < n
result << num2
num1, num2 = num2, num1 + num2
end
result
end
end
res = Operation.new
puts res.fibonacci(res.input 'Enter the number upto which Fibonacci needs to be printed:')
end
And a sample run:
Enter the number upto which Fibonacci needs to be printed:
15
1
1
2
3
5
8
13
Change code to:
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
fibonacci(n)
end
And remove res.fibonacci(n).
Here is the full code:
module Fibonacci
class Operation
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
n = gets.chomp.to_i
fibonacci(n)
end
def fibonacci(n)
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
res.input
end
Hope this helped.
It could incredibly help if you have specified what exact error do you have, but let me guess: it’s kinda “NameError: undefined local variable or method `n'”
That happens because you have not passed an argument in your call to fibonacci. You have an option to fallback to getting the variable from the user input if none was specified:
class Operation
def input
puts 'Enter the number upto which Fibonacci needs to be printed:'
gets.chomp.to_i
end
def fibonacci(n = -1)
# HERE
n = input if n <= 0
num1 = 0
num2 = 1
while num2 < n
puts num2
num1, num2 = num2, num1 + num2
end
end
end
res = Operation.new
res.fibonacci(5)
#⇒ 1 1 2 3
res.fibonacci
#⇒ 'Enter the number ...'

Ruby return value in the if loop and code clarification

Here is the Digit fifth powers
I did not get why my "ans" is zero since the each_sum should has its value and added up in the
ans = ans + each_sum
and there is a number matched in the
i == i.to_s.each_char{|c| each_sum = each_sum + c.to_i**5 }
Code
def digit_fifth_powers
max = 0
4.times {max = max + 9**5} #max = 236196
each_sum,ans = 0,0
(2..max).each do |i|
if i == i.to_s.each_char{|c| each_sum = each_sum + c.to_i**5 }
ans = ans + each_sum
end
end
ans
end
p digit_fifth_powers
ans is 0
Okay. I check it twice, my previous answer was incorrect.
The point is i is Fixnum and that long statement returns String, hence the false in condition. Make it i.to_s == ...

How to I make floyd triangle shape using for loop?

I need output of Floyd triangle like:
1
0 1
1 0 1
0 1 0 1
I tried. I didn't get it exactly. Can anyone explain the logic?
This is the code I tried:
k = 0
for i in 1..5
for j in 1..5
if (i%2)==0;
k = (j%2==0) ? 1:0;
else;
k = (j%2==0) ? 0:1;
puts k,'';
end
end
puts
end
The main issue here is that in order to get the "triangle" shape of your output, you need your inner loop to increment from 1 to i instead of 1 to 5.
k = 0
for i in 1..5
for j in 1..i
if (i%2)==0
k = j + 1
else
k = j
end
print "#{k%2} "
end
puts
end
Here's a one line approach:
5.times {|line| puts (line + 1).times.with_object(""){|num, str| (num + line).even? ? (str << " 1 ") : (str << " 0 ") } }
to make it more clear:
lines = 5
lines.times do |line|
str = ""
line = line + 1 # 5.times runs from 0 to 4 and we need 1 to 5
line.times do |num|
# the condition is a bit different because I changes the code a bit
if (line + num).even?
str << " 0 "
else
str << " 1 "
end
end
puts str
end
Alright the following should work, but i hope it's readable. If you need more explanation or have specific questions let me know
i = 1
while i <= 4 do
if i%2 > 0
output = 1
else
output = 0
end
j = 1
while j <= i do
print( "#{output} " )
if output == 1
output = 0
else
output = 1
end
j+=1
end
print( "\n" )
i+=1
end
You can try following code for output you are expecting:
k = 0
for i in 1..4
for j in 1..i // inner loop code runs i times for each outer loop iteration
if (i%2)==0;
k = (j%2==0) ? 1:0;
else;
k = (j%2==0) ? 0:1;
end
print k,' ';
end
puts
end
Click Here to see output.
You can also get idea about for loops through this link.
The prefered ruby way:
layers = 4 # Change to as many layers as you want
layers.times do |i| # i starts from 0
(i + 1).times do |j| # j also starts from 0
print (i + j + 1) & 1, ' '
end
puts
end
The for way:
layers = 4
for i in 0...layers
for j in 0...(i + 1)
print (i + j + 1) & 1, ' '
end
puts
end

Resources