Home > Net >  Calculator in R error in user inup and if statement
Calculator in R error in user inup and if statement

Time:07-23

Basically, I want to make a calculator that gets the input from the user from which operation he wants to use, but I was testing what happens if after the user chooses the input, my code has a condition that prints depending what was the user input. Why am I getting this error? What is wrong with the if and else statement?

My code:

    Adicao = "Adição"
Subtracao = "Subtração"
Multiplicacao = "Multiplicação"
Divisao = "Divisão"

print("Choice of operations:")
cat("1.", Adicao)
cat("2.", Subtracao)
cat("3.", Multiplicacao)
cat("4.", Divisao)

escolha <- as.integer(readline(prompt="Enter your choice: "))

if(escolha = 1){
  print("Cool! You choose addition")
} else {
  print("You didnt choose addition ")
}

The error I get:

> escolha <- as.integer(readline(prompt="Enter your choice: "))
Enter your choice: 2
> if(escolha = 1){
Error: unexpected '=' in "if(escolha ="
>   print("Cool! You choose addition")
[1] "Cool! You choose addition"
> } else {
Error: unexpected '}' in "}"
>   print("You didnt choose addition ")
[1] "You didnt choose addition "
> }
Error: unexpected '}' in "}"

CodePudding user response:

You have to use == equality operator for comparison in if statement which return logical (TRUE or FALSE) , = used to assign value to object

if(escolha == 1){
    print("Cool! You choose addition")
} else {
    print("You didnt choose addition ")
}

CodePudding user response:

print("Choice of operations:")
cat("1.", "Add\t")
cat("2.", "Subtract\t")
cat("3.", "Multiply\t")
cat("4.", "Divide\n")

userSelected <- as.integer(readline(prompt="Enter your choice: "))

if(all.equal(1, as.integer(userSelected)) == TRUE) {
  print("Add")
} else {
  print("You didnt choose addition")
}

Related Links

  • Related