Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I want to code a QuizCreator, but I don't really know how I should save the Questions and Answers. Would it be better to save them in one file or separate them into two files?
Also, how could I display the questions and then check if the answers are correct?
I am new to programming, I would greatly appreciate any advice you have.
I would store them in a single file, and I'd use a file format like JSON. The file would look something like this:
[
{ "question": "What is your favorite color?",
"answers": [
{ "correct": true, "Blue" },
{ "correct": false, "Red" },
{ "correct": false, "Green" }
]
},
{ "question": "What is the airspeed of an unladed swallow?",
"answers": [
{ "correct": true, "I don't know that" },
{ "correct": true, "42 mph" },
{ "correct": false, "10 kmh" }
]
}
]
Then you can use a JSON parsing tool like GSON to parse the file for you. You'll have to read the file in, but you'll be able to find tons of examples of how to use GSON.
That's what I would do. Of course, you might want to use a format that's easier for you to parse.
Q: question 1
FA: 1
FA: 2
TA: 3
Q: question 2
...
Then you can just split the line at the : and see if it starts with Q (and new question) or FA/TA (false or true answers) assuming you're doing multiple choice.
You'll need to know how to open and read the contents of a file. If you use GSON, you'll spend some time learning how to use it. Otherwise you can read lines of the file at a time and parse them into your data structure yourself.
This is a pretty good practice program to write.
In my opinion... keep it simple, keep it all in a single Text file regardless of what format you decide to use. One text file per Quiz. This way you can always re-use these files. As a matter of fact, have everything related to a particular quiz in that one particular file. Let the file do the work for you.
For some file examples, one quiz might be a Math Quiz, another Quiz might be on History, and yet another Quiz on Sciences. The rules for each quiz should be displayed to the student before any test starts. These Rules should be contained within each Quiz File so that all your code needs to do is acquire these rules from the Quiz File being run and display them to the Student before the quiz begins. Allow the Student to start the Quiz when ready (after reading the rules).
An Example Math Quiz File (MathTest001.txt):
; QUIZ FILE - For the TimedQuestions class.
; The Quiz Message (optional) - This information is displayed to the User within
; a dialog box before the test begins.
; Quiz Message lines always begin with a Colon (:).
; As you can see below, basic HTML can be used to make the dialog message.
; This can add some pizzaz to your Quiz Message.
; ONLY EVER supply one Quiz Message in any Quiz File! Feel free to copy/paste
; the below message from Quiz File to Quiz File.
; Message Tags (if you decide to use them) are optional and are filled by the
; application:
;
; %flc Number of Quiz Questions in file.
; %sft Number of seconds to answer each Question
:<html>Within this Test there are <font color=blue><b>%flc</b></font> multiple choice questions that need<br>
:to be answered.<br><br>You will have <font color=blue><b>%sft</b></font> seconds to answer each test question
:unless<br>otherwise indicated above the question.<br><br>If a question runs out of time before it is answered
:then that<br>question will be considered as <font color=red><b>WRONG</b></font>.<br><br>
:<center>Press the <b>OK</b> button to start the Test</center><br><br></html>
; As a matter of fact, the above message is default and the lines above
; merely show how to make your own.
; Comment Lines always begin with a semicolon (;) and can go anywhere
; providing they are on their own line.
; Comment and Blank lines are always ignored within a Quiz File.
; MATH QUIZ QUESTIONS:
; The \n in Question Lines forces a CarriageReturn/Linefeed in Console. Format the
; questions as you see fit.
; Question & Multiple Choice Options | Correct Answer | Seconds To Answer Question
1: What is: 1 + 1 = ?\n a: 1 b: 2 c: 3 d: 4\n|b|10
2: What is: 5 + 5 = ?\n a: 1 b: 12 c: 10 d: 15\n|c|20
3: What is: 6 + 4 = ?\n a: 10 b: 11 c: 12 d: 13\n|a
4: What is: 2 + 3 = ?\n a: 3 b: 4 c: 5 d: 6\n|c|10
5: What is: 4 + 3 = ?\n a: 7 b: 6 c: 5 d: 8\n|a|10
An Example History Quiz File (HistoryTest001.txt):
; HISTORY QUIZ QUESTIONS:
; The \n in Question Lines forces a Carraige Return/Linefeed in Console.
; Question & Multiple Choice Options | Correct Answer | Seconds To Answer Question
1: Two of Henry VIII's six wives were executed. Anne Boleyn was one. Who was the second?\n a: Katherine Parr b: Jane Seymour c: Catherine Howard d: Lady Jane Grey\n|c|10
2: Who had his head chopped off in 1649?\n a: James I b: James II c: Charles I d: Charles II\n|c|10
3: When was William Shakespeare born?\n a: 1554 b: 1564 c: 1574 d: 1584\n|b
4: The Merry Wives of ...?\n a: Wandsworth b: Wycombe c: Walberswick d: Windsor\n|d|10
5: Approximately how long ago was Stonehenge built?\n a: 10,000 years b: 7,000 years c: 5,000 years d: 3,000 years\n|c|10
An Example Science Quiz File (ScienceTest001.txt):
; SCIENCE QUIZ QUESTIONS:
; The \n in Question Lines forces a Carraige Return/Linefeed in Console.
; Question & Multiple Choice Options | Correct Answer | Seconds To Answer Question
1: What was the Manhattan Project?\n a: Golf Ball Invention b: First US Satelite c: The development of the Atomic Bomb d: New York Housing Project\n|c|10
2: At what speed does light travel?\n a: 12,000 miles per second b: 186,000 feet per second c: 186,000 miles per second d: 186,000 meters per second\n|c|10
3: What is the largest moon of Saturn called?\n a: Titan b: CRT4 c: Quadra d: Sat76\n|a|12
4: The molecule DNA is described as having which shape?\n a: Sine Wave b: Elipsicle c: Tripple Spiral d: Double Helix\n|d|10
5: Percy Spencer invented which time saving kitchen appliance?\n a: Convection Oven b: The Microwave cooker c: Toaster d: Refridgerator\n|b|10
You will notice that within each of the above Quiz Files there is a value supplied for each question which relates to the number of seconds a Student has in order to answer any one question. The code supplied below contains a mechanism that places a time limit on how long the Student has to answer the question.
And the code to utilize any one of these files as a console application:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
public class TimedQuestions {
private final String ls = System.lineSeparator(); // OS Specific Line Separator for console messages
private boolean questionAnswered = false; // Keeps track of whether a question was answered
private int questionCount = 0; // Keeps count of number of questions asked to User
private int rightAnswers = 0; // Keeps count of questions answered Correctly
private int wrongAnswers = 0; // Keeps count of questions answered Incorrectly
private final int DEFAULTSECONDSFORTIMEOUT = 10; // The default question time limit
private int secondsPerQuestion = 10; // Current set time limit for question (can change by question)
private boolean timeOut = false; // Keeps track of whether or not the question has timed out.
/* If you are going to run this class on its own
through your IDE then supply the Quiz File name
to the testFilePath variable below, for example:
private String testFilePath = "C:\\Quizes\\MathTest001.txt";
*/
private String testFilePath;
// Constructors...
//================================================
public TimedQuestions() {}
public TimedQuestions(String testFilePath, int... secondsPerQuestion) {
this.testFilePath = testFilePath;
if (secondsPerQuestion.length > 0) {
this.secondsPerQuestion = secondsPerQuestion[0];
}
}
// ================================================
public static void main(String[] args) {
/* I like to start the application this way
because I don't like the need for statics. */
new TimedQuestions().startTest(args);
}
public void startTest(String... args) {
/* Get Command Line argument (if supplied) which needs
to be the path and file name of the Quiz File. */
if (args.length > 0) {
File f = new File(args[0]);
if (!f.exists()) {
System.err.println("Quiz Error! The supplied Quiz File can not be "
+ "found!" + ls + "[" + args[0] + "]" + ls);
return;
}
this.testFilePath = args[0];
}
// Start the test...
if (testFilePath == null || testFilePath.equals("")) {
System.err.println("Error! - No Quiz File Supplied!");
return;
}
start(testFilePath);
if (questionCount == 0) { return; }
// Calculate and display score for test...
double scr = (double) ((rightAnswers/questionCount)*100);
int score = (int) Math.ceil((double)rightAnswers/(double)questionCount*100.0);
System.out.println(ls + "======================================================");
System.out.println("Out of a total of " + questionCount + " questions" + ls
+ "you got " + rightAnswers + " questions Correct and" + ls
+ "you got " + wrongAnswers + " questions Wrong." + ls
+ "Your score is " + + score + "% "
+ "which gives you a grade of '" + getLetterGrade(score) + "'.");
System.out.println("======================================================");
// Done.
}
private void start(String testFilePath) {
// Get the number of lines (questions) within the supplied Test file...
int fileLinesCount = getNumberOfQuestions(testFilePath);
if (fileLinesCount == 0) { return; }
// Get Quiz Message from file (if there is any).
String msg = getQuizMessage(testFilePath);
// Display test information to the User via a Message Box
// and allow User to start the test.
if (msg.equals("")) {
// Default Quiz Message in case there is none in file.
msg = "<html>Within this Test there are <font color=blue><b>%flc" +
"</b></font> multiple choice questions that need<br>" +
"to be answered.<br><br>" +
"You will have <font color=blue><b>%sft</b></font> " +
"seconds to answer each test question unless<br>" +
"otherwise indicated above the question.<br><br>" +
"If a question runs out of time before it is answered then that<br>" +
"question will be considered as <font color=red><b>WRONG</b></font>.<br><br>" +
"<center>Press the <b>OK</b> button to start the Test</center><br><br></html>";
}
// Replace any custom tags (%flc and %sft) for their proper values.
// The %flc tag holds the total number of questions within the test file.
// The %sft tag holds the default Seconds For Timeout.
msg = msg.replace("%flc", String.valueOf(fileLinesCount))
.replace("%sft", String.valueOf(secondsPerQuestion));
// Display test information to the User bvia a Message Box
// and allow User to start the test.
JDialog dialog = new JDialog();
dialog.setAlwaysOnTop(true);
int response = JOptionPane.showConfirmDialog (dialog, msg, "Test Information...",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE);
dialog.dispose();
// If anything but the OK button was selected then quit application
if (response != 0) {
System.exit(0);
}
// Open a Bufferreader to read in questions from the Test file.
try (BufferedReader fileReader = new BufferedReader(new FileReader(testFilePath))) {
// Iterate through the Test file and process one question at a time....
String testFileLine;
while ((testFileLine = fileReader.readLine()) != null) {
// Skip Blank lines, Quiz Message Lines (lines that start with a
// semicolon [;]), and Header Lines (lines that start with a Colon
// [:]).
if (testFileLine.trim().startsWith(";") ||
testFileLine.trim().startsWith(":") ||
testFileLine.trim().equals("")) {
continue;
}
// Split the file line question into specific parts.
// 1st part will be the question itself, 2nd part will be
// the answer and the 3rd part will be the number of seconds
// allowed to answer question. If the 3rd part is not supplied
// within the file line question then a default of 10 seconds
// is used as set by the defaultSecondsForTimout class global
// variable.
String[] fileQuestionParts = testFileLine.split("\\|");
String question = fileQuestionParts[0];
// Allow for newline and tab tags within text string.
question = ls + question.replaceAll("\\\\n", "\n").replaceAll("\\\\t", "\t");
//Get the question answer from file line
String questionAnswer = fileQuestionParts[1];
// If the seconds time out is provided within the question file
// line then grab it for use.
if (fileQuestionParts.length > 2) { secondsPerQuestion = Integer.parseInt(fileQuestionParts[2]); }
// otherwise use the default of 10 seconds.
else { secondsPerQuestion = DEFAULTSECONDSFORTIMEOUT; }
String answerResult;
questionCount++; // Increment the questionCount variable
questionAnswered = false; // Set the qustionAnswered variable
// Ask the retrived question to User....
answerResult = askTimedQuestion(question, secondsPerQuestion);
questionAnswered = true;
// If the User entered then quit the test.
if (answerResult.equalsIgnoreCase("quit")) { break; }
// If the Usert supplied input is the right answer then...
if (answerResult.equalsIgnoreCase(questionAnswer)) {
System.out.print(" CORRECT " + ls);
rightAnswers++; // Increment the rightAnswers variable.
}
// If the Usert supplied input is the wrong answer then...
else {
wrongAnswers++; // Increment the wrongAnswers variable.
System.out.print(" WRONG " + ls); }
}
// Close the file reader.
fileReader.close();
}
catch (IOException e) {
// Display file errors
System.out.println(ls + "ERROR! - " + e.getMessage());
}
}
private int getNumberOfQuestions(String filePath) {
int q = 0;
try (BufferedReader fileReader = new BufferedReader(new FileReader(filePath))) {
// Iterate through the Test file and gather the number
// of file lines that are actually quiz questions.
String testFileLine;
while ((testFileLine = fileReader.readLine()) != null) {
// Skip Non-Quiz Question lines...
if (testFileLine.equals("") ||
testFileLine.startsWith(";") ||
testFileLine.startsWith(":")) {
continue;
}
q++;
}
// Close the file reader.
fileReader.close();
}
catch (IOException e) {
// Display file errors
System.err.println(ls + "ERROR! - " + e.getMessage());
}
return q;
}
private String getQuizMessage(String filePath) {
String msg = "";
try (BufferedReader fileReader = new BufferedReader(new FileReader(filePath))) {
// Iterate through the Test file and the quiz message if there is one.
// Any file line that starts with a colon (:) will be added together
// to create the Quiz Message (regardless of where it is in file). Make
// your Quiz Messsage one of the very first things you place into the
// Test File.
String testFileLine;
while ((testFileLine = fileReader.readLine()) != null) {
if (testFileLine.equals("")) { continue; } // Skip any blank lines
if (testFileLine.startsWith(":")) {
msg+= testFileLine.substring(1);
}
}
// Close the file reader.
fileReader.close();
}
catch (IOException e) {
// Display file errors
System.err.println("\nERROR! - " + e.getMessage());
}
return msg;
}
// Method for asking the questions retrieved from the supplied Test file
private String askTimedQuestion(String question, int secondsPerCurrentQuestion) {
// The secondsPerCurrentQuestion parameter allows you to change
// the number of seconds for each question if seconds are
// applied to a particular question within the Test file.
// (See Test file information)
secondsPerQuestion = secondsPerCurrentQuestion;
// Establish a new Thread for perform our question timing...
#SuppressWarnings("Convert2Lambda")
Thread timerThread = new Thread(new Runnable() {
#Override
#SuppressWarnings("SleepWhileInLoop")
public void run() {
try {
// See if this thread has been interrupted. If it has then
// we stop our timer While/Loop (a gracefull Thread Stop).
while (!Thread.currentThread().isInterrupted()) {
for (int seconds = secondsPerQuestion; seconds >= 1; seconds--){
// Break out of this timer FOR loop if the question
// was answered by using Thread.interrupt().
if (questionAnswered) { Thread.currentThread().interrupt(); break;}
// Show that timer is ticking away...
System.out.print("*");
// ==========================================================
// Or you can use this...
//if (seconds < secondsForTimout) { System.out.print("-"); }
//System.out.print(seconds);
// ==========================================================
Thread.sleep(1000);
}
// If the question wasn't answered and our timer loop has
// expired then inform User that time is up and set the
// timeOut variable to true.
if (!questionAnswered) {
System.out.print("\b\b\b\Your time is up for this question!");
timeOut = true;
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
// Catch Exceptions for BufferReader()/InputStreamReader()...
try {
// Declare a BufferReader object so as to get input from User.
// We use BufferReader along with InputStreamReader(System.in)
// for this.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Display the supplied Question from file to User...
if (questionCount > 1) {
System.out.println(ls + "------------------------------------------------------");
}
System.out.print("[" + secondsPerQuestion + " seconds]");
System.out.println(question);
// Declare User input variable & initialize to a Null String
String input = "";
// Reset the timeOut variable
timeOut = false;
// Make sure our timer thread is dead before restarting it.
//while (timerThread.isAlive()){}
// Start the Timer Thread
if (secondsPerQuestion > 0) { timerThread.start(); }
// Loop through input from the User
do {
// Wait until we have User input data to complete a readLine()
// or until our timer thread has set the timeOut variable to
// true.
while (!br.ready()) {
// If our timer thread has set the timeOut variable to
// true then let's get outta this question altogether.
// First we get out of our 'wait for input' loop...
if (secondsPerQuestion > 0 && timeOut) { break; }
}
// Then we get out of our Do/While Loop.
if (secondsPerQuestion > 0 && timeOut) { break; }
// No time-out so let's move on...
// Let's see what the User supplied for an answer.
// If just ENTER was supplied then input will contain
// a Null String and the User can still enter an answer
// until the question is timed out.
input = br.readLine();
// remove any unwanted text from System.out.print()
// that had made its way through the timer thread.
System.out.print("\b\b\b\b\b");
} while ("".equals(input));
// Stop the timer thread.
timerThread.interrupt();
return input;
}
catch (IOException ex) { return ""; }
}
// Determine & return the Letter Grade for the
// supplied integer test percentage score. This
// is a typical North American Standard (I think?).
private String getLetterGrade(int score) {
String grade = "";
if (score >= 90) { grade = "A"; }
if (score >= 80 && score <= 89) { grade = "B"; }
if (score >= 70 && score <= 79) { grade = "C"; }
if (score >= 60 && score <= 69) { grade = "D"; }
if (score >= 0 && score <= 59) { grade = "F"; }
return grade;
}
public int getSecondsPerQuestion() {
return secondsPerQuestion;
}
public void setSecondsPerQuestion(int secondsPerQuestion) {
this.secondsPerQuestion = secondsPerQuestion;
}
public String getTestFilePath() {
return testFilePath;
}
public void setTestFilePath(String testFilePath) {
this.testFilePath = testFilePath;
}
public boolean isQuestionAnswered() {
return questionAnswered;
}
public int getQuestionCount() {
return questionCount;
}
public int getRightAnswers() {
return rightAnswers;
}
public int getWrongAnswers() {
return wrongAnswers;
}
public int getDEFAULTSECONDSFORTIMEOUT() {
return DEFAULTSECONDSFORTIMEOUT;
}
}
You can use the above class on its own or add it to another project.
To use on its own within your IDE:
Create a new Project named TimedQuestions;
Create a new Java Class named TimedQuestions;
Copy/paste the above code into the new Class;
Modify the private String testFilePath; class member variable to
private String testFilePath = "Your_Quiz_path_And_File_Name";
Run the project.
To use within an existing Java Project:
Create a new Java Class named TimedQuestions within your project;
Copy/paste the above code into the new Class;
Somewhere within your project code activate the class:
TimedQuestions tq = new TimedQuestions();
tq.startTest("C:\\Quizes\\ScienceTest001.txt");
This is a very broad question and it requires an answer with some amount of opinion.
To address your first concern:
Before you being programming, you should separate the questions and answers into two separate files. One file for questions, one file for answers. Both files should be indexed 1 to N. Also, you should mark each answer to indicate which question it belongs to, and you should mark each answer with incorrect or correct.
Common file types like .txt or .csv are fine (Notepad, Excel). Database systems are good too, but they are more complex (MS SQL, MySql).
How to program the game:
Once this is done, you can use a common programming language like Java to access the question-file and access and display question by line-number. Then, you can access the answer-file and display all associated answers.
Next, you will prompt the user to make an answer-choice. Using the user's response, you will compare it against the correct answer's index. If they are the same, the user has selected correctly. If not, the user's answer is wrong. Whatever the case, you return the result of the user's decision to them.
The actual implantation of this code is pretty straightforward. You will need statements like:
read from file
read from console
write to console
if and else statements
You can find all the documentation for these statements at Java Tutorials
Joseph's answer is pretty good, and you can definitely use his suggestions to great effect. That said, another option is XML. There's a great tutorial here that breaks it down pretty nicely. I suggest you take a look at it.
You could structure your XML something like this:
<quiz>
<question type="mc">
<prompt>What color is an orange?</prompt>
<a>orange</a>
<b>blue</b>
<c>red</c>
<d>yellow</d>
<answer> a </answer>
</question>
<question type="mc">
<prompt>What color is a banana?</prompt>
<a>orange</a>
<b>blue</b>
<c>red</c>
<d>yellow</d>
<answer> d </answer>
</question>
<question type="tf">
<prompt>The sky is blue</prompt>
<a>true</a>
<b>false</b>
<answer> a </answer>
</question>
</quiz>
Of course, you could structure this however you want. But its a good way to get used to the nature of Java while also integrating a robust and customizable solution into your project.
I'm really scratching my heard on this one. I'm new at java, and I'm having the strangest thing happen.
It's homework and I'm taking it one step at a time. My issue is the loop just keeps going and stops asking for input, just keeps looping until it terminates. My comments are largely for myself. I tried to extract what was causing my problem and post it here.
Look at the "hatColor" switch, you'll notice the way I'm making sure the user enter only from the options I have allotted. Should I be using a exception handler or something?
Anyway, in short, the problem is that if I enter something with spaces, the loop skips asking for my next input. Like, if I entered "y y y y y " to the scanner when first prompted, the program will terminate and not give me the chance to enter something else.
Please, anyone that understands this, I would really appreciate your help.
import java.util.Scanner;
public class Testing
{
static String hatColor;
public static void main(String[] args) {
gameStart();
}
public static void gameStart()
{
Scanner userInput = new Scanner(System.in);
boolean keepLooping = true;
int loopCounter = 0;
System.out.println("The game begins. You must choose between 3 different colored hats."
+ " You can type white, black, or gray.");
while (keepLooping == true)
{
hatColor = userInput.next();
switch(hatColor)
{
case "white":
System.out.println("You have chosen the path of well intentioned decisions.");
walletDrop();
//the two items below are only there in case the wallet drop somehow completes without calling another method
keepLooping = false; // stops the while loop from looping again.
break; // breaks out of the switch
case "gray":
System.out.println("You have chosen the path of free will.");
walletDrop();
keepLooping = false;
break;
case "black" :
System.out.println("You have chosen the path of personal gain.");
walletDrop();
keepLooping = false;
break;
default : //we could just copy this default chunk for later switch statements
if (loopCounter >= 3)//end program on them
{
System.exit(0);
}
System.out.println("You didn't enter a usable answer. Try again");
loopCounter++;
if (loopCounter == 3)
{
System.out.println("This program will self destruct if you enter another invalid response.");
}
}//end of switch
}//end of while
}//end of game start method
public static void walletDrop()
{
System.out.println("wallet drop successful");
}
}
So I have actually solved this right after posting. In case someone else needs to look here for help:
The issue I was experiencing was due to using the scanner method
variableToAssign = scannerName.next();
instead of
variableToAssign = scannerName.nextLine();
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
So slowly relearning java since I've forgotten all of it from college. I've always wondered if I do my loops in a weird way. I feel there has to be a better way to do loops. I'm pretty sure I always make them far longer than they should be. Anyways I'm following http://programmingbydoing.com/a/twenty-questions.html as it makes me have to google a lot and forces me to come to an understanding rather than just copying code. I'm on this 20 questions part (the link). Here is the code I wrote for it, which works. But is there a better way I could do this? Or what are the other possible ways I could have done this. Does && count as a nested if statement.
edit* Come to think of it. Any critiques at all are welcome. Not necessarily just my loops. If there is anything I am doing the long version of or anything that I'm doing a strange way please let me know.
*edit2. Whoops sorry. Did not know there was a codereview area. Would have posted there if I knew it existed.
import java.util.Scanner;
public class TwoQuestions
{
public static void main (String [] args)
{
Scanner keyboard = new Scanner (System.in);
String answerOne, answerTwo;
System.out.println("Two questions game!");
System.out.println("Think of an object, and I'll try to guess it");
System.out.println("");
System.out.println("");
System.out.println("Question 1 - Is it an animal, vegetable, or random thing?");
answerOne = keyboard.next();
System.out.println("");
System.out.println("Question 2 - Is it bigger than a breadbox?");
answerTwo = keyboard.next();
if (answerOne.equals("animal") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a moose!");
}
else if (answerOne.equals("animal") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a squirrel");
}
else if (answerOne.equals("mineral") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a Camaro");
}
else if (answerOne.equals("mineral") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a paper clip");
}
else if (answerOne.equals("vegetable") && answerTwo.equals("yes"))
{
System.out.println("You are thinking of a watermelon");
}
else if (answerOne.equals("vegetable") && answerTwo.equals("no"))
{
System.out.println("You are thinking of a carrot");
}
else
{
System.out.println("Please make sure you are spelling correctly, no caps");
}
}
}
There is nothing wrong with your conditional statements, but those aren't loops.
Read this for information on loops: http://www.tutorialspoint.com/java/java_for_loop.htm
For your else case, you should ask the user for another input so they don't have to rerun the program if they make a typo.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
This is how I usually code:
public void foo (int x) {
if (x == 1) {
System.out.println("You entered one!");
} else if (x == 2) {
System.out.println("You entered two!");
} else if (x == 3){
................. and so on.
I realized that the following also produces the same results:
public void foo (int x) {
if (x == 1) {
System.out.println("You entered one!");
return;
}
if (x == 2) {
System.out.println("You entered two!");
return;
}
if (x == 3) {
...... and so on.
Which one would be better to use, even though they produce the same results and why?
I realize that there is a switch statement.
In this case, there will be almost no performance diffence. It comes down to readability.
I personally prefer a switch:
switch(x) {
case 1:
System.out.println("You entered one!");
break;
case 2:
System.out.println("You entered two!");
break;
case 3:
System.out.println("You entered three!");
break;
}
This is a "primarily opinion-based" question, but the main opinions are:
if/else (or, more importantly, fall-through to return) is better because it's bad to exit in the middle of a method. It's bad to exit in the middle because code should be structured with nested blocks ({}) and a logical progression of setup and the mirror takedown logic, and a return in the middle can result in bypassing takedown logic, often introducing subtle bugs.
if/return is better because exiting in the middle of a method is "cleaner". If the method is designed to fall-through to the return, one tends to get more and more deeply nested conditionals, as logic later in the method bypasses the "error" or "quick exit" cases that would have been handled by an embedded return. This can result in subtle bugs, and makes the code messy.
Obviously, both can't be right. Or can they?? In some cases the first argument would hold sway, in other cases the second. Anyone who claims that there's a hard-and-fast rule one way or the other (that isn't simply restating a language restriction) is just parroting some "expert" who has never really done real programming.
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've just started learning Java and I've been playing around with a few ideas. I've written the following small piece of code which when run outputs a different room in a house. The room is decided by a random integer between the value of 1 and 3. The code seems to work just fine. However, as I am new to programming my concern is that I may have misunderstood one of the tutorials informing my work and used an inefficient way to complete it.
Can anyone tell me if am I using the best practises to achieve my desired result and explain any changes I could make to make the code better?
import java.util.Random;
public class Rooms {
public static void main(String[] args) {
Random random = new Random();
int roomNumber = random.nextInt(3) + 1;
String getRoom = "";
if (roomNumber == 1) {
getRoom = "Living Room";
} else if (roomNumber == 2) {
getRoom = "Kitchen";
} else if (roomNumber == 3) {
getRoom = "Bathroom";
}
System.out.println(getRoom);
}
}
Thanks for reading this.
You could simply put the rooms into an array:
String[] rooms = { "Living Room", "Kitchen", "Bathroom" };
int roomNumber = random.nextInt(rooms.length);
System.out.println(rooms[roomNumber]);
Background: Random.nextInt(n) takes an int argument as the upperbound which returns an integer between 0 and (but not including) n. Using rooms.length here will allow you to select a random index from the array without causing an ArrayIndexOutOfBoundsException.
Your code is just fine. The only thing I can recommend is: Using switch instead of multiple-if's with else's is faster, but as you run this random once, that doesn't really matter. That switch if you need:
switch (roomNumber) {
case 1: getRoom = "Living Room";
break;
case 2: getRoom = "Kitchen";
break;
case 3: getRoom = "Bathroom";
break;
default: getRoom = "Error!";
break;
}
Also you can use List or Arrays. Arrays will speed you up too, always use arrays if you have defined number of elements.
String[] rooms = new String[]{"Living Room", "Kitchen", "Bathroom"};
getRoom = rooms[random.nextInt(rooms.length)];