Java Multiplication Expression Generator [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
The goal of this assignment is to generate a multiplication problem in class Multiplier to display in GameTester so that the user may input an answer. If incorrect 3 times, it will display the correct answer and then prompt whether or not they would like to play again. My overall issue is after they solve or fail to solve the problem and I prompt the next question they are unable to answer. I am looking for a more efficient way to display another question so that it is more fluid and continuous in the program.
import java.util.Scanner;
public class GameTester{
public static String question;
public static void main(String[] args){
Multiplier m = new Multiplier();
Scanner s = new Scanner(System.in);
question = m.generateProblem();
System.out.println(question);
int userAnswer = s.nextInt();
if(userAnswer == m.checkAnswer()){
System.out.println("Correct!! Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
else {
System.out.println("Sorry, the answer is incorrect. Try again!");
s.nextLine();
for(int i = 0; i <=1; i++){
System.out.println(question);
if(i != 1 && s.nextInt() != m.checkAnswer()){
System.out.println("Sorry, the answer is incorrect. Try again!");
}
else if(i == 1 && s.nextInt() != m.checkAnswer()){
System.out.println("The correct answer was " + m.checkAnswer());
System.out.println("Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
else{
System.out.println("Correct!! Want to play again?");
s.nextLine();
String user = s.nextLine();
playAgain(user);
}
}
}
}
public static void playAgain(String userInput){
if(userInput.equals("yes")){
Multiplier m2 = new Multiplier();
question = m2.generateProblem();
System.out.println(question);
}
else{
System.exit(0);
}
}
}
import java.util.Random;
public class Multiplier{
public static int product;
public Multiplier(){
}
public static String generateProblem(){
Random r = new Random();
int term1 = r.nextInt(11);
int term2 = r.nextInt(11);
product = term1 * term2;
String s = "How much is " + term1 + " times " + term2 + "?";
return s;
}
public static int checkAnswer(){
return product;
}
}

It's all a simple matter of utilizing a boolean flag and while loops at specific locations. By doing this you can actually eliminate the playAgain() method but on the same token, we create other methods to streamline the flow and eliminate duplicate code.
Since you've brought up the subject of flow, it's always a good idea to keep your Class's main() method clean and by clean I mean by only placing relevant code or calls pertaining to to the true flow of your application instead of filling it with what I call method clutter. Allow the main() method to deal with Command Line Arguments and call another method to actually start your application, branching can then go from there. Try to only place method calls that outline the true main flow of your application. Even though your project is a simple console application it's still a good habit to get into if for anything, the sake of readability. Then again...this is just my opinion and really holds no merit to any of the valid answers provided towards your post.
You might want to streamline your code like this:
package gametester;
import java.util.InputMismatchException;
import java.util.Scanner;
public class GameTester {
public static String question;
public static int questionCount = 0;
private static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
playQuiz();
}
private static void playQuiz() {
boolean playAgain = true;
System.out.println("First Question:");
while (playAgain) {
question = Multiplier.generateProblem();
System.out.println(question);
int userAnswer = getAnswer();
playAgain = processAnswer(userAnswer);
}
}
private static int getAnswer() {
int answer = 0;
while (true) {
answer = 0;
// Trap any non-numerical answers from User
try {
answer = s.nextInt();
s.nextLine();
} catch (InputMismatchException ex) {
// Needed to clear the scanner buffer otherwise
// this catch clause will play over and over again
// indefinately.
s.nextLine();
// Display an Input fault to User.
System.err.println("Incorrect Numerical Response Provided "
+ "(Numbers only please)! Try Again.\n");
// Get another answer from User.
continue;
}
break; // Good input, get outta this loop
}
return answer;
}
private static boolean processAnswer(int userAnswer) {
boolean pAgain = false;
if (userAnswer == Multiplier.checkAnswer()) {
System.out.print("Correct!! ");
pAgain = promptPlayAgain();
} else {
System.out.println("Sorry, the answer is incorrect. Try again!");
for (int i = 0; i <= 1; i++) {
System.out.print(question);
System.out.println(" (Attempt #: " + (i+2) + ")");
int ans = getAnswer();
if (i != 1 && ans != Multiplier.checkAnswer()) {
System.out.println("Sorry, the answer is incorrect. Try again!");
} else if (i == 1 && ans != Multiplier.checkAnswer()) {
System.out.println("The correct answer was " + Multiplier.checkAnswer());
pAgain = promptPlayAgain();
} else {
System.out.print("Correct!! ");
pAgain = promptPlayAgain();
break;
}
}
}
return pAgain;
}
private static boolean promptPlayAgain() {
boolean pAgain = false;
while (true) {
System.out.println("Want to play again (y or n)?");
String user = s.nextLine();
if (user.toLowerCase().charAt(0) == 'n') {
pAgain = false;
break;
} else if (user.toLowerCase().charAt(0) == 'y') {
pAgain = true;
System.out.println("\nNext Question :");
break;
} else {
System.err.println("Incorrect Response ('y' or 'n' exprected)! Try Again.\n");
}
}
return pAgain;
}
}
And your Multiplier Class:
package gametester;
import static gametester.GameTester.questionCount;
import java.util.Random;
public class Multiplier{
public static int product;
public Multiplier(){ }
public static String generateProblem(){
questionCount++;
Random r = new Random();
int term1 = r.nextInt(11);
int term2 = r.nextInt(11);
product = term1 * term2;
String s = String.valueOf(questionCount) + ") How much is " + term1 + " times " + term2 + "?";
return s;
}
public static int checkAnswer(){
return product;
}
}
Now, put a configurable time limit on each question :)

You could split the asking of the question into a method askQuestion. This would instantiate a Multiplier, output the question, and take the user's response. Your method askQuestion could either return the Multiplier, or check the answer and return a boolean indicating whether they got it right.
Your main method would then mainly contain the control loop necessary to run the program. One useful tool for repeatedly asking something is a do-while loop, which runs a block of code at least once, and then repeatedly until a condition is satisfied. For example:
boolean Correct = false;
int Attempts = 0;
do {
Correct = askQuestion();
Attempts++;
} while (!Correct && Attempts < 3);

You can use the while loop as:
public static void main(String[] args) {
Multiplier m = new Multiplier();
Scanner s = new Scanner(System.in);
question = m.generateProblem();
System.out.println(question);
String user;
int count = 0;
int userAnswer;
while (true) {
userAnswer = s.nextInt();
if (userAnswer == m.checkAnswer()) {
System.out.println("Correct!! Want to play again?");
s.nextLine();
user = s.nextLine();
playAgain(user);
count = 0;
} else {
if(count == 2){
System.out.println("The correct answer was " + m.checkAnswer());
System.out.println("Want to play again?");
s.nextLine();
user = s.nextLine();
playAgain(user);
count = 0;
} else {
System.out.println("Sorry, the answer is incorrect. Try again!");
count++;
}
}
}
}

Related

Java exception error causing code to stop suddenly

I was working on a project for class and everything works fine until the code the professor gave us that will prompt the user to "doOver" the code if they choose to, it's coming out with this error and I'm frankly confused.
I tried changing the sc.nextLine to a .hasNextLine as I've seen in other posts, but it comes up with an error stating it needs to be a boolean and then says I can not use the next doOver.trim() code on a boolean.
final static String TITLE = "ISBN-13 Generator!";
final static String CONTINUE_PROMPT = "\nDo this again? [y/n] ";
static Scanner input = new Scanner(System.in);
private static void process(Scanner sc, String args[]) {
boolean numberChecker;
String isbn;
do {
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
input.close();
isbn = isbn.trim();
numberChecker = true;
int s = 0;
do {
numberChecker = numberChecker && Character.isDigit(isbn.charAt(s));
s++;
} while (s < isbn.length() || numberChecker == false);
} while (isbn.length() != 12 & numberChecker == false);
int sum = 0;
int s = 0;
do {
if (s % 2 == 0) {
sum = sum + isbn.charAt(s) - 48;
} else {
sum = sum + 3 * (isbn.charAt(s) - 48);
}
s++;
} while (s < 12);
{
sum = 10 - (sum % 10);
if (sum == 10)
sum = 0;
}
System.out.println("Your ISBN is " + isbn + sum);
}
private static boolean doThisAgain(Scanner sc, String prompt) {
System.out.print(prompt);
String doOver = sc.nextLine();
return doOver.trim().equalsIgnoreCase("Y");
}
public static void main(String args[]) {
System.out.println("Welcome to " + TITLE);
Scanner sc = new Scanner(System.in);
do {
process(sc, args);
} while (doThisAgain(sc, CONTINUE_PROMPT));
sc.close();
System.out.println("Thank you for using the " + TITLE);
}
It should display "Do this again? [y/n]" with you inputting "y" to start the process over and entering "n" to stop and have the system print out ("Thank you for using the " + TITLE)
This is happening because you have closed the scanner instance already using line input.close();
Just comment out or delete input.close(); and your program will work as expected.
System.out.println("\nEnter the first 12 digits of an ISBN-13: ");
isbn = input.nextLine();
//input.close();
Let me know if it helps! :)

My Java code that is about for loop with factorial doesnt work like it should [duplicate]

This question already has answers here:
What is a debugger and how can it help me diagnose problems?
(2 answers)
Closed 4 years ago.
My Java code should let the user enter a number and then calculate the factorial of that number and I need to use "for loop" When I enter number 5 it tells me the factorial is 6 when it should be 120. I have tried to watch tutorials with factoring loop but they wont work, i think its because i have "do" command that gets values from calling
Here is the code:
static Scanner kboard = new Scanner(System.in); //variable to read in values
public static void main(String[] args) {
int choice = 0;
String dummy = "";
String forename = "";
String surname = "";
int number = 0;
do {
System.out.println("1. display the user name, 2. calculate factorial, 3. exit");
choice = kboard.nextInt();
dummy = kboard.nextLine(); //strips out the return
if (choice == 1) {
forename = getforename();
surname = getsurname();
displaydetails(forename, surname);
}
if (choice == 2) {
number = getnumber();
calcfactorial(number);
}
if (choice == 3) {
System.out.println("bye");
}
} while (choice != 3);
}
public static String getforename() {
String newforename = "";
System.out.println("Please enter your forename ?");
newforename = kboard.next();
return (newforename);
} // end getforename
public static String getsurname() {
/*
Code to prompt the user to enter a surname
*/
String newsurname = "";
System.out.println("Please enter your surname ?");
newsurname = kboard.next();
return (newsurname);
} // end getsurname
public static void displaydetails(String displayforename, String displaysurname) {
/*
Code will carry out prescribed changes and display the result
*/
char displayinitial;
String displayusername = "";
displaysurname = displaysurname.toUpperCase();
displayinitial = displayforename.charAt(0);
displayusername = displayinitial + displaysurname;
System.out.println("Your username is " + displayusername);
}
public static int getnumber() {
System.out.println("What numbers factorial do you want to know?");
int newnumber = kboard.nextInt();
return newnumber;
}
public static void calcfactorial(int newnumber) {
int count = 0;
int factorial = 1;
if (newnumber > 0) {
for (count = 1; count <= newnumber; count++); {
factorial = factorial * count;
System.out.println("Factorial of " + newnumber + " is: " + factorial);
}
} else {
System.out.println("Number must be positive");
}
}
If you had used a debugger, then you could tell that it's only executing the multiplication in the calcfactorial method once, and count is already 6 at this point. Reasons:
First, remove the semicolon at the end of the for condition loop. It is acting as the body of the for loop. This makes count equal to newnumber + 1, or 6.
Second, move your print statement after the end of the for loop, but still within the if block. Otherwise you'll get newnumber lines of printouts.
I am not going to fully give away the answer...user azurefrog posted a helpful link on debugging code.
However, your for loop is doing something you don't intend:
public static void calcfactorial(int newnumber)
{
int count = 0;
int factorial = 1;
if (newnumber > 0)
{
for (count=1;count<=newnumber;count++);
{
factorial = factorial * count; System.out.println("Factorial of "+newnumber+" is: "+factorial);
}
}
else
{
System.out.println("Number must be positive");
}
}
Reading through this, the line factorial = factorial * count; is just going to do 1*1, 1*2, 1*3, 1*4, 1*5, etc. for whatever is entered to be calculated for factorial. This is not the correct logic.
I recommend thinking through the logic of the for loop a bit more carefully. You should be using the number entered (i.e. 5 for the example you've given) somewhere in that loop.

What is the correct syntax for validating user input?

My code creates a set of sport results using a scanner, the user enters input in this format "Home team : Away team : Home score : Away score" - each part is split into a string in the array. I want to create an error message if one part is missing for example "Error, Home team seems to be missing" for each corresponding section however;
I am a beginner and have been trying to put an else-if condition in the for loop to help make this error message however I am doing something wrong judging by the amount of errors I am getting (delete this token).
This code will help your program to validate the user-input as per the your requirements in your question, if any of the inputs is missed by the user it is reported to him:
import java.util.Scanner;
public class Test4 {
public static void ismissing(int i)
{
switch(i)
{
case 0:
System.out.println("Home team missing");
break;
case 1:
System.out.println("Away team missing");
break;
case 2:
System.out.println("Home score missing");
break;
case 3:
System.out.println("Away score missing");
break;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Input as follows; ");
System.out.println("Home team : Away team : Home score : Away score");
String str=scanner.nextLine();
String array[]=str.split(":");
for(int i=0;i<array.length;i++)
{
if(array[i].equals(" "))
{
ismissing(i);
System.exit(0); //will exit program if something is missing
}
}
System.out.println("Correct Input");
}
}
If you are going to be creating numerous games, I would recommend you make a Game class as this will make it easier to manage a Game object as opposed to 2 Strings and 2 Integer values. With a Game object you can also output your desired string output using the toString method of your Game object. When getting the user input, the criteria I used is such that team names cannot be blank and team scores cannot be less than 0. If the user enters and empty string or an invalid integer, then we simply output a message indicating the invalid input and have the user try again until they get valid input. If you want to exit when this happens you could change this to accommodate a graceful exit of the program when the user enters invalid data.
I made two methods in the main, one to get a valid String team name, and another to get a valid Integer for the score. Again if the user inputs invalid data we will loop until the input is valid.
Game Class:
public class Game
{
String homeTeam = "";
String awayTeam = "";
int homeScore = -1;
int awayScore = -1;
public Game(String inHomeTeam, int inHomeScore, String inAwayTeam, int inAwayScore)
{
super();
this.homeTeam = inHomeTeam;
this.awayTeam = inAwayTeam;
this.homeScore = inHomeScore;
this.awayScore = inAwayScore;
}
#Override
public String toString()
{
return homeTeam + "[" + homeScore + "] | " + awayTeam + "[" + awayScore + "]";
}
public String getHomeTeam() {
return homeTeam;
}
public void setHomeTeam(String homeTeam) {
this.homeTeam = homeTeam;
}
public String getAwayTeam() {
return awayTeam;
}
public void setAwayTeam(String awayTeam) {
this.awayTeam = awayTeam;
}
public int getHomeScore() {
return homeScore;
}
public void setHomeScore(int homeScore) {
this.homeScore = homeScore;
}
public int getAwayScore() {
return awayScore;
}
public void setAwayScore(int awayScore) {
this.awayScore = awayScore;
}
}
Main
public class Main
{
static Scanner scanner = new Scanner(System.in);
static Game[] allGames;
static String homeTeam = "";
static String awayTeam = "";
static int homeScore = -1;
static int awayScore = -1;
static int numberOfGames = 0;
public static void main(String[] args)
{
numberOfGames = GetUserInt("How many games do you want to enter - 100 or less: ");
if (numberOfGames > 100)
numberOfGames = 100;
allGames = new Game[numberOfGames];
for (int i = 0; i < numberOfGames; i++) {
homeTeam = GetUserString("Enter the home team name: ");
homeScore = GetUserInt("Enter the home team score: ");
awayTeam = GetUserString("Enter the away team name: ");
awayScore = GetUserInt("Enter the away team score: ");
allGames[i] = new Game(homeTeam, homeScore, awayTeam, awayScore);
}
// output the users games
for(Game curGame : allGames)
{
if (curGame != null)
System.out.println(curGame.toString());
}
}
private static String GetUserString(String prompt)
{
String input = "";
while(true) {
System.out.print(prompt);
input = scanner.nextLine();
if (input.length() > 0)
return input;
else
System.out.println("Invalid input: Can not be empty string!");
}
}
private static int GetUserInt(String prompt)
{
String input = "";
while(true) {
System.out.print(prompt);
input = scanner.nextLine();
if (input.length() > 0) {
if (isValidInt(input)) {
int value = Integer.parseInt(input);
if (value >= 0) {
return value;
}
else {
System.out.println("Invalid input: Score can not be negative");
}
}
else {
System.out.println("Invalid input: Score must be a valid integer");
}
}
else {
System.out.println("Invalid input: Score can not be empty");
}
}
}
private static boolean isValidInt(String inString)
{
try {
Integer.parseInt(inString);
return true;
}
catch (NumberFormatException e) {
return false;
}
}
}
Hope this helps!
There are some things you can do, like checking the values with an if statement. You can say something like:
if(stringIsEmpty)
{
print ("Error");
}
else
{
/*Keep executing program*/
}
You could also use a try/catch block. This could help because if a string is null (empty), you can throw a null pointer exception and define it the way you want, like this:
try
{
/*blank string code*/
}catch(NullPointerException e)
{
System.out.println("Empty strings are not allowed");
}

Creating Methods that will produce the same result

I'm in a Beginner Java class and I'm confused about using additional methods and using them in another. I think that I have most of my assignment done but I just need help to create the methods. One is to generate the question and the other one is to display the message.
I know that in order to call a method
public static test(num1,num2,num3)
but in my code, how do I make it so that I call the method and still make it loop correctly?
In the assignment instructions that was given to me, In order to do that, I have to write a method named
public static in generateQuestion()
and
public static void displayMessage(boolean isCorrect)
This is my code:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
//Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
//Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
//Question prompt
System.out.println("How much is " +number1+ " times " +number2+ "? ");
answer = input.nextInt();
//If Else While Statements
if(answer == (number1*number2))
{
System.out.println("Good job! You got it right!");
}
else
{
while (answer !=(number1*number2))
{
System.out.println("You got it wrong, try again!");
answer = input.nextInt();
}
}
}
}
You are going to have two methods
public static void generateQuestion()
Which is going to hold the code to generate the random values and output it. It will return void because all it's doing is printing out.
Next you will have
public static void displayMessage(boolean isCorrect)
which will be called if if(answer == (number1*number2)) is true with true as the parameter. Otherwise it will still be called, but the parameter passed in will be false. This method will determine if isCorrect is true or false, and output the appropriate message.
If I got it right, I have a solution that might be a little stupid but will work for your assignment.
If you make generateQuestion that makes two random ints, prints the question and returns their multiple (answer).
And displayMessgae that prints "Good job! You got it right!" if isCorrect is true and "You got it wrong, try again!" else,
you can call generateQuestion, then get an answer (in main), and loop until answer is correct (according to return value of generateQuestion).
Every time you get a new answer (in loop), call displayMessgae(false).
After the loop ended call displayMessgae(true)
This is my working code for this:
//For Random Generator
import java.util.Random;
//Uses a class Scanner
import java.util.Scanner;
public class Assign6
{
public static int generateQuestion()
{
Random r = new Random();
int x = r.nextInt(9), y = x = r.nextInt(9);
System.out.println("How much is " + x + " times " + y + "? ");
return x * y;
}
public static void displayMessage(boolean isCorrect)
{
if (isCorrect)
System.out.println("Good job! You got it right!");
else
System.out.println("You got it wrong, try again!");
}
public static void main(String[] args)
{
//Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
int rightAnswer = 0;
rightAnswer = generateQuestion();
while (input.nextInt() != rightAnswer)
displayMessage(false);
displayMessage(true);
}
}
If I understand your question correctly, It's simply a matter of separating the functionality that prints a question and displays the answer into separate methods. See my edited version of your code below
public class Assign6
{
public static void main(String[] args)
{
// Scanner to Obtain Input from CW
Scanner input = new Scanner(System.in);
// Generate Random Number for Quiz
Random randomNumbers = new Random();
int number1 = 0;
int number2 = 0;
int answer = 0;
// Rolls number from 1-9
number1 = randomNumbers.nextInt(9);
number2 = randomNumbers.nextInt(9);
displayQuestion("How much is " + number1 + " times " + number2 + "?");
answer = input.nextInt();
// If Else While Statements
if (answer == (number1 * number2))
{
displayMessage(Boolean.TRUE);
}
else
{
while (answer != (number1 * number2))
{
displayMessage(Boolean.FALSE);
answer = input.nextInt();
}
}
}
public static void displayQuestion(String q)
{
System.out.println(q);
}
public static void displayMessage(Boolean isCorrect)
{
if (isCorrect)
{
System.out.println("Good job! You got it right!");
}
else
{
System.out.println("You got it wrong, try again!");
}
}
}

Java / Creating hi/low game using multiple methods, stuck at returning no. of guesses

I'm creating a high/low guessing game as part of a study assignment, and the part im stuck at is getting the amount of guesses returned to the main method. We have specifically been told that the main method has to print the number of guesses, while the method "playGame" actually does the playing.
There's more to the code, a method called giveReponse that checks if the number is correct or too high/low, but it works as intended. I get "Cannot find symbol" when trying to print how many guesses it took to complete the game.
If it wasn't so important to print it in the main method I'd print the amount in the method playGame, but thats a no-go. What am I doing wrong?
The code looks like this:
public class HiLo {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to classic guessing game of high/low!");
String difficulty = scan.next();
if (difficulty.equals("easy")) {
playGame(10);
} else if (difficulty.equals("medium")) {
playGame(100);
} else if (difficulty.equals("hard")) {
playGame(1000);
}
System.out.println("You won in" + guesses + "attempts.");
}//EndsMain
public static int playGame(int maxNumber) {
Scanner scan = new Scanner(System.in);
int rannr = (int)(Math.random() * maxNumber) +1;
int answer = rannr;
int guess = 0;
int guesses = 0;
System.out.println("Game is starting...");
do {
guess = scan.nextInt();
guesses ++;
giveResponse(answer, guess);
if (answer == guess) {
break;
}
} while (answer != guess);
return guesses;
} //Ends playGame
Your method playGame( ) is returning a value but since is not assigned to no variable, those returns are getting lost...
additional to that it looks like the code is not complete:
this statement is not going to let you compile:
System.out.println("You won in" + guesses + "attempts.");
because the only guesses variable I see in there is scoped in the playGame method....
do instead something like:
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to classic guessing game of high/low!");
int guesses = 0;
String difficulty = scan.next();
if (difficulty.equals("easy")) {
guesses = playGame(10);
} else if (difficulty.equals("medium")) {
guesses = playGame(100);
} else if (difficulty.equals("hard")) {
guesses = playGame(1000);
}
The problem is at:
System.out.println("You won in" + guesses + "attempts.");
Since the variable guesses is not defined in the main method, the compiler doesn't know what you are referencing to with that symbol.
But since playGame() returns the number of guesses, I'd recommend something like this:
if (difficulty.equals("easy")) {
System.out.println("You won in" +playGame(10)+ "attempts.");
} else if (difficulty.equals("medium")) {
System.out.println("You won in" +playGame(100)+ "attempts.");
} else if (difficulty.equals("hard")) {
System.out.println("You won in" +playGame(1000)+ "attempts.");
}
Here's a solution that shows how easy it would be to restrict guesses. Not much extra effort or thought:
package games;
import java.util.Random;
import java.util.Scanner;
/**
* HiLo guessing game
* Created by Michael
* Creation date 4/9/2016.
* #link https://stackoverflow.com/questions/36522303/java-creating-hi-low-game-using-multiple-methods-stuck-at-returning-no-of-gu
*/
public class HiLo {
public static void main(String [] args) {
int maxValue = (args.length > 0) ? Integer.parseInt(args[0]) : 100;
int maxGuesses = (args.length > 1) ? Integer.parseInt(args[1]) : 5;
Scanner scanner = new Scanner(System.in);
String answer = "Y";
do {
play(scanner, maxValue, maxGuesses);
System.out.println("Play again? [Y/N]: ");
answer = scanner.next();
System.out.println(String.format("You answered %s; let's play again!", answer));
} while ("Y".equalsIgnoreCase(answer));
}
private static void play(Scanner scanner, int maxValue, int maxGuesses) {
int value = new Random().nextInt(maxValue) + 1;
int numGuesses = 0;
boolean match = false;
do {
System.out.println(String.format("Guess a value between 1 and %d: ", maxValue));
int guess = Integer.parseInt(scanner.next());
if (guess < value) {
System.out.println(String.format("Too low; guess again. (%d guesses left)", (maxGuesses-numGuesses-1)));
} else if (guess > value) {
System.out.println(String.format("Too high; guess again (%d guesses left)", (maxGuesses-numGuesses-1)));
} else {
match = true;
System.out.println(String.format("You got it right in %d guesses! ", numGuesses+1));
break;
}
} while (!match && ++numGuesses < maxGuesses);
if (!match) {
System.out.println(String.format("The correct answer was %d; you're only allowed %d guesses. Better luck next time!", value, maxGuesses));
}
}
}

Categories

Resources