2015-06-14 71 views
0

我被困在決策部分。當答案變量是N當我鍵入n這意味着我不希望在不同的行打印文本)和標誌着變量爲Y當我Y型那就意味着我不想打印帶引號的文本),我收到消息:答案'Y'無效。程序正在終止。下面是代碼:Ruby中的決策錯誤

def multiFunctionalPrinter 
    puts "How many times do you want to print?" 
    number = gets 
    puts "-------------------------------------------" 
    puts "What do you want to print?" 
    text = gets.chomp             #chomping variable to format it for decision making 
    puts "-------------------------------------------" 
    puts "Do you want to print in different lines (Y or N)?" 
    answer = gets.chomp             #chomping variable to format it for decision making 
    puts "-------------------------------------------" 
    puts "Do you want to add quotation marks (') (Y or N)?" 
    marks = gets.chomp             #chomping variable to format it for decision making 

    if answer == "Y" && marks == "Y"          # Different lines: ON , Quotation marks: ON 
     1.upto(number.to_i) {puts "'" + text.to_s + "'"} 
    elsif answer == "Y" && marks == "N"         # Different lines: ON , Quotation marks: OFF 
     1.upto(number.to_i) {puts text.to_s} 
    elsif answer == "Y" && marks != "Y" || marks != "N"     # Different lines: ON , Quotation marks: INVALID 
     puts "Answer '#{marks}' is invalid. Program is terminating." 
    elsif answer == "N" && marks == "Y"         # Different lines: OFF , Quotation marks: ON 
     puts "Do you want to split what you print? (Y or N)" 
     answer2 = gets.chomp 
     if answer2 == "Y"            # Split: ON 
      1.upto(number.to_i) {print "'" + text.to_s + "' "} 
      print "\n" 
     elsif answer2 == "N"            # Split: OFF 
      1.upto(number.to_i) {print "'" + text.to_s + "'"} 
     else 
      puts "Answer '#{answer2}' is invalid. Program is terminating." 
     end 
    elsif answer == "N" && marks == "N"         # Different lines: OFF , Quotation marks: OFF 
     puts "Do you want to split what you print? (Y or N)" 
     answer2 = gets.chomp 
     if answer2 == "Y"            # Split: ON 
      1.upto(number.to_i) {print text.to_s + " "} 
     elsif answer2 == "N"            # Split: OFF 
      1.upto(number.to_i) {print text.to_s} 
     else 
      puts "Answer '#{answer}' is invalid. Program is terminating." 
     end 
    else 
     puts "Answer '#{answer}' or '#{marks}' is invalid. Program is terminating." 
    end 
    puts "--------------------------------------------" 
end 

multiFunctionalPrinter 

我在做什麼錯?

回答

1

二元運算符&&的優先級高於||
這意味着,這條線:

answer == "Y" && marks != "Y" || marks != "N" 

是相當於

(answer == "Y" && marks != "Y") || marks != "N" 

所以每當marks不同於"N",聲明成立。


你應該如何解決你的問題是添加一堆括號。

answer == "Y" && (marks != "Y" || marks != "N") 
0

邏輯的問題是在這條線:(!答案== 「Y」 & &標記= 「Y」)

elsif answer == "Y" && marks != "Y" || marks != "N" 

你的腳本是希望看到現在||標記!=「N」。它在語句到達語句之前進行評估,因爲答案是「N」,標記是「Y」(answer ==「Y」& & marks!=「Y」)的計算結果爲true。

你想擁有左右括號或表達式因此上述線路將變爲:

elsif answer == "Y" && (marks != "Y" || marks != "N") 

和程序應按照您的想法。