Question

This is the code I have written for my Java homework assignment but I can't seem...

This is the code I have written for my Java homework assignment but I can't seem to get it to run. Any help would be appreciated!

import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;
public class javaGamev5 {
   public static void main(String[] args) throws IOException
   {
      String question = null, answerA = null, answerB = null, answerC = null ;
      int menuChoice = 0, correctAnswer = 0, points = 0, score = 0, highscore = 0;
      displayIntro();
      do {
      menuChoice = displayMainMenu();
      if (menuChoice == 1)
      {
         displayRules();
      }
      else if (menuChoice == 2)
      {
         //Declare a File object
         File inFile = new File ("questions.txt");
         //Declare Scanner
         Scanner in = new Scanner(inFile);
         for(int i = 1; i<=8;i++)
         {
            question = in.nextLine();
            answerA = in.nextLine();
            answerB = in.nextLine();
            answerC = in.nextLine();
            
            correctAnswer = in.nextInt();
            in.nextLine();
            points = in.nextInt();
            in.nextLine();
            score+=processQuestion(question, answerA, answerB, answerC, points, correctAnswer);
            displayScore(score);
         }
         in.close();
         highscore = readInHighScore();
         compareScore(highscore, score);
         JOptionPane.showMessageDialog(null, "Thanks for playing!");
      }
      else if (menuChoice == 3)
      {
         System.exit(0);
      }
      }while(menuChoice!=3);
   }  
   //Return type: int
   //Parameters: None
   //Purpose: Display intro and prompt user for name and greet them by name
   public static void displayIntro()
   {
      String name = null;
      // Display an Introduction to the Game.
      JOptionPane.showMessageDialog(null,"\n Welcome to Who Wants to Be a Java Programmer! ");  
      //Use an input dialog box to prompt the user for his/her name. 
      name= JOptionPane.showInputDialog("\n Please enter your name: "); 
      //Use an message dialog box to say hello. 
      JOptionPane.showMessageDialog(null,"\n Hello " + name + "!");
   }
   //Return type: char
   //Parameters: None
   //Purpose: To display main menu and prompt user for their choice and validate. Method returns menu choice
   public static int displayMainMenu()
   {
      String input = null;
      int menuChoice = 0;
      do
          {
        input = JOptionPane.showInputDialog("\n =====  Main Menu: =====\n >>> Enter 1 to See Rules"
          + "\n >>> Enter 2 to  Play Game\n >>> Enter 3 to  Exit Game\n"
          + "\n Please select an option from the main menu: ");
        menuChoice = int.parseInt(input);
        if (menuChoice < 1 || menuChoice > 3)
        {
           JOptionPane.showMessageDialog(null, "Invalid input! Please enter a number from 1-3 for your menu choice.");
        }
          }while(menuChoice < 1 || menuChoice > 3);
      return menuChoice;
   }
   //Return type: void
   //Parameters: None
   //Purpose: To display the rules of the game
   public static void displayRules()
   {
      JOptionPane.showMessageDialog(null, "\n =====Game Rules===== \n You will be asked 10 questions "
                + "\n If answered correctly, you will receive however many points each question is worth. "
                + "\n If answered incorrectly, you will not receive any points.\n"
                + "\n These questions will be multiple choice, by which you will use the corresponding letters (A, B or C) to choose your answer .\n");
   }
   //Return type: int
   //Parameters: 5 Strings and 2 ints
   //Purpose: To display the question and prompt for answer choice and validate. Returns the points the user earned depending on if they were correct or incorrect
   public static int processQuestion(String q1, String ansA, String ansB, String ansC,  int pointValue, int correctAns) throws IOException
    {
      int answerChoice = 0;
      String input = null;
      do 
      {
         input = JOptionPane.showInputDialog(null, q1 + "\n" + "1. " + ansA + "\n" + "2. " + ansB + "\n" + "3. " + ansC + "\n" );
         answerChoice = Integer.parseInt(input);
         if (answerChoice < 1 || answerChoice > 3)
          {
             JOptionPane.showMessageDialog(null, "Invalid input! Please enter a number from 1-3.");
          }
      }while (answerChoice < 1 || answerChoice > 3);
      if (answerChoice == correctAns)
      {
         JOptionPane.showMessageDialog(null, "You are correct!");
         return pointValue;
      }
      else 
      {
         JOptionPane.showMessageDialog(null, "Incorrect! Try again");
         return 0;
      }
    }
   //Return type: int
   //Parameters: None
   //Purpose: To read in the highscore from text file and return that value
   public static int readInHighScore() throws IOException 
   {
      int highscore = 0;
      File outFile = new File ("highscore.txt"); // This is to open the highscore file to compare with user score
      Scanner currentScore = new Scanner(outFile); // This is to read in the current highscore to compare with user score
      highscore = currentScore.nextInt();
      currentScore.close();
      return highscore;
   }
   //Return type: void
   //Parameters: 2 ints
   //Purpose: To compare the user score to highscore and update the highscore file if user attained high score
   public static void compareScore(int highScore, int userScore) throws IOException
   {
      if (userScore > highScore)
      {
         //Declare a PrintWriter object for output
         PrintWriter out = new PrintWriter("highscore.txt"); 
         out.print(userScore);
         out.close();
      }
   }
   //Return type: void
   //Parameters: 1 int
   //Purpose: To display the user's score
   public static void displayScore(int score)
   {
      JOptionPane.showMessageDialog(null, "Your total score is: " + score);
   }
}

Homework Answers

Answer #1

I am not sure what issue you were getting but i am able to run the code with slight changes. I have updated the code and pasted below. Also i have attached output screenshots.

Here is the code.

import javax.swing.JOptionPane;
import java.io.*;
import java.util.Scanner;

public class javaGamev5 {
   public static void main(String[] args) throws IOException {
       String question = null, answerA = null, answerB = null, answerC = null;
       int menuChoice = 0, correctAnswer = 0, points = 0, score = 0, highscore = 0;
       displayIntro();
       do {
           menuChoice = displayMainMenu();
           if (menuChoice == 1) {
               displayRules();
           } else if (menuChoice == 2) {
               // Declare a File object
               File inFile = new File("questions.txt");
               // Declare Scanner
               Scanner in = new Scanner(inFile);
               for (int i = 1; i <= 8; i++) {
                   if(in.hasNextLine()) {
                       question = in.nextLine();
                       answerA = in.nextLine();
                       answerB = in.nextLine();
                       answerC = in.nextLine();

                       correctAnswer = in.nextInt();
                       in.nextLine();
                       points = in.nextInt();
                       in.nextLine();
                       score += processQuestion(question, answerA, answerB, answerC, points, correctAnswer);
                       displayScore(score);
                   }
               }
               in.close();
               highscore = readInHighScore();
               compareScore(highscore, score);
               JOptionPane.showMessageDialog(null, "Thanks for playing!");
           } else if (menuChoice == 3) {
               System.exit(0);
           }
       } while (menuChoice != 3);
   }

   // Return type: int
   // Parameters: None
   // Purpose: Display intro and prompt user for name and greet them by name
   public static void displayIntro() {
       String name = null;
       // Display an Introduction to the Game.
       JOptionPane.showMessageDialog(null, "\n Welcome to Who Wants to Be a Java Programmer! ");
       // Use an input dialog box to prompt the user for his/her name.
       name = JOptionPane.showInputDialog("\n Please enter your name: ");
       // Use an message dialog box to say hello.
       JOptionPane.showMessageDialog(null, "\n Hello " + name + "!");
   }

   // Return type: char
   // Parameters: None
   // Purpose: To display main menu and prompt user for their choice and validate.
   // Method returns menu choice
   public static int displayMainMenu() {
       String input = null;
       int menuChoice = 0;
       do {
           input = JOptionPane.showInputDialog("\n ===== Main Menu: =====\n >>> Enter 1 to See Rules"
                   + "\n >>> Enter 2 to Play Game\n >>> Enter 3 to Exit Game\n"
                   + "\n Please select an option from the main menu: ");
           menuChoice = Integer.parseInt(input);
           if (menuChoice < 1 || menuChoice > 3) {
               JOptionPane.showMessageDialog(null,
                       "Invalid input! Please enter a number from 1-3 for your menu choice.");
           }
       } while (menuChoice < 1 || menuChoice > 3);
       return menuChoice;
   }

   // Return type: void
   // Parameters: None
   // Purpose: To display the rules of the game
   public static void displayRules() {
       JOptionPane.showMessageDialog(null, "\n =====Game Rules===== \n You will be asked 10 questions "
               + "\n If answered correctly, you will receive however many points each question is worth. "
               + "\n If answered incorrectly, you will not receive any points.\n"
               + "\n These questions will be multiple choice, by which you will use the corresponding letters (A, B or C) to choose your answer .\n");
   }

   // Return type: int
   // Parameters: 5 Strings and 2 ints
   // Purpose: To display the question and prompt for answer choice and validate.
   // Returns the points the user earned depending on if they were correct or
   // incorrect
   public static int processQuestion(String q1, String ansA, String ansB, String ansC, int pointValue, int correctAns)
           throws IOException {
       int answerChoice = 0;
       String input = null;
       do {
           input = JOptionPane.showInputDialog(null,
                   q1 + "\n" + "1. " + ansA + "\n" + "2. " + ansB + "\n" + "3. " + ansC + "\n");
           answerChoice = Integer.parseInt(input);
           if (answerChoice < 1 || answerChoice > 3) {
               JOptionPane.showMessageDialog(null, "Invalid input! Please enter a number from 1-3.");
           }
       } while (answerChoice < 1 || answerChoice > 3);
       if (answerChoice == correctAns) {
           JOptionPane.showMessageDialog(null, "You are correct!");
           return pointValue;
       } else {
           JOptionPane.showMessageDialog(null, "Incorrect! Try again");
           return 0;
       }
   }

   // Return type: int
   // Parameters: None
   // Purpose: To read in the highscore from text file and return that value
   public static int readInHighScore() throws IOException {
       int highscore = 0;
       File outFile = new File("highscore.txt"); // This is to open the highscore file to compare with user score
       Scanner currentScore = new Scanner(outFile); // This is to read in the current highscore to compare with user
                                                       // score
       highscore = currentScore.nextInt();
       currentScore.close();
       return highscore;
   }

   // Return type: void
   // Parameters: 2 ints
   // Purpose: To compare the user score to highscore and update the highscore file
   // if user attained high score
   public static void compareScore(int highScore, int userScore) throws IOException {
       if (userScore > highScore) {
           // Declare a PrintWriter object for output
           PrintWriter out = new PrintWriter("highscore.txt");
           out.print(userScore);
           out.close();
       }
   }

   // Return type: void
   // Parameters: 1 int
   // Purpose: To display the user's score
   public static void displayScore(int score) {
       JOptionPane.showMessageDialog(null, "Your total score is: " + score);
   }
}

--------------------------------------------------------OUTPUT------------------------------------------------------------

Please upvote if my answered helped you.

BEST OF LUCK!

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
I am a beginner when it comes to java codeing. Is there anyway this code can...
I am a beginner when it comes to java codeing. Is there anyway this code can be simplified for someone who isn't as advanced in coding? public class Stock { //fields private String name; private String symbol; private double price; //3 args constructor public Stock(String name, String symbol, double price) { this.name = name; this.symbol = symbol; setPrice(price); } //all getters and setters /** * * @return stock name */ public String getName() { return name; } /** * set...
Here is my java code, I keep getting this error and I do not know how...
Here is my java code, I keep getting this error and I do not know how to fix it: PigLatin.java:3: error: class Main is public, should be declared in a file named Main.java public class Main { ^ import java.io.*; public class Main { private static BufferedReader buf = new BufferedReader( new InputStreamReader(System.in)); public static void main(String[] args) throws IOException { String english = getString(); String translated = translate(english); System.out.println(translated); } private static String translate(String s) { String latin =...
Start with the code below and complete the getInt method. The method should prompt the user...
Start with the code below and complete the getInt method. The method should prompt the user to enter an integer. Scan the input the user types. If the input is not an int, throw an IOException; otherwise, return the int. In the main program, invoke the getInt method, use try-catch block to catch the IOException. import java.util.*; import java.io.*; public class ReadInteger { pubilc static void main() { // your code goes here } public static int getInt() throws IOException...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The...
THIS IS FOR JAVA I have to write a method for a game of Hangman. The word the user is trying to guess is made up of hashtags like so " ###### " If the user guesses a letter correctly then that letter is revealed on the hashtags like so "##e##e##" If the user guesses incorrectly then it increments an int variable named count " ++count; " String guessWord(String guess,String word, String pound) In this method, you compare the character(letter)...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code...
Complete a Java program named ARMgr that maintains customer accounts receivable in a database. The code to initialize the CustomerAccountsDB database table and add a set of customer accounts is provided. Finish the code in these 3 methods in CustomerAccountDB.java to update or query the database: -purchase(double amountOfPurchase) -payment(double amountOfPayment) -getCustomerName() Hint: For getCustomerName(), look at the getAccountBalance() method to see an example of querying data from the database. For the purchase() and payment() methods, look at the addCustomerAccount() method...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list...
Assignment 1 - ITSC 2214 I have to complete the array list for a shopping list code and can't figure out how to complete it: Below is the code Complete the three empty methods (remove(), find(), and contains()) in the ShoppingListArrayList.java file. These methods are already implemented in the ShoppingListArray class. /////////////////////////////////////////////////////////////////////////////////////////////////////////// Grocery Class (If this helps) package Shopping; public class Grocery implements Comparable<Grocery> { private String name; private String category; private int aisle; private float price; private int quantity;...
I wrote the following java code with the eclipse ide, which is supposed to report the...
I wrote the following java code with the eclipse ide, which is supposed to report the number of guesses it took to guess the right number between one and five. Can some repost the corrected code where the variable "guess" is incremented such that the correct number of guesses is displayed? please test run the code, not just look at it in case there are other bugs that exist. import java.util.*; public class GuessingGame {    public static final int...
main The main method instantiates an ArrayList object, using the Car class. So, the ArrayList will...
main The main method instantiates an ArrayList object, using the Car class. So, the ArrayList will be filled with Car objects. It will call the displayMenu method to display the menu. Use a sentinel-controlled loop to read the user’s choice from stdin, call the appropriate method based on their choice, and redisplay the menu by calling displayMenu. Be sure to use the most appropriate statement for this type of repetition. displayMenu Parameters:             none Return value:          none Be sure to use...
Hello, I am trying to create a Java program that reads a .txt file and outputs...
Hello, I am trying to create a Java program that reads a .txt file and outputs how many times the word "and" is used. I attempted modifying a code I had previously used for counting the total number of tokens, but now it is saying there is an input mismatch. Please help! My code is below: import java.util.*; import java.io.*; public class Hamlet2 { public static void main(String[] args) throws FileNotFoundException { File file = new File("hamlet.txt"); Scanner fileRead =...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length();...
import java.util.Scanner; public class FindMinLength { public static int minLength(String[] array) { int minLength = array[0].length(); for (int i = 0; i < array.length; i++) { if (array[i].length() < minLength) minLength = array[i].length(); } return minLength; } public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] strings = new String[50]; for (int i = 0; i < strings.length; i++) { System.out.print("Enter string " + (i + 1) + ": "); strings[i] = in.nextLine(); } System.out.println("Length of smallest...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT