Difference between revisions of "Code Snippet: Prompt for Yes or No"

From Coder Merlin
(Created page with "// Prompt the user for 'yes' or 'no' var line : String? repeat { print("Please enter 'yes' or 'no' ->", terminator:"") line = readLine() } while (line == nil || (lin...")
 
 
(4 intermediate revisions by 3 users not shown)
Line 1: Line 1:
= Prompt the user to input either a "yes" or a "no" =
== Swift ==
<syntaxhighlight lang="swift">
// Prompt the user for 'yes' or 'no'
// Prompt the user for 'yes' or 'no'
var line : String?
var line : String?
Line 7: Line 11:


// By the time we get here, line! is either "yes" or "no"
// By the time we get here, line! is either "yes" or "no"
</syntaxhighlight>
== Python ==
<syntaxhighlight lang="python">
text = input("Please enter 'yes' or 'no' ->")
while text != "yes" and text != "no":
    text = input("Please enter 'yes' or 'no' ->")
</syntaxhighlight>
== Java ==
<syntaxhighlight lang="java">
Scanner input = new Scanner(System.in); // don't forget to import Scanner in java.util
System.out.print("Please enter 'yes' or 'no': "); // use println to go to the next line
String userInput = input.next(); // for string in same line
// Look up Scanner java for more information
</syntaxhighlight>

Latest revision as of 09:50, 15 January 2020

Within these castle walls be forged Mavens of Computer Science ...
— Merlin, The Coder

Prompt the user to input either a "yes" or a "no"[edit]

Swift[edit]

// Prompt the user for 'yes' or 'no'
var line : String?
repeat {
     print("Please enter 'yes' or 'no' ->", terminator:"")
     line = readLine()
} while (line == nil || (line! != "yes" && line! != "no")) 

// By the time we get here, line! is either "yes" or "no"

Python[edit]

text = input("Please enter 'yes' or 'no' ->")
while text != "yes" and text != "no":
    text = input("Please enter 'yes' or 'no' ->")

Java[edit]

Scanner input = new Scanner(System.in); // don't forget to import Scanner in java.util
System.out.print("Please enter 'yes' or 'no': "); // use println to go to the next line
String userInput = input.next(); // for string in same line
// Look up Scanner java for more information