Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2

Thread: error help

  1. #1
    New to the CF scene
    Join Date
    Aug 2016
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    error help

    Hello,

    I have learnet Java in my school and I am thorough with it. I decided to start learning this new "Ruby" Languague and i gave it a go.
    I started to learn ruby (like.. yesterday night) and i tried the program below.
    It throws an error and It would be appreciated a lot if someone tells me where in the code i have gone wrong (and If you can, you can explain it in java terms). Thanks!



    Code:
    print "Enter number : "
     num = gets.chomp
     i = 1
     boo = true
     while (i<num)
    if (i%num==0) 
    boo=true
    end
     i++
     end
    
    if (boo==true)
    puts (num+"is a prime number")
    else
    puts (num+"is not a prime number")
    end
    -e17b6e3890b84db9a1ab75eab7d144eb-png

  2. #2
    New Coder
    Join Date
    Nov 2016
    Location
    South Africa, Cape Town
    Posts
    49
    Thanks
    1
    Thanked 1 Time in 1 Post
    There's a few reasons you're getting that error.
    The first reason is because of invalid operators such as i++ - that doesn't exist in ruby. You have to use i += 1.
    Secondly you're comparing a string to a number in your while loop. You have to convert it using num = num.to_i.

    Here's the part I don't get, as it doesn't make sense regardless of the language.


    You have an if statement inside the while loop that sets the already True boolean variable to True and also have an entire new if-else statement block outside the while loop that compares bool values even though the bool value doesn't and can never change within your code...

    For someone who knows Java, Ruby should be a breeze. I speak from experience.

    Explaining this in any language would be syntactically the same - the if statement compared the wrong values and was placed outside the while loop.

    Note that i removed chomp from the num value. This is because we use puts to place new lines in our code.

    Code:
    print "Enter number : "
    
    num = gets
    
    i = 1
    num = num.to_i
    
    while i < num
      if (num % i == 0) 
        puts "#{i} is a prime number"
      else
        puts "#{i} is not a prime number"
      end
      i += 1
    end


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •