Lie Detector
Back to the Program-A-Day homepage
ProblemCreate a program that will allow the user to enter in a statement, and output whether the statement is true or false. The statement will be inputted using JOptionPane.showInputDialog. The program will evaluate the truthiness of the statement randomly (just like a real lie detector). The result should be given using System.out.println. To solve this problem, you will need to understand:
|
Primitive Data Types | |
---|---|---|
SolutionThere are three distinct steps in this program:
The first step is to read in the input. You are going to need to use an input dialog box. String statement = JOptionPane.showInputDialog(null, "Enter a statement"); Don't forget your import statement. import javax.swing.*; //needed for JOptionPane The next step is to calculate the truthiness of the statement using the random method. The method is part of the Math class, so make sure you import it. import java.lang.Math;//needed for Random Math.random() will return a decimal value between 0 and 1. By comparing the value to a constant value, we can calculate the truthiness. boolean truthiness = Math.random() < 0.5; I am using 0.5 so that ~50% of statements will be true. If you are testing the program on someone who is more or less trustworthy, you may want to adjust the value accordingly. With the truthiness calculated, all that is left is to output the result. This should be done using System.out System.out.println("The Statement " + quote + statement + quote + " is " + truthiness); You should now have a program that divines truth from statements. For the entire code solution, see below. | ||
Code |