I'm currently a senior high school student and I'm doing a short quiz game as a project. And I was wondering if you can add multiple questions. Here Is the code
import java.util.Scanner;
import java.util.Random;
public class Quiz
{
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
Random r = new Random();
int lives = 3;
String answers;
while (lives > 0)
{
System.out.println("Question Goes Here: ");
answers = s.nextLine();
if (answers.equalsIgnoreCase("Answer"))
{
System.out.println("Correct! Please press ENTER to continue");
s.nextLine();
}
//TO-DO IF THE ANSWER IS WRONG
else
{
--lives;
System.out.println("You have " + lives + " lives left");
}
}
//TO-DO IF "LIVES" IS EQUAL TO 0
if (lives == 0)
{
System.out.println("Game Over");
}
}
Assuming that you have prepared a 2D array of questions and answers:
final Scanner s = new Scanner(System.in);
String[][] arrQA = {
{"question1", "answer1"},
{"question2", "answer2"},
{"question3", "answer3"},
{"question4", "answer4"},
};
int lives = 3;
int success = 0;
for (int i = 0; i < arrQA.length && lives > 0; i++) {
String[] qa = arrQA[i];
System.out.print(qa[0] + " goes here, type your answer: ");
String answer = s.nextLine();
if (answer.equalsIgnoreCase(qa[1])) {
success++;
System.out.println("Correct! Please press ENTER to continue");
s.nextLine();
} else {
--lives;
System.out.println("Incorrect! You have " + lives + " lives left");
}
}
System.out.println("Game Over! You have answered " + success + " questions correctly");
I would recommend creating a POJO class for questions. Something like this:
class Question{
String question;
String answer;
public Question(String question, String answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
}
And then create your main function, with the list of questions, iterate over your question with some variable.
public static void main(final String[] args) {
//Variables
final Scanner s = new Scanner(System.in);
final Random r = new Random();
int lives = 3;
String answers;
ArrayList<Question> quizBrain = new ArrayList<Question>();
quizBrain.add(new Question("question1", "answer1"));
quizBrain.add(new Question("question2", "answer2"));
quizBrain.add(new Question("question3", "answer3"));
quizBrain.add(new Question("question4", "answer4"));
quizBrain.add(new Question("question5", "answer5"));
int questionCounter = 0;
//Conditions
while (lives > 0)
{
System.out.println(quizBrain.get(questionCounter).getQuestion());
answers = s.nextLine();
if (answers.equalsIgnoreCase(quizBrain.get(questionCounter).getAnswer()))
{
System.out.println("Correct! Please press ENTER to continue");
questionCounter++;
s.nextLine();
}
//TO-DO IF THE ANSWER IS WRONG
else
{
--lives;
System.out.println("You have " + lives + " lives left");
}
}
//TO-DO IF "LIVES" IS EQUAL TO 0
if (lives == 0)
System.out.println("Game Over");
}
You can see this for the advantages of POJO class. It would be a great help if you need to store your question in the database.
I recomend you to create an array with all the questions and then acces it with math.random. You will also have to create an array for the answers in the same order as the question's one, so math.random can get the correct answer for the choosen question.
Related
I want to make a quiz program in java, i need an output that if the user chose the wrong answer all question will repeat until the the user chose the correct answer and put an output that must display also the key to correction and i hope you all help guys on my quiz program in java. and i want to correct my score when 5 wrong answer will back in the question with two wrong answer. when i run the code the score is 178 points with the 5 wrong answer in code but when i perfect the quiz the score is 150 that's is the total score of my quiz
int score = 0;
int count = 0;
String name;
String age;
String subject;
String course;
String schoolyear;
name = JOptionPane.showInputDialog("Enter your name");
age = JOptionPane.showInputDialog("Enter your age");
subject = JOptionPane.showInputDialog("Enter your subject");
course = JOptionPane.showInputDialog("Enter your course");
schoolyear = JOptionPane.showInputDialog("Enter your school year today");
boolean a = true;
boolean b = true;
boolean c = true;
do {
if (a == true) {
String question1 =JOptionPane.showInputDialog("What year when the release of Java?\n"
+ ("2 points \n")
+ ("The answer is B\n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n" );
if("B".equals(question1))
{
System.out.println("Correct\n");
score+= 2;
count++;
a = false;
}else{
System.out.println("Incorrect\n");
}
}
if (b == true) {
String question2 =JOptionPane.showInputDialog("Who created Java?\n"
+ ("2 points \n")
+ ("The answer is B\n")
+ "(A.)Manny Pacquio\n (B.)James Gosling\n (C.)James Bond\n (D.)Matt Damon\n");
if("B".equals(question2))
{
System.out.println("Correct\n");
score+= 2;
count++;
b = false;
}else{
System.out.println("Incorrect\n");
}
}
if (c == true) {
String question3 =JOptionPane.showInputDialog("In Which team where Java created?\n"
+ ("2 points \n")
+ ("The answer is D\n")
+ "(A.)Team Black\n (B.)Team White\n (C.)Team Brown\n (D.)Team Green\n" );
if("D".equals(question3))
{
System.out.println("Correct\n");
score+= 2;
count++;
c = false;
}else{
System.out.println("Incorrect\n");
}
} while (count <3);
}
Scanner input = new Scanner(System.in);
System.out.println("Your score: " + score);
System.out.println(100 *score/150 + "%");
if (score >=150) {
System.out.println("Excellent");
} else if (score >=140) {
System.out.println("Ultimatum!");
} else if (score >=120) {
System.out.println("Great Job!");
} else if (score >=100) {
System.out.println("Good Job!");
} else if (score >=80) {
System.out.println("Pass");
} else if (score >=60) {
System.out.println("Passangawa");
} else if (score >=40) {
System.out.println("Satisfy");
} else if (score >=20) {
System.out.println("Try again");
} else if (score >=0) {
System.out.println("Failed");
} else {
System.out.println("Wasted!");
```All question will repeat until the user chose the correct answer and i need the score will be correct when one or more wrong answer will back to answer again and the score will back to its correct score with the 28 question in total.
I suggest to use while loop and add some flag if the answer is correct and iterate until it will be correct
QUESTION
public class Question {
private String question;
private String answer;
public Question(String question, String answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
MAIN
public static void main(String[] args) {
int score = 0;
Question q1 = new Question("What year when the release of Java?\n" + ("2 points \n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n", "B");
Question q2 = new Question("What is hourse" + ("2 points \n") + "(A.)Animal\n (B.)Dog\n (C.)Human\n (D.)Lake\n",
"A");
List<Question> questionsList = new ArrayList<>();
questionsList.add(q1);
questionsList.add(q2);
for(Question question : questionsList) {
boolean isCorrectQuestion = false;
while (!isCorrectQuestion) {
String answer = JOptionPane.showInputDialog(question.getQuestion());
if (question.getAnswer().equals(answer)) {
System.out.println("Correct\n");
score += 2;
isCorrectQuestion = true;
} else {
System.out.println("Incorrect\n");
}
}
}
}
By the way first release of Java was in 1996
public static void main(String[] args) {
int score = 0;
int count = 0;
boolean a = true;
boolean b = true;
do {
if (a == true) {
String question1 = JOptionPane.showInputDialog("What year when the release of Java?\n"
+ ("2 points \n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n");
if ("B".equals(question1)) {
System.out.println("Correct\n");
score += 2;
count++;
a = false;
} else {
System.out.println("Incorrect\n");
}
}
if (b == true) {
String question2 = JOptionPane.showInputDialog("#2: What year when the release of Java?\n"
+ ("2 points \n")
+ "(A.)1990\n (B.)1991\n (C.)1998\n (D.)1980\n");
if ("B".equals(question2)) {
System.out.println("Correct\n");
score += 2;
count++;
b = false;
} else {
System.out.println("Incorrect\n");
}
}
} while (count < 2);
}
}
i am having trouble passing the value of "guess" into my main method. The
method that is trying to return guess just shows up as zero in the main.I have tried various things such as void methods and different returns but the guess value does not get updated in the while loop of the main even though, from what i am seeing, it should be getting updated from the method and passing it down to the guesses right below it.
import java.util.*;
public class assignment052 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
int userGuess = 0;
int compNum = 0;
int guess = 0;
int totalGuesses = 0; //
int best = 9999; //
introduction();
int games = 0;
String playAgain = "y";
while(playAgain.equalsIgnoreCase("y")) {
System.out.println();
System.out.println("I'm thinking of a number between 1 and 100...");
games++;
guessNumber(console, userGuess, compNum, guess);
System.out.println(guess);
totalGuesses += guess;
System.out.println("Do you want to play again?");
Scanner newGame = new Scanner(System.in);
playAgain = newGame.next();
if (best > guess) { //
best = guess; //
}
}
result(games, totalGuesses, best);
}
// Method that introduces the game
public static void introduction() {
System.out.println("This program allows you to play a guessing game.");
System.out.println("I will think of a number between 1 and");
System.out.println("100 and will allow you to guess until");
System.out.println("you get it. For each guess, I will tell you");
System.out.println("whether the right answer is higher or lower");
System.out.println("than your guess.");
}
// method to play 1 game
public static double guessNumber(Scanner console, int userGuess, int compNum, int guess) {
Random rand = new Random();
userGuess = console.nextInt();
guess = 1;
compNum = rand.nextInt(100)+1;
while(compNum != userGuess) {
if(compNum > userGuess) {
System.out.println("It's higher.");
} else {
System.out.println("It's lower.");
}
guess++;
userGuess = console.nextInt();
}
System.out.println("you got it right in " + guess + " guesses");
return guess;
}
// method for overall result
public static void result(int games, int totalGuesses, int best) {
System.out.println("Overall results:");
System.out.println();
System.out.println("Total games played : " + games);
System.out.println("Total guesses : " + totalGuesses);
System.out.println("Guesses per game : " + totalGuesses / games);
}
}
I know it's a silly silly program. It's just to practice constructors.
public class PetRecord {
private String name = "Bob";
private int age;
private double weight;
public PetRecord(String initialName, int initialAge, double initialWeight) {
name = initialName;
if(initialAge < 0 || weight < 0) {
System.out.println("Error: Age or weight cannot be negative");
System.exit(0);
}
else {
age = initialAge;
weight = initialWeight;
}
}
public PetRecord(String initialName) {
name = initialName;
}
public void output() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Weight: " + weight);
}
public void setAll(String newName, int newAge, double newWeight) {
name = newName;
if ((newAge < 0) || (newWeight < 0)) {
System.out.println("Error: Negative age or weight.");
System.exit(0);
}
else {
age = newAge;
weight = newWeight;
}
}
public void review() {
if(age < 8 && weight < 8) {
System.out.println("Your pets weight and age are healthy.");
}
if(age >= 8 && weight >=8) {
System.out.println("Your pets weight and age are unhealthy.");
}
else {
System.out.println("Come to my office for a proper assessment.");
}
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
PetRecord d = new PetRecord("Bob");
System.out.println("Please check if our current records are correct.");
d.output();
System.out.println("Are they correct?");
String answer = input.nextLine();
String yes = "Yes";
String no = "No";
if((answer.equals(yes))) {
System.exit(0);
}
if(answer.equals(no)) {
System.out.println("Please enter your pets name.");
String correctName = input.nextLine();
System.out.println("Age?");
int correctAge = input.nextInt();
System.out.println("Weight?");
double correctWeight = input.nextDouble();
d.setAll(correctName, correctAge, correctWeight);
System.out.println("Your updated records say: ");
d.output();
System.out.println("Would you like a health review?");
String answer1 = input.nextLine();
String yes1 = "yes";
String no1 = "no";
if(answer1.equals(yes1)) {
d.review();
}
if(answer1.equals(no1)) {
System.out.println("Thank you for using PetSystem. Goodbye.");
System.exit(0);
}
}
}
}
My program accepts input for String answer, but my program will not accept String answer1. I can't even type anything in the console after the program asks you if you would like a health review.
The issue comes from here
System.out.println("Your updated records say: ");
d.output();
Because you have printed something out in the middle of accepting input, you most likely have an extra newline token you have not dealt with. Prior to asking the "health review" question place the following code.
while (input.hasNextLine()) {
input.nextLine();
}
This will make sure that you clear out any extra tokens before continuing to accept user input.
you can,t type anything in the console after "if you would like a health review." because you code only runs ones you should put it in a loop to make it run more than once
So my objective is to create a maths game where the user selects if he/she wants a maths question from a file or a random generate one consisting of the 4 maths elements in 3 difficulties.I have created a lot of methods... I have an idea where im going but now im stuck. I need to have it so it keeps a score of questions answered correctly. How do i return the points to the main method and have the game going until the user presses 3 on the gamePlay()method
public class MathsGameProject2 {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int score;
int points = 0;
int questionType;
System.out.print("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
questionType = keyboard.nextInt();
while (questionType != 3) {
if (questionType == 1) {
questionFromFile();
} else if (questionType == 2) {
randomQuestion();
} else {
System.out.println("Please enter the what type of question you want" + "\n 1 Question from a file" + "\n 2 Random question" + "\n 3 Quit game\n");
}
}
}
public static questionFromFile() {
}
public static randomQuestion() {
Scanner keyboard = new Scanner(System.in);
int difficulty;
System.out.println("Please enter the difficulty you want to play." + "\n 1. Easy" + "\n 2. Medium" + "\n 3. Hard\n");
difficulty = keyboard.nextInt();
if (difficulty == 1) {
easy();
} else if (difficulty == 2) {
medium();
} else if (difficulty == 3) {
hard();
} else {
System.out.println("Please enter a number between 1-3\n");
}
}
public static easy() {
Scanner keyboard = new Scanner(System.in);
int mathElement;
System.out.print("What element of maths do you want?" + "\n1 Additon" + "\n2 Subtraction" + "\n3 Multiplication" + "\n4 Division\n");
mathElement = keyboard.nextInt();
if (mathElement == 1) {
easyAdd();
} else if (mathElement == 2) {
easySub();
} else if (mathElement == 3) {
easyMulti();
} else if (mathElement == 4) {
easyDiv();
} else {
System.out.println("Please enter a number between 1-4\n");
}
}
public static easyAdd() {
Scanner keyboard = new Scanner(System.in);
Random rand = new Random();
int num = rand.nextInt(10) + 1;
int num2 = rand.nextInt(10) + 1;
int correct = num + num2;
int answer;
System.out.print("What is the answer of " + num + " + " + num2 + " ?");
answer = keyboard.nextInt();
if (answer == correct) {
}
}
In order to keep track of how many questions the user answers successfully, you will need to:
For each question, return whether or not the user answered correctly
Have a counter which increments whenever a user answers a question correctly
Optionally, have a counter which increments whenever a question is answered wrong
For #1, you can use a boolean return value for specifying if the question was answered successfully.
return (answer == correct);
You will want to propagate that return value all the way up to the main() method.
static void main() {
....
boolean isCorrect = randomQuestion();
....
}
static boolean randomQuestion() {
....
return easy();
....
}
static boolean easy() {
....
return easyAdd();
....
}
static boolean easyAdd() {
...
return (answer == correct);
}
Then for #2 and #3, you can increment counter(s) defined in main based on the value returned by randomQuestion()
int numberCorrect = 0;
int numberWrong = 0;
....
boolean isCorrect = randomQuestion();
if (isCorrect) {
numberCorrect++;
} else {
numberIncorrect++;
}
Additionally (no pun intended), you can use a while loop to continuously receive user input until you get your exit code, which in this case is 3. One way to do this is to use a while(true) loop and break out when the user enters 3.
while (true) {
/* Get user input */
....
if (questionType == 3) {
break;
}
}
Finally, after your loop, you can simply print out the value of your numberCorrect and numberIncorrect counters.
Hope this helps.
I have been working on this bank program for my Java class at school for the past week and a half. I thought I finally had it working the way my instructor wanted. However, when I try to access an account that does not exist, the program "blows up" (my instructors words). I need it to let the user know that the account does not exist and redirect them back to the main menu. So, my problem I believe is in my findAcct method in my Bank class. I have tried several fixes but none have worked. Any insight or help would be greatly appreciated! I need to have this done by Monday. I know I said the problem is in one method, but I'll post my whole program for context.
Bank Class
import java.util.Scanner;
public class Bank
{
private int max = 25;
private int count;
bankAcct myAcct[] = new bankAcct[max];
Scanner scannerObject = new Scanner(System.in);
public void openAcct()
{
if (count >= max){
System.out.println("Not accepting new customers at this time.");
}else{
System.out.println("Please enter your name: ");
String lname = scannerObject.next();
myAcct[count] = new bankAcct(count + 1, 25, lname);
count++;
System.out.println("Thank you " + lname + ", your account number is: " + count);
}
}
public int findAcct() // This is the method in question
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
}
}
return found;
}
public void seeBal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].dispBal();
}
}
public void Deposit()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeDeposit();
}
}
public void Withdrawal()
{
int lfound = findAcct();
if (lfound == -1){
System.out.println("Error!");
}else{
myAcct[lfound].makeWithdrawal();
}
}
}
bankAcct Class
import java.util.Scanner;
public class bankAcct
{
private double Bal;
private int acctNum;
private String name;
Scanner scannerObject = new Scanner(System.in);
public bankAcct(int pAcctNum, double pBal, String pName)
{
Bal = pBal;
acctNum = pAcctNum;
name = pName;
}
public void makeDeposit()
{
System.out.print( "Hello " + name + ", please, enter amount to deposit $");
double lDep = scannerObject.nextDouble();
Bal = Bal + lDep;
System.out.println( " You have deposited $" + lDep);
System.out.println( " Your new balance is $" + Bal);
}
public void makeWithdrawal()
{
System.out.print( "Hello " + name + ", please, enter amount to withdraw $");
double lWDraw = scannerObject.nextDouble();
if (lWDraw <= Bal){
Bal = Bal - lWDraw;
System.out.println( "You have withdrawn $" + lWDraw);
System.out.println( "Your new balance is $" + Bal);
}else{
System.out.println("Insufficient funds!");
}
}
public void dispBal()
{
System.out.println( "Hello " + name + ", your current balance is $" + Bal);
}
public int getAcctNum()
{
return acctNum;
}
public void setName(String pName)
{
name = pName;
}
public String getName()
{
return name;
}
}
bankUser Class
import java.util.Scanner;
public class bankUser
{
public static void main(String[] args)
{
Bank myBank = new Bank();
int Choice;
do
{
dispMenu();
Choice = getChoice();
proChoice(Choice, myBank);
}
while (Choice !=0);
}
public static void dispMenu()
{
System.out.println( "|==================================|");
System.out.println( "| TONY'S FIRST NATIONAL BANK |");
System.out.println( "|***********Menu Options***********|");
System.out.println( "|__________________________________|");
System.out.println( "| Press [1] To Open New Account |");
System.out.println( "| Press [2] To View Balance |");
System.out.println( "| Press [3] To Make Deposit |");
System.out.println( "| Press [4] To Make Withdrawal |");
System.out.println( "| Press [0] to Exit |");
System.out.println( "|__________________________________|");
System.out.println( "| Please Make Selection Now... |");
System.out.println( "|==================================|");
}
static int getChoice()
{
Scanner scannerObject = new Scanner(System.in);
int pChoice, Choice;
pChoice = scannerObject.nextInt();
Choice = pChoice;
return Choice;
}
static void proChoice(int Choice, Bank myBank)
{
switch (Choice)
{
case 1: myBank.openAcct();
break;
case 2: myBank.seeBal();
break;
case 3: myBank.Deposit();
break;
case 4: myBank.Withdrawal();
break;
case 0: System.out.println( "Thank you, come again.");
break;
}
}
}
Again, any help would be greatly appreciated. I am still a padawan when it comes to Java.
*UPDATE: I have tried this code, and it seems to work! However, my instructor told me that we can never have 2 return statements within a method.
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
return found = i;
}
}
return -1;
}
UPDATE: Here is what I did to my findAcct method in my Bank Class:
public int findAcct()
{
System.out.println("Greetings, please enter your account number: ");
int acctNum = scannerObject.nextInt();
int found = -1;
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == acctNum){
found = i;
break; //Ends Loop
}
}
return found;
}
My instructor did not mind a break statement, so I added out at the end of my for loop. I also moved my local variable found = -1; down a couple lines. Thank you for all the help! I can't wait to learn more!
If you do not want to have 2 return statements within a method (which you can have, but sometimes it is bad practice when you are beginning coding so professors like to just make that rule) you can use your found variable to store the value that will be returned and return found at the end of the function.
You were on the right track.
Example:
public int findAcct()
{
int found = -1;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(myAcct[i].getAcctNum() == found){
found = i;
break; //Exit out of the loop
}
}
return found;
}
This code will set found to i if it finds the account and then break out of the loop. After it breaks out of the loop it will return found. Otherwise, found will never be set and return -1 since you initialized it to -1 at the top.
If your instructor has not taught you break statements yet, then you can use a boolean variable foundAccount initialized to false. Then check if foundAccount is false before doing your if statement check. Once you find it, set it to true so you do not keep looking.
Example:
public int findAcct()
{
int found = -1;
boolean foundMatch = false;
System.out.println("Greetings, please enter your account number: ");
found = scannerObject.nextInt();
for(int i = 0; i < count; i++){
if(!foundMatch){
if(myAcct[i].getAcctNum() == found){
found = i;
foundMatch = true; //we will no longer search
}
}
}
return found;
}