Globalize an input variable in Java - java

I am trying to make a lottery game in Java and it uses method calls instead of while loops for looping purposes. However, I cannot get an input variable( such as int bet = input.nextInt()) to be recognized as a variable for other methods. I do not know how to globalize "bet" so it can be used by all the methods instead of just in the method it is a part of. Here is part of my code below, including just the one method called "play()"
public static void play()
{
System.out.println("\nPlay? Yes = 1 No = 2 ");
Scanner input = new Scanner(System.in);
int play = input.nextInt();
if(play == 1)
{
System.out.print("Current balance is " + account);
System.out.print("\nPlace your bet: ");
int bet = input.nextInt();
if((bet <= account) && (bet > 0)){
lottery();
}
else if((bet < 0) || (bet > account)){
play();
}
}
else if(play == 2){
System.out.println("Final balance is " + account);
System.exit(0);
}
else{
System.out.println("Invalid input!");
play();
}
}

Simplest answer is to declare play and bet as static class variables.
public class Game {
private static int play = 0;
private static int bet = 0;
public static void play() {
System.out.println("\nPlay? Yes = 1 No = 2 ");
Scanner input = new Scanner(System.in);
play = input.nextInt();
if(play == 1) {
System.out.print("Current balance is " + account);
System.out.print("\nPlace your bet: ");
bet = input.nextInt();
if((bet <= account) && (bet > 0)) {
lottery();
}
else if((bet < 0) || (bet > account)){
play();
}
}
else if(play == 2){
System.out.println("Final balance is " + account);
System.exit(0);
}
else{
System.out.println("Invalid input!");
play();
}
}

Define bet outside of the play() method.

If you define bet as a field in the class like :
public class Lottery {
private int bet;
public void lottery() {
...
}
public void play() {
...
}
public static void main(String[] args) {
Lottery lottery = new Lottery();
lottery.play();
}
}
then bet is available in all methods in the class, but not outside.
It is not necessary to make play public, so this can stay nicely inside the scope of the play method. It is considered good practice to give variables no more visibility than strictly needed.
Most people would in this case not make bet a field, but pass it as a parameter to the lottery method. In this case the visibiltiy can even be further restricted to only the play and lottery methods.
A final note is you use of function calls to loop. Since java does not support tail-call-optimisation (and it would not apply here in any case) you are going to fill up the stack and finally die of a stack overflow if you play long enough.

Pass it between methods as a parameter. (Defining it as public is not recommended.) Or, if this is a class, you can make it a member variable (property).

Related

how to run the same result of a if statement in a method in a new method

I am new to java and I'm working on a temp conversion tool
the whatToDo method takes a users input and runs it though if and else if statements and will convert one unit to another depending on what the user imputed
then the whatsNext method runs once the conversion method was executed it will ask the user if they want to convert something else convert the same thing or exit the program
I want it so when the whatsNext method is ran the and the user inputs "1" it will run the same conversion method that was just run from the whatToDo method
I have tried to take the WhatToConvert int from the whatToDo method to make a new if statement in the whatsNext method but I can not because its in a method and java cannot find it
Thank you in advanced if you do help :)
import java.util.Scanner;
public class App {
public static void conversions() {
System.out.println("What two temperatures would you like to convert?");
System.out.println("[1]:celsius to fahrenheit");
System.out.println("[2]:fahrenheit to celsius");
System.out.println("[3]:celsius to kelvin");
System.out.println("[4]:fahrenheit to kelvin");
System.out.println("[5]:kelvin to celsius");
System.out.println("[6]:kelvin to fahrenheit");
}
public static void options() {
System.out.println("what would you like to do now?");
System.out.println("[1]:convert the same thing");
System.out.println("[2]:convert something else");
System.out.println("[3]:exit");
}
public static void whatToDo() {
Scanner in = new Scanner(System.in);
conversions();
int whatToConvert = in.nextInt();
if (whatToConvert == 1) {
cF();
} else if (whatToConvert == 2) {
fC();
} else if (whatToConvert == 3) {
cK();
} else if (whatToConvert == 4) {
fK();
} else if (whatToConvert == 5) {
kC();
} else if (whatToConvert == 6) {
kF();
}
else {
System.out.flush();
System.out.println(whatToConvert + ": is a unknown command pls try again:");
whatToDo();
}
}
// runs once conversion method was run
public static void whatNext() {
var in = new Scanner(System.in);
options();
int choice = in.nextInt();
if (choice == 1) {
System.out.println("needs to be added");
cF();
} else if (choice == 2) {
whatToDo();
} else if (choice == 3) {
System.exit(1);
}
}
// conversion methods
public static void cF() {
Scanner in = new Scanner(System.in);
System.out.println("please enter the temperature in celsius:");
double cToF = in.nextDouble();
System.out.println(cToF + "°C is about " + (cToF * 1.8 + 32) + "°F");
}
public static void fC() {
Scanner in = new Scanner(System.in);
System.out.println("please enter the temperature in fahrenheit:");
double fToC = in.nextDouble();
System.out.println(fToC + "°F is about " + (fToC - 32) / 1.8 + "°C");
}
public static void cK() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in celsius:");
double cToK = in.nextDouble();
System.out.println(cToK + "°C is about " + (cToK + 273.15) + "°K");
}
public static void fK() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in fahrenheit:");
double fToK = in.nextDouble();
System.out.println(fToK + "°F is about " + ((fToK - 32)*5/9 + 273.15) + "°K");
}
public static void kC() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in kelvin:");
double kToC = in.nextDouble();
System.out.println(kToC + "°K is about " + (kToC - 273.15) + "°C");
}
public static void kF() {
Scanner in = new Scanner(System.in);
System.out.println("enter the temperature in kelvin:");
double kToF = in.nextDouble();
System.out.println(kToF + "°K is about " + ((kToF - 273.15)* 9/5 + 32) + "°C");
}
public static void main(String[] args) throws Exception {
while (true) {
whatToDo();
whatNext();
}
}
}
I could think of two easy ways you can achieve this:
The variable whatToConvert is declared inside a variable. Hence its scope (or simply say its access) is only inside that method - unless you specifically pass it as argument to some other method.You can also have variables with global scope - meaning variables declared at class level and not inside a method. Such variables are accessible to all the methods of that class.You can read more on "scope of variables in java".
What you can do here is - declare whatToConvert variable as static at class level instead of inside whatToDo() method.
public class App {
static int whatToConvert = 0;
//all other code
}
Method whatNext() can then have access to this variable.
You know that whatNext() always runs after whatToDo(). In such case, you can return the value of 'whatToConvert' from whatToDo() and pass
that value as method argument to whatNext()
In either case you should extract the if-else code to a new method to add re-usability for method whatNext()
New method can have method signature something like:
public static void decideOperation(int choice) {
//If-else blocks or switch case
}
When you declare a variable in a method, it will be local, so it will be instantiated and in the method and removed once the method is finished. In order for a variable to be read by all methods you should declare it as a global variable, in this way:
public class App {
private static int whatToConvert;
...
public static void whatToDo() {
Scanner in = new Scanner(System.in);
conversions();
whatToConvert = in.nextInt();
...
}
Now you can use whatToConvert in other methods

Java Multiplication Expression Generator [closed]

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

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

Set and get with arguments in Java

I new to java, still trying to get down arguments and passing info. I am writing a blood pressure program for school and have some issue passing info from one class to another.
I have a fully functioning system to take in the user info in one class and have to set up another to check if the average is above or below range. Now, the range is easy, but the passing of info is another thing.
Here is part of my program (in the class PressureInput) and where my issues start:
public void setSystolic(int sys)
{
sys = sysAvrg;
}
So, assuming the avrgSys has a number (it does), I then want to pass the info to the other class (BPChecker).
I don't feel like I'm doing this right, or at least, not in such a way as to facilitate passing the 'int' of sysAvrg from the class its in into another class (BPChecker).
I'm not sure whether to use a getSystolic since I'm not sure what the return would be.
I can't just initialize sys in the other class (BPChecker) without giving sys a value (which defeats the purpose), but it keeps telling me to.
In the end, I need to move the number of avrgSys into BPChecker without rewriting the whole program. So far, I keep getting a lot of 0s or errors...
Any help is appreciated, though my newness may have more complicated explanations go over my head (sorry to say).
So, here's the code i wrote. the ONLY thing I'm worried about is the very last part, the 'getSystolic' and its return. I need to send the info to another part of the program not in main or in this PressueInput (its BPChecker btw) and just banging my head against the problem.
Thank you for the input:
` import java.util.Scanner;
public class PressureInput
{
private int sysInput;
private int diaInput;
private int sysAvrg;
private int diaAvrg;
public PressureInput()
{
sysInput = 0;
diaInput = 0;
sysAvrg = 0;
diaAvrg = 0;
}
public void setSysPressure()
{
sysInput = 0;
while(sysInput <= 0 || sysInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
sysInput= cin.nextInt();
System.out.println("You have entered " + sysInput + "\n");
if(sysInput <=0 || sysInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
sysAvrg += sysInput;
}
public int getSysPressure()
{
return sysInput;
}
public void setDiaPressure()
{
diaInput = 0;
while(diaInput <= 0 || diaInput >= 320)
{
Scanner cin = new Scanner(System.in);
System.out.println("Please enter a systolic reading> ");
diaInput= cin.nextInt();
System.out.println("You have entered " + diaInput + "\n");
if(diaInput <=0 || diaInput >= 320)
{
System.out.println("You're either dead or entered"
+ " an error. Try again." + "\n");
}
}
diaAvrg += diaAvrg;
}
public int getDiaPressure()
{
return diaInput;
}
public void sysAvrgRead()
{
sysAvrg = sysAvrg / 3;
System.out.println("\n" + "The systolic averge is " + sysAvrg);
}
public void diaAvrgRead()
{
diaAvrg = diaAvrg / 3;
System.out.println("The diastolic averge is " + diaAvrg + "\n");
}
public void setSystolic(int sys)
{
sysAvrg = sys;
}
public int getSystolic()
{
return sys;
}
} `
In Object-oriented programming, you can create an instance of an object in any class you want. In order to access class variables from other classes, you can use accessor methods.
i.e.
public class PressureInput {
private static int sysAvrg;
public PressureInput(int sysAvrg){
this.sysAvrg = sysAvrg;
}
public void setSystolic(int sys){
this.sysAvrg = sys;
}
public int getSystolic() {
return this.sysAvrg;
}
}
You have a variable called sys so if you want to set it with the average create a setter Method:
public void setSystAve(float sysAvrgParameter){
sysAvrg = sysAvrgParameter;
}
if you want to get the sysAvrg create a getter Method:
public float getSystAve(){
return sysAvrgParameter;
}
now somewhere in your code:
sys = yourObject.getSystAve();

Return value executing a method?

import java.util.*;
public class Guess {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
Random r = new Random();
intro();
int numGames = 0;
int numGuesses = game(console, r);
int max = max(numGuesses);
String again = "y";
do {
game(console, r);
System.out.println("Do you want to play again?");
again = console.next();
System.out.println();
numGames++;
} while (again.startsWith("y") || again.startsWith("Y"));
stats(numGames, numGuesses, max);
}
public static void intro() {...}
public static int game(Scanner console, Random r) {
System.out.println("I'm thinking of a number between 1 and 100...");
int answer = r.nextInt(100) + 1;
System.out.println("answer = " + answer);
int guess = -1;
int numGuesses = 0;
while (answer != guess) {
System.out.print("Your guess? ");
guess = console.nextInt();
numGuesses++;
if (guess > answer) {
System.out.println("It's lower.");
} else if (guess < answer) {
System.out.println("It's higher.");
} else {
System.out.println("You got it right in " + numGuesses + " guesses");
}
max(numGuesses);
}
return numGuesses;
}
public static int max(int numGuesses) {
int max = numGuesses;
if (max > numGuesses) {
max = numGuesses;
}
return max;
}
public static void stats(int numGames, int numGuesses, int max) {
System.out.println("Overall results:");
System.out.println(" total games = " + numGames);
System.out.println(" total guesses = " + numGuesses);
System.out.println(" guesses/game = " + numGuesses / numGames / 1.0);
System.out.println(" best game = " + max);
}
}
So this is a small part of my program and the problem I'm having is that my initial int for numGuesses (int numGuesses = game(console, r);) is executing the game method shown below.
All I want from the game method is the return value of numGuesses so that I can forward the value into a different method called stats(numGames, numGuesses, max); . How do I make it so that the initial value isn't executing the method and only the do/while loop is?
Is the way I produce a return statement wrong? Also, my return values aren't saving in my stats method so when I run it, I get the wrong answers.
Then you should put the code that's responsible of generating numGuesses in another method that you will use on both main and game, for example:
public static int game(Scanner console, Random r) {
int numGuesses = getNumberOfGuesses(..);
//continue implementation here
}
public static void main(String[] args) {
int numGuesses = getNumberOfGuesses(..);
//use value
}
You should get familiar with class variables. At the top of your class, you can declare a variable and also give it a value. That is what you should do with numGuesses if you want to access it from different methods in your class. Here is the Foobar example:
class Foo {
private int bar = 0;
private void foobar(int arg) {...}
}
You just need to watch out that you don't do int numGuesses somewehere in a method as that would create a second local variable. The class variable can be accessed via just the name.
Next, you want to keep track of the total games played and the total guesses. You can guess now (hahaha), that you need to use class variables as well. If you need to keep track of the total guesses even when the program is restarted you will need to store these values in a file, but that will be for another time.
Finally, two more little things.
1.) The method max. I do not know what max should do, but at the moment it is just returning the value passed to it. Also the if statement will never execute (x can't be higher than x).
2.) You should maybe consider not making everything static. It obviously works that way, but that is not, what is called object-oriented programming.

Categories

Resources