Java classes and calling variables in other classes - java

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;
}
}

Related

How to display error message instead of java exception?

I am trying to make a Guessing Game for a Java assignment, I have everything I need except exception handling, you see I'm trying to make it display an error message instead of displaying Exception in thread "main" java.util.InputMismatchException when someone tries to enter a numerical number in alphabetical form. The code I have is followed.
(I know I need a try and catch but I don't know what to put exactly.)
package guessNumber;
import java.util.Scanner;
public class GuessNumberApp {
public static void main(String[] args) {
final int LIMIT = 10;
System.out.println("Guess the number!");
System.out.println("I'm thinking of a number from 1 to " + LIMIT);
System.out.println();
// get a random number between 1 and the limit
double d = Math.random() * LIMIT; // d is >= 0.0 and < limit
int number = (int) d; // convert double to int
number++; // int is >= 1 and <= limit
// prepare to read input from the user
Scanner sc = new Scanner(System.in);
int count = 1;
while (true) {
int guess = sc.nextInt();
System.out.println("You guessed: " + guess);
if (guess < 1 || guess > LIMIT) {
System.out.println("Your Guess is Invalid.");
continue;
}
if (guess < number) {
System.out.println("Too Low.");
} else if (guess > number) {
System.out.println("Too High.");
} else {
System.out.println("You guessed it in " + count + " tries.\n");
break;
}
count++;
}
System.out.println("Bye!");
}
}
try something like that:
try {
int guess = sc.nextInt();
} catch(InputMismatchException e) {
System.out.println("some nice error message");
continue;
}
This would replace
int guess = sc.nextInt();

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;
}
}
}

I need a Java Scanner 'reset' on invalid character fix

I am a new human learning to code!
I had a problem with my Scanner, which is that I need it to 'reset' on an invalid character.
My code:
public class Lemonade {
static int m = 150;
private static Scanner scan;
public static void main(String[] args) {
int day = 1;
for(int gameover = m; gameover > 0; day++) {
int Random = (int) (Math.random() * 100);
if(Random <= 25) {
System.out.println("Great Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 50) {
System.out.println("Good Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 75) {
System.out.println("Bad Chance!");
System.out.println("--------------------------------");
}
else if(Random <= 100) {
System.out.println("Awful Chance!");
System.out.println("--------------------------------");
}
int count = 0;
int none = 0;
scan = new Scanner(System.in);
System.out.println("Enter a number between 0 and " + m + "!");
count = scan.nextInt();
if(count >= none && count <= m) {
System.out.println("You entered " + count + "!");
System.out.println("--------------------------------");
day = day + 1;
m = m - count;
System.out.println("Day " + day);
}
else {
System.out.println("Enter a number between 0 and " + m + ".");
count = scan.nextInt();
}
}
}
}
Now is my question how to get this to 'reset' on an invalid character like 'f', as Scanner only accepts numbers.
Thanks for the help!
If I understand you correctly then this is something you're looking for,
InputMismatchException will thrown if user enters invaild characters instead of int. You may use looping until the user enters an integer
import java.util.Scanner;
import java.util.InputMismatchException;
class Example
{
public static void main(String args[])
{
boolean isProcessed = false;
Scanner input = new Scanner(System.in);
int value = 0;
while(!isProcessed)
{
try
{
value = input.nextInt();
//example we will now check for the range 0 - 150
if(value < 0 || value > 150) {
System.out.println("The value entered is either greater than 150 or may be lesser than 0");
}
else isProcessed = true; // If everything is ok, Then stop the loop
}
catch(InputMismatchException e)
{
System.out.print(e);
input.next();
}
}
}
}
If this is not you're looking for please let me know!

Adding a loop to my game

I have a game that's running perfectly. I want to put a line of code that asks the player if they want to play again at the end of the game. I would also like to keep a score system for every player and computer win.
I'm having trouble with the input = Integer.parseInt(sc.nextInt()); line
import java.util.Scanner;
public class Sticks {
public static boolean whoStart(String choice) {
int ran = (int) (Math.random() * 2 + 1);
String ht = "";
switch (ran) {
case 1:
ht = "head";
break;
case 2:
ht = "tails";
}
if (ht.equals(choice.toLowerCase())) {
System.out.println("you start first");
return true;
} else {
System.out.println("computer starts first");
return false;
}
}
public static int playerTurn(int numberOfSticks) {
System.out.println(" \nthere are " + numberOfSticks + " sticks ");
System.out.println("\nhow many sticks do you wanna take? 1 or 2?");
Scanner in = new Scanner(System.in);
int sticksToTake = in.nextInt();
while ((sticksToTake != 1) && (sticksToTake != 2)) {
System.out.println("\nyou can only take 1 or 2 sticks");
System.out.println("\nhow many sticks do you wanna take?");
sticksToTake = in.nextInt();
}
numberOfSticks -= sticksToTake;
return numberOfSticks;
}
public static int computerTurn(int numberOfSticks) {
int sticksToTake;
System.out.println("\nthere are " + numberOfSticks + " sticks ");
if ((numberOfSticks - 2) % 3 == 0 || (numberOfSticks - 2 == 0)) {
sticksToTake = 1;
numberOfSticks -= sticksToTake;
} else {
sticksToTake = 2;
numberOfSticks -= sticksToTake;
}
System.out.println("\ncomputer took " + sticksToTake + " stick ");
return numberOfSticks;
}
public static boolean checkWinner(int turn, int numberOfSticks) {
int score = 0;
int input;
int B = 1;
int Y=5, N=10;
if ((turn == 1) && (numberOfSticks <= 0)) {
System.out.println("player lost");
return true;
}
if ((turn == 2) && (numberOfSticks <= 0)) {
System.out.println("player won");
score++;
return true;
}
System.out.println("Your score is "+ score);
System.out.println("Do you want to play again? Press (5) for Yes / (10) for No");
// ----- This line -----
input = Integer.parseInt(sc.nextInt());
if (input == Y) {
B = 1;
System.out.println("Rock, Paper, Scissors");
} else if (input == N) {
System.exit(0);
System.out.println("Have A Good Day!");
}
}
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
System.out.println("choose head or tails to see who starts first");
String choice = in.next();
if (whoStart(choice) == true) {
do {
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
} else {
do {
turn = 2;
numberOfSticks = computerTurn(numberOfSticks);
if (checkWinner(turn, numberOfSticks) == true) {
break;
};
turn = 1;
numberOfSticks = playerTurn(numberOfSticks);
checkWinner(turn, numberOfSticks);
} while (numberOfSticks > 0);
}
}
}
The title of your question almost answered you what you need to add: a loop!
I suggest you to refactor your function main and extract all your game logic from it to be stored within a dedicated function for the sake of the readability. Let's call it startGame().
Your main is going to become shorter and can represent a good location to introduce this loop, such as:
public static void main(String[] a) {
boolean isPlaying = true;
Scanner in = new Scanner(System.in);
while(isPlaying) {
startGame();
// Your message to continue or stop the game
if(in.next().equalsIgnoreCase("No")) {
isPlaying = false;
}
}
}
I recommend you to use a boolean that is checked in your while loop rather than using a break statement, as it brings a better control flow in your application.
Just put everything in a while(true) loop and use a break; if they choose no. Something like:
static int playerPoints = 0;
public static void main(String args[]) {
int turn;
int numberOfSticks = 21;
Scanner in = new Scanner(System.in);
while(true){
...
System.out.println("You have " + playerPoints + " points!")
System.out.println("Do you want to play again?");
if (!in.nextLine().toLowerCase().equals("yes")){
break;
}
}
}
Edit: ZenLulz's answer is better than this one, mainly because it encourages better programming practice. Mine works but isn't the best way to solve the issue.

Ask users if user wishes to re-run the program

I wrote the following program which displays if a number is a prime and if not a prime it display its prime factors and the next prime number.
However, I am not sure how to have the program ask the user if he/she wishes to input another number.
The user must answer either yes, no, y or n using any combination of lower and upper case letters.
If an invalid answer is given, the program must be informed that the answer was not acceptable, and then be prompted again for another answer. The program will only prompt up to three tries otherwise the program will exit.
If the answer is Yes (in any allowed form), the program must continue from step in the main function.
The program is written in prototype methods because that is what is called for.
If anyone can assist a newbie with the last part, i would greatly appreciate it.
code:
package primefactors;
import java.util.Scanner;
public class Primefactors {
//------------------three tries check method-------------------
public static int getNumberWithThreeTries(int m) {
int count = 1;
int number;
String s = "tries";
while (count <= 3) {
number = getInputNumber(m); //getScore returns -1 for invalid inputs
if (number <= 1) {
if ((3 - count) < 2) {
s = "try"; //just make sure that singular /plural form in the next statme is correct
}
if (count == 3) {
System.out.println("No more tries remaining!\n");
} else {
System.out.println((3 - count) + " " + s + " remaining! Try Again! \n");
}
count = count + 1;
} else {
return number;
}
}
return -1;
}
//-------------------boolean try again---work in progress---------------
public boolean askRunAgain() {
System.out.println("Would u like to solve more problems? ");
Scanner scanner = new Scanner(System.in);
boolean askRunAgain = scanner.nextBoolean();
return askRunAgain;
}
//----------------------------------boolen prime check method------------------
public static boolean isPrime(int m) {
for (int i = 2; i * i <= m; i++) {
if (m % i == 0) {
return false;
}
}
return true;
}
//------------------------next prime method-----------------
private static int nextPrime(int m) {
if (m % 2 == 0) {
m = m + 1;
}
for (m = m; !isPrime(m); m = m + 2)
;
return m;
}
//---------------------primefactors----------------------
public static String getPrimeFactors(int m) {
String ans = "";
for (int i = 2; i <= m; i = i + 1) {
if (m % i == 0) {
ans += i + "*";
m = (m / i);
i--;
}
}
return (ans.substring(0, ans.length() - 1));
}
//----------------------------------------------------------
public static int getInputNumber(int m) {
Scanner n = new Scanner(System.in);
int number = 0;
System.out.println("Enter an Integer greater than 1");
if (!n.hasNextInt()) {
System.out.print("That's not a number! you have ");
n.next();
return -1;
}
number = n.nextInt();
if (number <= 1) {
return -1;
}
return number;
}
//------------------------------main method ----------------------
public static void main(String[] args) {
int number;
int count = 0;
number = getNumberWithThreeTries(1);
if (number <= 1) {
System.out.println("Program Terminated");
System.exit(0);
}
if (isPrime(number)) {
System.out.println(number + ": Is a Prime Number \n\n"
+ getPrimeFactors(number) + ": Is its prime factor");
} else {
System.out.println(number + " Is not a Prime number\n\n"
+ getPrimeFactors(number) + " Are its prime factors \n\n"
+ nextPrime(number) + " Is the next Prime number\n ");
}
}
}
You need to place the getNumberWithThreeTries within a while loop, which at the end, ask if the user wants to try again. If they say yes, then your while loop should then continue to execute again, otherwise, it should exit.

Categories