I need help converting my code from c++ to java [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
One of my assignments is to convert a famous coding game called NIM from C++ to Java using three different methods. I'm having trouble converting it from C++ to Java. Can anyone help me fix my problem?
This is what they gave me in C++:
#include <iostream.h>
#include <lvp\random.h>
#include <lvp\bool.h>
//-----------------------------------------------------------------------------
void UserMove(int &NumStones)
/* Pre: NumStones > 0
Post: User has taken 1, 2, or 3 stones from pile */
{
cout << "How many would you like? ";
int TakeStones;
cin >> TakeStones;
while (TakeStones<1 || TakeStones>3 || TakeStones>NumStones) {
cout << "Value must be between 1 and 3" << endl;
cout << "How many would you like? ";
cin >> TakeStones;
}
NumStones-=TakeStones;
}
//-----------------------------------------------------------------------------
void ComputerMove(int &NumStones)
/* Pre: NumStones > 0
Post: Computer has taken 1, 2, or 3 stones from pile */
{
int TakeStones;
do {
TakeStones=1+random(3);
} while (TakeStones<1 || TakeStones>3 || TakeStones>NumStones);
cout << "The computer takes " << TakeStones << "." << endl;
NumStones-=TakeStones;
}
//-----------------------------------------------------------------------------
void PlayNim(NumStones)
/* Post: A game of Nim played with NumStones stones */
{
while (true) {
if (NumStones>0) {
cout << "There are " << NumStones << " stones. ";
UserMove(NumStones);
}
else {
cout << "You win!";
break;
}
if (NumStones>0) {
cout << "There are " << NumStones << " stones. ";
ComputerMove(NumStones);
}
else {
cout << "Computer wins!";
break;
}
}
}
//-----------------------------------------------------------------------------
int main()
{
randomize();
int NumStones=15+random(16);
PlayNim(NumStones);
return(0);
}
And this is what I got from converting it over to Java:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
public class Nim {
public static void Usermove(int numstones) {
Scanner input = new Scanner(System.in);
numstones = 0;
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while (takestones > numstones) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
numstones-=takestones;
}
public static void Computermove(int numstones) {
Random rand = new Random();
int takestones;
int random = rand.nextInt(3);
do {
takestones=1 + random;
} while (takestones > numstones);
System.out.println("The computer takes" + takestones + ".");
numstones-=takestones;
}
public static void PlayNim(int numstones) {
while(true){
if (numstones>0) {
System.out.println("There are" + numstones + "stones");
Usermove(numstones);
}
else {
System.out.print("You Win!");
break;
}
if (numstones>0) {
System.out.println("There are" + numstones + "stones");
Computermove(numstones);
break;
}
}
}
public static void main(String[] args) {
Random rand = new Random();
int random = rand.nextInt(16);
int NumStones=15+random;
PlayNim(NumStones);
return(1);
}
}

I see several issues with your Java code.
UserMove() in the Java code sets numstones=0 upon entry, whereas UserMove() in the C++ code does not do that. You don't want UserMove() to zero out the input before modifying it.
The while loop of UserMove() in the Java code does not match the while loop of UserMove() in the C++ code. You are not checking the user's input to make sure it is between 1..3, inclusive.
The do..while loop of ComputerMove() in the Java code does not match the do..while loop of ComputerMove() in the C++ code. The C++ code generates a new random number on each loop iteration, but the Java code generates one random number before the loop and then reuses it on each iteration.
But, most importantly, in the C++ code, UserMove() and ComputerMove() (and presumably PlayNim(), too) take their int parameters by reference, which allows any modifications made by the functions to their parameter values to be reflected back to variables in the callers. However, in the Java code, the same functions take their int parameters by value instead, and as such any modifications made to their parameter values are not reflected back to the callers.
Java does not support pass-by-reference semantics, so you will have to re-write the logic a little bit. There are several ways you can do that.
You can wrap the int inside of a mutable class wrapper, such as Java's AtomicInteger or Apache's MutableInt, and pass around an instance of that class, eg:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
import org.apache.commons.lang3.mutable;
public class Nim {
public static void Usermove(MutableInt numstones) {
Scanner input = new Scanner(System.in);
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones)) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
numstones.subtract(takestones);
}
public static void Computermove(MutableInt numstones) {
Random rand = new Random();
int takestones;
do {
takestones = 1 + rand.nextInt(3);
}
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones));
System.out.println("The computer takes " + Integer.toString(takestones) + ".");
numstones.subtract(takestones);
}
public static void PlayNim(MutableInt numstones) {
while (true) {
if (numstones.intValue() > 0) {
System.out.println("There are " + numstones.toString() + " stones");
Usermove(numstones);
}
else {
System.out.print("You Win!");
break;
}
if (numstones.intValue() > 0) {
System.out.println("There are " + numstones.toString() + " stones");
Computermove(numstones);
break;
}
}
}
public static void main(String[] args) {
Random rand = new Random();
MutableInt NumStones = new MutableInt(15 + rand.nextInt(16));
PlayNim(NumStones);
}
}
You can use return values instead of pass-by-reference parameters, eg:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
public class Nim {
public static int Usermove(int numstones) {
Scanner input = new Scanner(System.in);
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones)) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
return numstones - takestones;
}
public static int Computermove(int numstones) {
Random rand = new Random();
int takestones;
do {
takestones = 1 + rand.nextInt(3);
}
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones));
System.out.println("The computer takes " + takestones + ".");
return numstones - takestones;
}
public static int PlayNim(int numstones) {
while (true) {
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
numstones = Usermove(numstones);
}
else {
System.out.print("You Win!");
break;
}
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
numstones = Computermove(numstones);
break;
}
}
}
public static void main(String[] args) {
Random rand = new Random();
int NumStones = 15 + rand.nextInt(16);
PlayNim(NumStones);
}
}
You can move the int into the Nim class itself, and remove the static from the class methods, eg:
import java.lang.Math;
import java.util.Scanner;
import java.util.Random;
public class Nim {
int numstones;
Random rand;
public Nim() {
rand = new Random();
numstones = 15 + rand.nextInt(16);
}
public void Usermove() {
Scanner input = new Scanner(System.in);
int takestones;
System.out.println("How many would you like: ");
takestones = input.nextInt();
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones)) {
System.out.println("Value must be between 1 and 3");
System.out.println("How many would you like? ");
takestones = input.nextInt();
}
numstones -= takestones;
}
public void Computermove() {
int takestones;
do {
takestones = 1 + rand.nextInt(3);
}
while ((TakeStones < 1) || (TakeStones > 3) || (TakeStones > NumStones));
System.out.println("The computer takes " + Integer.toString(takestones) + ".");
numstones -= takestones;
}
public void PlayNim() {
while (true) {
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
Usermove();
}
else {
System.out.print("You Win!");
break;
}
if (numstones > 0) {
System.out.println("There are " + Integer.toString(numstones) + " stones");
Computermove();
break;
}
}
}
public static void main(String[] args) {
Nim game = new Nim();
game.PlayNim();
}
}

Related

How to add a roll dice function and a check guess function?

How to add a roll dice method and a check guess method?
My code:
package oui;
import java.util.Scanner;
public class dicecalc {
public static void main(String args[]) {
Scanner kb = new Scanner(System.in);
int numGuess;
System.out.println("Enter the number the numer the dice will roll: ");
numGuess = kb.nextInt();
int dice1=(int)(Math.random()*6+1);
int dice2=(int)(Math.random()*6+1);
int sum = dice1 + dice2;
System.out.println("Roll: total = " + sum);
{
if (sum != numGuess) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
}
I need to have this assignment resubmitted because I forgot those things but I don't know how to add it. Please help. I already have tried for days.
Here's one possible basic layout. Replace the ??? with some code!
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("Enter the number the numer the dice will roll: ");
int numGuess = kb.nextInt();
int sum = sumOfTwoDiceRolls();
System.out.println("Roll: total = " + sum);
{
if (!checkGuess(numGuess, sum)) {
System.out.println("Sorry with a " + sum + " You LOSE :(");
} else {
System.out.println("Woah!!! With a " + sum + " You WIN!!!!!!!");
}
}
}
public static int sumOfTwoDiceRolls() {
return ??? ;
}
public static int singleDiceRoll() {
// Math.random() * (max - min + 1) + min
return (int)(Math.random() * (6 - 1 + 1) + 1);
}
public static boolean checkGuess(int guess, int numberToGuess) {
return ??? ;
}
}

Print return value in Java

I'm currently making a high-low guessing game in Java. I believe I have two issues hindering the game from functioning properly.
Firstly, I have a while-statement inside the playGame method that doesn't change as it is now, and I have trouble understanding how I can make it change if the correct guess is made. As I understand it I can't change the value of boolean bool = true; from the giveResponse method, it has to be done from the same method playGame? If there a better way of doing this than using a while-statement?
Secondly, when the correct guess is made and the playGame method return the value of parameter guessCount to the main method it should then be printed out. The instruction I have for this game says it should be printed in the main method after the return have been made.
import java.io.Reader;
import java.util.Scanner;
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r"
+ "1. 1-10 \r"
+ "2. 1-100 \r"
+ "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n==1) {
playGame(10);
}
else if (n==2) {
playGame(100);
}
else if (n==3) {
playGame(1000);
}
else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int)(Math.random() * maxNumber) +1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
giveResponse(answer, guess);
}
return guessCount;
}
public static void giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
}
else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
}
else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
}
}
}
I hope the questions are clear and specific enough. Any pointers in the right direction is appreciated.
You could have the giveResponse method return a boolean
static boolean giveResponse(...)
and put return false; inside the if (guess == answer){ case, and return true at the end of the method. Instead of calling giveResponse as a void method, use bool = giveResponse(answer,guess).
And for the second question, add a int numberOfGuesses in the main method before the if statement, and call playGame with numberOfGuesses = playGame(...), then System.out.println("You guessed " + numberOfGuesses + " times."); after the if-statements.
I think this is what you're trying to do.
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r"
+ "1. 1-10 \r"
+ "2. 1-100 \r"
+ "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n==1) {
System.out.println("Guess count: "+playGame(10));
}
else if (n==2) {
System.out.println("Guess count: "+playGame(100));
}
else if (n==3) {
System.out.println("Guess count: "+playGame(1000));
}
else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int)(Math.random() * maxNumber) +1;
int guessCount = 0;
boolean bool = false;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (! bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
bool = giveResponse(answer, guess);
}
return guessCount;
}
public static boolean giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
return true;
}
else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
return false;
}
else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
return false;
}
}
}
Here is your complete solution
import java.io.Reader;
import java.util.Scanner;
public class HereSOl {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r" + "1. 1-10 \r" + "2. 1-100 \r" + "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n == 1) {
System.out.println("Guesstcount : " + playGame(10));
} else if (n == 2) {
System.out.println("Guesstcount : " + playGame(100));
} else if (n == 3) {
System.out.println("Guesstcount : " + playGame(1000));
} else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int) (Math.random() * maxNumber) + 1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
boolean ans =giveResponse(answer, guess);
if (ans == true) {
break;
}
}
return guessCount;
}
public static boolean giveResponse(int answer, int guess) {
if (guess == answer) {
System.out.println("Your guess is correct!\r");
return true;
} else if (guess > answer) {
System.out.println("Your guess is too high, guess again:\r");
return false;
} else if (guess < answer) {
System.out.println("Your guess is too low, guess again:\r");
return false;
}
return false;
}
}
I think you should use enum, Here is my Solution.
import java.util.Scanner;
public class HiLo2 {
public static void main(String[] args) {
System.out.println("Decide a level of difficulty\r" + "1. 1-10 \r" + "2. 1-100 \r" + "3. 1-1000");
Scanner reader = new Scanner(System.in);
int n = reader.nextInt();
if (n == 1) {
playGame(10);
} else if (n == 2) {
playGame(100);
} else if (n == 3) {
playGame(1000);
} else {
System.out.println("This level of difficulty doesn't exist. Please try one between 1 and 3.");
}
}
public static int playGame(int maxNumber) {
int answer = (int) (Math.random() * maxNumber) + 1;
int guessCount = 0;
boolean bool = true;
Scanner reader = new Scanner(System.in);
System.out.println("Guess a number between 1 and " + maxNumber);
while (bool) {
int guess = reader.nextInt();
guessCount = guessCount + 1;
Answer ans = giveResponse(answer, guess);
System.out.println(ans.getMessage());
if (ans == Answer.CORRECT) {
bool = false;
System.out.println("You took " + guessCount + " guess to get right number.");
}
}
return guessCount;
}
public static Answer giveResponse(int answer, int guess) {
if (guess == answer) {
return Answer.CORRECT;
} else if (guess > answer) {
return Answer.HIGH;
} else {
return Answer.LOW;
}
}
private enum Answer {
CORRECT("Your guess is correct!\r"), HIGH("Your guess is too high, guess again:\r"), LOW("Your guess is too low, guess again:\r");
private String message;
public String getMessage() {
return this.message;
}
Answer(String message) {
this.message = message;
}
}
}

Java classes and calling variables in other classes

I'm still fairly new in java programming and I've gotten some aspects down but the classes within Java are by far giving me the most trouble. What I'm trying to do is make a random number game where the player has to pick a number 1 through 10 and if it's wrong then try again and have the program record how many times they guessed (but not add to the number of guess when a number has been picked previously or if the number that was picked is outside the specified range) I have already worked out the logic code and was trying to make a class specifically for just the logic and a class that is specifically just for the I/O interface. But I'm having one heck of a time. Any input or tips will be very appreciated and I will provide the code that I already have below:
This is the Logic class where I want it to handle all the logic
package guessapp;
import java.util.HashSet;
import java.util.Scanner;
public class GuessLogic {
public static int Logic() {
HashSet<Integer> hs = new HashSet<>();
int GuessLogic = (int) (Math.random() * 10 + 1);
Scanner keyboard = new Scanner(System.in);
int A;
int guess;
int NumGuess = 1;
do {
guess = keyboard.nextInt();
if (hs.contains(guess)) {
A = 1;
return A;
}
if (guess < 0 || guess > 10) {
A = 2;
return A;
}
if (guess == GuessLogic) {
A = 3;
return A; // this will stop the loop
} else if (guess < GuessLogic) {
NumGuess++;
A = 4;
return A;
} else if (guess > GuessLogic) {
NumGuess++;
A = 5;
return A;
}
hs.add(guess);
} while (true);
}
public static int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}
And this is the class I want to handle all I/O interface
import java.util.HashSet;
import java.util.Scanner;
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
r = GuessLogic.Logic();
w = GuessLogic.getGuess();
int NumGuess;
NumGuess = 2;
System.out.print("Enter a guess: ");
if (r == 1) {
System.out.println("You have already entered this number");
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + NumGuess);
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + NumGuess);
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + NumGuess);
}
}
}
Below is the modified codes. There are some general ideas:
GuessLogic should be used as an instance rather than a static class. Because you need GuessLogic to save the operations and the target number.
The while loop should be coded in main. Because GuessLogic is responsible for logic only.
The elements is Set is unique, so there is no need to count how many different number by yourself.
GuessApp:
public class GuessApp {
public static void main(String[] args) {
int r, w, y;
GuessLogic guessLogic = new GuessLogic();
while(true){
System.out.print("Enter a guess: ");
w = guessLogic.getGuess();
r = guessLogic.Logic();
if (r == 1) {
System.out.println("You have already entered this number");
continue;
}
if (r == 2) {
System.out.println("Your guess is out of the specified range. Please try again.");
continue;
}
System.out.println("Your guess is " + w);
if (r == 3) {
System.out.println("You got it right!! Congrats!! Total Number of Guesses: " + guessLogic.getNumber());
break;
} else if (r == 4) {
System.out.println("You are wrong!!! Hint: Guess Higher, Guess number: " + guessLogic.getNumber());
} else if (r == 5) {
System.out.println("You are wrong!!! Hint: Guess Lower, Guess number: " + guessLogic.getNumber());
}
}
}
}
GuessLogic:
public class GuessLogic {
HashSet<Integer> hs = new HashSet<>();
int number = (int) (Math.random() * 10 + 1);
public int getNumber(){
return hs.size();
}
public int Logic(int guess) {
if (hs.contains(guess)) {
return 1;
}
if (guess < 0 || guess > 10) {
return 2;
}
if (guess == number) {
return 3; // this will stop the loop
} else if (guess < number) {
// just add to the set. The set will guarantee that there is no repetitive item.
hs.add(guess);
return 4;
} else if (guess > number) {
hs.add(guess);
return 5;
}
return -1;
}
public int getGuess() {
int guess;
Scanner keyboard = new Scanner(System.in);
guess = keyboard.nextInt();
return guess;
}
}

Maths Game - returning points in methods

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.

User input on same line?

I'm new to Java so forgive me. I'm writing a small little Guessing Game program.
import java.util.Scanner;
public class GuessingGame {
static Scanner userInput = new Scanner(System.in);
public static void main(String[] args) {
int menuOption;
// Main Screen //
System.out.println("Guessing Game");
System.out.println("---------------------");
System.out.println("1.) Play Game");
System.out.println("2). Exit");
System.out.println();
while (true) {
System.out.print("Please select a menu option: ");
menuOption = userInput.nextInt();
if (menuOption == 2) {
System.out.println("Exiting the game. Thanks for playing!");
break;
} else if (menuOption == 1) {
System.out.println("Let's start the game!");
getRandomRange();
} else {
System.out.println("Sorry, that's not a valid option. Please try again.");
continue;
}
}
}
/**
* Determine the range of numbers to work with
*/
public static void getRandomRange() {
int min;
int max;
System.out.print("Choose a minimum number: ");
min = userInput.nextInt();
System.out.print("Choose a maximum value: ");
max = userInput.nextInt();
getRandomNumber(min, max);
}
public static void getRandomNumber(int min, int max) {
int randomNumber = (int) (Math.random() * (max - min + 1)) + min;
getAGuess(min, max, randomNumber);
}
public static void getAGuess(int min, int max, int randomNumber) {
int guess;
while (true) {
System.out.print("Guess a number between " + min + " and " + (max) + ": ");
guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
}
}
}
}
When I prompt the user to guess a number and the number is incorrect, I want to be able to flush immediately flush the input stream and enter another guess on the same line.
For example:
Guess a number between 0 and 5: I enter my guesses here on this one line only.
I could take the print out of the loop but in that case, if I enter an inccorect number, the cursor jumps to the next line.
Hope this makes sense. Thanks!
If your goal is only to clear the console, then you could do:
Runtime.getRuntime().exec("cls");
Or if you are on Linux or OS X:
Runtime.getRuntime().exec("clear");
Now if you add previous line that you wanted to keep, you will need to keep then in an Array and reprint after each clear.
This won't work in IDE's.
If you want a more system-independent way, there is a library named JLine (GitHub), which is designed for a better console usage. It actually contains a method clearScreen.
You could also do:
System.out.print("\033[H\033[2J");
This will clear the screen and return the cursor to the first row.
A quick and dirty solution...
public class Main {
public static final void main(String[] data) {
Scanner userInput = new Scanner(System.in);
int min = 0;
int max = 10;
int randomNumber = (int) ((Math.random() * max) + (min + 1));
while (true) {
System.out.print("Guess a number between " + min + " and " + max + ": ");
int guess = userInput.nextInt();
if (guess == randomNumber) {
System.out.println("Correct! The random number is: " + randomNumber);
break;
} else {
for (int i = 0 ; i < 25; i++) {
System.out.println();
}
}
}
}
}

Categories