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 |
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:
Project 7-3 Guessing Game import java.util.Scanner; public class GuessNumberApp { public static void main(String[] args)...
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 = 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 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; 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...
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 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...
import java.util.Scanner; public class MPGMain { public static void main(String[] args) { Scanner input = new Scanner(System.in); Mileage mileage = new Mileage(); System.out.println("Enter your miles: "); mileage.setMiles(input.nextDouble()); System.out.println("Enter your gallons: "); mileage.setGallons(input.nextDouble()); System.out.printf("MPG : %.2f",mileage.getMPG()); } } public class Mileage { private double miles; private double gallons; public double getMiles()...
import java.util.Scanner; public class TriangleMaker { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("Welcome to the Triangle Maker! Enter the size of the triangle."); Scanner keyboard = new Scanner(System.in); int size = keyboard.nextInt(); for (int i = 1; i <= size; i++) { for (int j = 0; j < i; j++) { System.out.print("*"); } System.out.println(); } for (int...
import java.util.Scanner; public class creditScore { public static void main(String[]args) { // declare and initialize variables int creditScore; double loanAmount,interestRate,interestAmount; final double I_a = 5.56,I_b = 6.38,I_c = 7.12,I_d = 9.34,I_e = 12.45,I_f = 0; String instructions = "This program calculates annual interest\n"+"based on a credit score.\n\n"; String output; Scanner input = new Scanner(System.in);// for receiving input from keyboard // get input from user System.out.println(instructions ); System.out.println("Enter the loan amount: $"); loanAmount = input.nextDouble(); System.out.println("Enter the credit score: "); creditScore...
import java.util.Scanner; public class Client{ public static void main(String args[]){ Coin quarter = new Coin(25); Coin dime = new Coin(10); Coin nickel = new Coin(5); Scanner keyboard = new Scanner(System.in); int i = 0; int total = 0; while(true){ i++; System.out.println("Round " + i + ": "); quarter.toss(); System.out.println("Quarter is " + quarter.getSideUp()); if(quarter.getSideUp() == "HEADS") total = total + quarter.getValue(); dime.toss(); System.out.println("Dime is " + dime.getSideUp()); if(dime.getSideUp() == "HEADS") total = total +...