Question

Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args)...

Project 7-3 Guessing Game

import java.util.Scanner;

public class GuessNumberApp {
  
public static void main(String[] args) {
displayWelcomeMessage();

// create the Scanner object
Scanner sc = new Scanner(System.in);

String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// generate the random number and invite user to guess it
int number = getRandomNumber();
displayPleaseGuessMessage();

// continue until the user guesses the number
int guessNumber = 0;
int counter = 1;
while (guessNumber != number) {
// get a valid int from user
guessNumber = getIntWithinRange(sc, "Enter number: ", 0, 101);

// display result of guess to user
if (guessNumber == number) {
displayCorrectGuessMessage(counter);
} else {
displayGuessAgainMessage(number, guessNumber);
}
counter++;
}

// see if the user wants to continue
choice = getChoiceString(sc, "Try again? (y/n): ", "y", "n");
System.out.println();
}
System.out.println("Bye - Come back soon!");
System.out.println();
}

private static void displayWelcomeMessage() {
System.out.println("Welcome to the Guess the Number Game");
System.out.println("++++++++++++++++++++++++++++++++++++");
System.out.println();
}
  
private static int getRandomNumber() {
return (int) (Math.random() * 100) + 1;
}
  
private static void displayPleaseGuessMessage() {
System.out.println("I'm thinking of a number from 1 to 100.");
System.out.println("Try to guess it.");
System.out.println();
}
  
private static void displayCorrectGuessMessage(int counter) {
System.out.println("You got it in " + counter + " tries.");
if (counter <= 3) {
System.out.println("Great work! You are a mathematical wizard.\n");
} else if (counter > 3 && counter <= 7) {
System.out.println("Not too bad! You've got some potential.\n");
} else {
System.out.println("What took you so long? Maybe you should take some lessons.\n");
}
}
  
private static void displayGuessAgainMessage(int number, int guessNumber) {
int difference = guessNumber - number;
if (guessNumber > number) {
if (difference > 10) {
System.out.println("Way too high! Guess again.\n");
} else {
System.out.println("Too high! Guess again.\n");
}
} else {
if (difference < -10) {
System.out.println("Way to low! Guess again.\n");
} else {
System.out.println("Too low! Guess again.\n");
}
}
}

private static int getInt(Scanner sc, String prompt) {
int i = 0;
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
if (sc.hasNextInt()) {
i = sc.nextInt();
isValid = true;
} else {
System.out.println("Error! Invalid integer value. Try again.");
}
sc.nextLine(); // discard any other data entered on the line
}
return i;
}

private static int getIntWithinRange(Scanner sc, String prompt,
int min, int max) {
int i = 0;
boolean isValid = false;
while (!isValid) {
i = getInt(sc, prompt);
if (i <= min) {
System.out.println("Error! Number must be greater than " + min);
} else if (i >= max) {
System.out.println("Error! Number must be less than " + max);
} else {
isValid = true;
}
}
return i;
}

private static String getRequiredString(Scanner sc, String prompt) {
String s = "";
boolean isValid = false;
while (!isValid) {
System.out.print(prompt);
s = sc.nextLine();
if (s.equals("")) {
System.out.println("Error! This entry is required. Try again.");
} else {
isValid = true;
}
}
return s;
}

private static String getChoiceString(Scanner sc, String prompt,
String s1, String s2) {
String s = "";
boolean isValid = false;
while (!isValid) {
s = getRequiredString(sc, prompt);
if (!s.equalsIgnoreCase(s1) && !s.equalsIgnoreCase(s2)) {
System.out.println("Error! Entry must be '" + s1 + "' or '" + s2 + "'. Try again.");
} else {
isValid = true;
}
}
return s;
}
}

Criteria:

Console class-Create a class named Console
Move retrieve methods to Console- Move all the methods that retrieve user input to Console
Move validate methods to Console- Move all the methods that validate user input to Console
This criterion is linked to a Learning OutcomeConsole static methods-Console class methods remain static
Game class- Create a class named Game
This criterion is linked to a Learning OutcomeMove display methods to Game-Move all the methods that display messages to the Game class
Move guess methods to Game- Move all the methods that handle user guesses to the Game class
Game instance methods- Adjust Game methods so they aren't static
Game instance variables-Use instance variables of the Game class to keep track of numbers, guesses, and so on
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Following is the answer:

All the methods that are getting the input from the console are moved to this class

Console.java

import java.util.Scanner;

public class Console {

    Console(){}

    public static int getInt(Scanner sc, String prompt) {
        int i = 0;
        boolean isValid = false;
        while (!isValid) {
            System.out.print(prompt);
            if (sc.hasNextInt()) {
                i = sc.nextInt();
                isValid = true;
            } else {
                System.out.println("Error! Invalid integer value. Try again.");
            }
            sc.nextLine(); // discard any other data entered on the line
        }
        return i;
    }

    public static int getIntWithinRange(Scanner sc, String prompt,
                          int min, int max) {
        int i = 0;
        boolean isValid = false;
        while (!isValid) {
            i = getInt(sc, prompt);
            if (i <= min) {
                System.out.println("Error! Number must be greater than " + min);
            } else if (i >= max) {
                System.out.println("Error! Number must be less than " + max);
            } else {
                isValid = true;
            }
        }
        return i;
    }

    public static String getRequiredString(Scanner sc, String prompt) {
        String s = "";
        boolean isValid = false;
        while (!isValid) {
            System.out.print(prompt);
            s = sc.nextLine();
            if (s.equals("")) {
                System.out.println("Error! This entry is required. Try again.");
            } else {
                isValid = true;
            }
        }
        return s;
    }

    public static String getChoiceString(Scanner sc, String prompt,
                                  String s1, String s2) {
        String s = "";
        boolean isValid = false;
        while (!isValid) {
            s = getRequiredString(sc, prompt);
            if (!s.equalsIgnoreCase(s1) && !s.equalsIgnoreCase(s2)) {
                System.out.println("Error! Entry must be '" + s1 + "' or '" + s2 + "'. Try again.");
            } else {
                isValid = true;
            }
        }
        return s;
    }
}

All the methods are that are used to display the messages and helper methods are moved to this class and all methods are not static methods.

Game.java

public class Game {

    Game(){}

    public void displayWelcomeMessage() {
        System.out.println("Welcome to the Guess the Number Game");
        System.out.println("++++++++++++++++++++++++++++++++++++");
        System.out.println();
    }

    public int getRandomNumber() {
        return (int) (Math.random() * 100) + 1;
    }

    public void displayPleaseGuessMessage() {
        System.out.println("I'm thinking of a number from 1 to 100.");
        System.out.println("Try to guess it.");
        System.out.println();
    }

    public void displayCorrectGuessMessage(int counter) {
        System.out.println("You got it in " + counter + " tries.");
        if (counter <= 3) {
            System.out.println("Great work! You are a mathematical wizard.\n");
        } else if (counter > 3 && counter <= 7) {
            System.out.println("Not too bad! You've got some potential.\n");
        } else {
            System.out.println("What took you so long? Maybe you should take some lessons.\n");
        }
    }

    public void displayGuessAgainMessage(int number, int guessNumber) {
        int difference = guessNumber - number;
        if (guessNumber > number) {
            if (difference > 10) {
                System.out.println("Way too high! Guess again.\n");
            } else {
                System.out.println("Too high! Guess again.\n");
            }
        } else {
            if (difference < -10) {
                System.out.println("Way to low! Guess again.\n");
            } else {
                System.out.println("Too low! Guess again.\n");
            }
        }
    }


}
GuessNumberApp.java
import java.util.Scanner;

public class GuessNumberApp {

    public static void main(String[] args) {

        Game game = new Game();

        game.displayWelcomeMessage();

        // create the Scanner object
        Scanner sc = new Scanner(System.in);

        String choice = "y";
        while (choice.equalsIgnoreCase("y")) {
            // generate the random number and invite user to guess it
            int number = game.getRandomNumber();
            game.displayPleaseGuessMessage();

            // continue until the user guesses the number
            int guessNumber = 0;
            int counter = 1;
            while (guessNumber != number) {
                // get a valid int from user
                guessNumber = Console.getIntWithinRange(sc, "Enter number: ", 0, 101);

                // display result of guess to user
                if (guessNumber == number) {
                    game.displayCorrectGuessMessage(counter);
                } else {
                    game.displayGuessAgainMessage(number, guessNumber);
                }
                counter++;
            }

            // see if the user wants to continue
            choice = Console.getChoiceString(sc, "Try again? (y/n): ", "y", "n");
            System.out.println();
        }
        System.out.println("Bye - Come back soon!");
        System.out.println();
    }
}

Output:

Add a comment
Know the answer?
Add Answer to:
Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp {    public static void main(String[] args)...
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. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc...

    public static void main(String[] args) {         System.out.println("Welcome to the Future Value Calculator\n");         Scanner sc = new Scanner(System.in);         String choice = "y";         while (choice.equalsIgnoreCase("y")) {             // get the input from the user             System.out.println("DATA ENTRY");             double monthlyInvestment = getDoubleWithinRange(sc,                     "Enter monthly investment: ", 0, 1000);             double interestRate = getDoubleWithinRange(sc,                     "Enter yearly interest rate: ", 0, 30);             int years = getIntWithinRange(sc,                     "Enter number of years: ", 0, 100);             System.out.println();            ...

  • Need help debugging. first class seems fine. second class is shooting an error on s =...

    Need help debugging. first class seems fine. second class is shooting an error on s = super.getString(prompt);   third class is giving me an error in the while loop where int num = console.getInt("Enter an integer:"); //-------------------------------------------------------------------------- import java.util.Scanner; public class Console {     private Scanner sc;     boolean isValid;     int i;     double d;        public Console()     {         sc = new Scanner(System.in);     }     public String getString(String prompt)     {         System.out.print(prompt);         return sc.nextLine();...

  • Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public...

    Make a FLOWCHART for the following JAVA Prime Number Guessing Game. import java.util.Random; import java.util.Scanner; public class Project2 { //Creating an random class object static Random r = new Random(); public static void main(String[] args) {    char compAns,userAns,ans; int cntUser=0,cntComp=0; /* * Creating an Scanner class object which is used to get the inputs * entered by the user */ Scanner sc = new Scanner(System.in);       System.out.println("*************************************"); System.out.println("Prime Number Guessing Game"); System.out.println("Y = Yes , N = No...

  • import java.util.Scanner; public class Age { public static void main(String args[]) { Scanner sc = new...

    import java.util.Scanner; public class Age { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int a; System.out.println("Input your age"); a = sc.nextInt(); boolean mess = isAllowed(a); String mess2 = ?isAllowed(a)return"You are allowed to vote";:"You arent allowed"; String age = personAge(a); personAge(a); } public static String personAge(int age) { String mess = ""; if(age<18) return mess = "You are minor"; else if(age>=18 && age<=22) return mess = "You are legal you can vote"; else if(age>=22 && age<=60) return...

  • import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 {    public static void main(String[] args)    {...

    import java.util.Scanner; import java.util.ArrayList; public class P3A2_BRANDT_4005916 {    public static void main(String[] args)    {        String name;        String answer;        int correct = 0;        int incorrect = 0;        Scanner phantom = new Scanner(System.in);        System.out.println("Hello, What is your name?");        name = phantom.nextLine();        System.out.println("Welcome " + name + "!\n");        System.out.println("My name is Danielle Brandt. "            +"This is a quiz program that...

  • Consider the following sample program: import java.util.Scanner; public class Palindrome { public static void main(String[] args){...

    Consider the following sample program: import java.util.Scanner; public class Palindrome { public static void main(String[] args){ Scanner kb = new Scanner(System.in); System.out.println("Enter a word:"); String word = kb.next();    String reverse = ""; for (int i=word.length()-1; i>=0; i--) reverse += word.charAt(i); boolean result = reverse.equalsIgnoreCase(word);    if (result) System.out.println("The word " +word+ " is a Palindrome."); else System.out.println("The word " +word+ " is not a Palindrome."); } } Rewrite the program so that the main method is: public static void...

  • Need help debugging. Create an application that keeps track of the items that a wizard can...

    Need help debugging. Create an application that keeps track of the items that a wizard can carry. console application which has no errors: import java.util.Scanner; public class Console {        private static Scanner sc = new Scanner(System.in);     public static String getString(String prompt) {         System.out.print(prompt);         String s = sc.nextLine();         return s;     }     public static int getInt(String prompt) {         int i = 0;         boolean isValid = false;         while (!isValid) {             System.out.print(prompt);...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

  • import java.util.Scanner; public class SieveOfEratosthenes {    public static void main(String args[]) {       Scanner sc...

    import java.util.Scanner; public class SieveOfEratosthenes {    public static void main(String args[]) {       Scanner sc = new Scanner(System.in);       System.out.println("Enter a number");       int num = sc.nextInt();       boolean[] bool = new boolean[num];            for (int i = 0; i< bool.length; i++) {          bool[i] = true;       }       for (int i = 2; i< Math.sqrt(num); i++) {          if(bool[i] == true) {             for(int j = (i*i); j<num; j = j+i) {                bool[j] = false;...

  • import java.util.Scanner; public class StudentClient {       public static void main(String[] args)    {   ...

    import java.util.Scanner; public class StudentClient {       public static void main(String[] args)    {        Student s1 = new Student();         Student s2 = new Student("Smith", "123-45-6789", 3.2);         Student s3 = new Student("Jones", "987-65-4321", 3.7);         System.out.println("The name of student #1 is ");         System.out.println("The social security number of student #1 is " + s1.toString());         System.out.println("Student #2 is " + s2);         System.out.println("the name of student #3 is " + s3.getName());         System.out.println("The social security number...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT