So I just whipped up this quick little demo game in like 30 minutes and I was wondering 2 things:
How could I organize my code more?
Would you be willing to play a game like this?
I know that I could use classes but I'm a bit inexperienced them. I'm confused on how to get variables from specific classes. Would I need to import them into the main method class?
import java.util.Scanner;
public class mainGame
{
public static Scanner kboard = new Scanner(System.in);
public static boolean loop = true;
public static int treesInArea = 0;
public static int day = 0;
public static int wood = 0;
public static int woodCollected = 0;
public static int woodLevel = 0;
public static void main(String[] args)
{
System.out.println("__________________________________");
System.out.println(" Welcome to seul...Lets begin ");
System.out.println(" You woke up in the middle of ");
System.out.println(" a forest. Use the command walk ");
System.out.println(" in order to walk into a new area ");
System.out.println("__________________________________\n");
while(loop == true)
{
String choice = kboard.nextLine();
if(choice.equalsIgnoreCase("walk"))
{
treesInArea = (int)(Math.random() * 20);
System.out.println("__________________________________");
System.out.println("The number of trees in this area is");
System.out.println(treesInArea + " trees");
System.out.println("__________________________________\n");
day++;
System.out.println(" It is day " + day + " ");
System.out.println("__________________________________\n");
System.out.println(" Current usuable commands are : ");
System.out.println(" - Chop tree\n");
} else
if(choice.equalsIgnoreCase("choptree") || choice.equalsIgnoreCase("chop tree"))
{
if(treesInArea < 1)
{
System.out.println("There are no trees in this area.");
} else
{
woodCollected = (int)(Math.random() * 10);
treesInArea --;
wood += woodCollected;
woodLevel += (int)(Math.random() * 2);
System.out.println("__________________________________");
System.out.println(" You collected " + woodCollected + " wood");
System.out.println(" Your total wood = " + wood);
System.out.println(" Your total woodcutting level = " + woodLevel);
System.out.println("__________________________________\n");
}
}
}
}
}
You could improve your code in 4 main ways:
1 • Your code-indentation is not great, it should be a 4 space(or just press tab) indent after class name, loops, if statements etc. Example:
private methodName() {
for(int i = 0; i < 10; i++;) {
//do something
}
}
2 • It is easier to read your code when braces are right after methods/loops, and it takes less space, such as(5 lines of neat code):
if (condition = true) {
//do something
} else {
//do something else
}
Rather than(7 lines of messy code):
if (condition = true)
{
//do something
} else
{
//do something else
}
because when you have long if-else blocks, or long loops, it can become hard to read.
3 • You do not need to add spaces after a line, this does nothing. So this:
System.out.println(" It is day " + day + " ");
Can become this:
System.out.println(" It is day " + day);
4 • Lastly, the best way to organize code is by "dividing and conquering". This means make methods even if they're very short, to prevent repeat-code and save time. For example, you printed this line: System.out.println("__________________________________"); 7 times in your program. If you make a method like the one below, you can save time and space, by avoiding repeat-code, and simply call the method using printDivider(); wherever you used this line:
private static void printDivider() {
System.out.println("__________________________________");
}
Yes, I would play your game(in fact i did play your game), but you could improve it, by adding more possibilities, or different 'paths' to go down, ending in different results.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner (System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake,BMR);
//this is what you actually ate
actualCalories(actualIntake,BMR);
//gym with protein
gym (30,40,50,100, actualIntake);
}
//testing method
testingMeth(actualIntake);
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR){
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0 ){
calorieDifference = Math.abs (BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0){
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories (int actualIntake, int BMR ) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR ) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR ) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin." );
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym (int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50 ) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50 ) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth (int actualIntake) {
System.out.println(actualIntake);
}
}
//Take calories in then calculate BMR and compare, return value
So I am currently learning java, just learning and making random calorie deficit and BMR program. I created a new method called:
public static int testingMeth(actualIntake) {
System.out.println(actualIntake);
}
The issue is when i try to call the method after the gym method, it creates an error.
gym (30,40,50,100, actualIntake);
}
testingMeth(actualIntake);
If i was to delete the gym method from the main method, all my other methods has errors. I do not necessarily need a solution for this program but rather why am i receiving these errors? Just want to learn and improve! Thanks.
In other words, I can call the testingMeth before the Gym method and it works fine, but why not after the gym method? and if i get rid of the gym method, multiple errors occur amongst the other methods within the program?
If you see below code, i am able to run both method in any sequence and it's working fine as well.
You need to go through with basics of method declaration and method call.
It will help you.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
//making values easier to change and also create global variables for gym comparison
Scanner scan = new Scanner(System.in);
System.out.println("How many calories did you consume today?>> ");
int actualIntake = scan.nextInt();
System.out.println("What is your BMR?>> ");
int BMR = scan.nextInt();
scan.close();
//this method is what is expected with deficit
calorieCalculation(actualIntake, BMR);
//this is what you actually ate
testingMeth(actualIntake);
actualCalories(actualIntake, BMR);
//gym with protein
gym(30, 40, 50, 100, actualIntake);
}
//testing method
//What the user should be following
public static int calorieCalculation(int actualIntake, int BMR) {
int calorieDifference = BMR - actualIntake;
if (calorieDifference <= 0) {
calorieDifference = Math.abs(BMR - actualIntake);
System.out.println("You have went over your deficit, well done fatty = " + calorieDifference);
} else if (calorieDifference >= 0) {
System.out.println("Expected calorie deficit should be " + calorieDifference);
}
return calorieDifference;
}
//What the user actually did
public static int actualCalories(int actualIntake, int BMR) {
int deficitCalculation = actualIntake - BMR;
if (actualIntake > BMR) {
System.out.println("You fat lard stop overeating you dumbass, " + "failed deficit of over " + deficitCalculation + " Calories.");
} else if (actualIntake < BMR) {
System.out.println("Well done you created a deficit of " + deficitCalculation + " keep her going keep her movin.");
}
return deficitCalculation;
}
//How much did you burn in the gym
public static int gym(int treadMillCal, int rowingMachineCal, int weightsCal, int proteinShakeCal, int actualIntake) {
int totalGym = ((treadMillCal + rowingMachineCal + weightsCal) - proteinShakeCal);
if (totalGym >= 50) {
System.out.println("Well done you have burned more than 50 calories whilst drinking protein shake");
} else if (totalGym < 50) {
System.out.println("Whats the bloody point of drinking protein if your putting the calories back on fatty: " + totalGym + " calories is how much you lost");
}
int gymAndTotal = actualIntake - totalGym;
System.out.println("What you ate, plus minusing your workout along with the protein you consumed " + gymAndTotal);
return totalGym;
}
public static void testingMeth(int actualIntake) {
System.out.println(actualIntake);
}
}
You need to understand for every opening braces of class/method/switch-case/or condition must have closing braces.
In your case you are try to call some method after closing braces of class, so those elements are not part of your class and that's why it's throwing an error.
Where the commented section is, it says that there is a StackOverflowError - null. I am trying to get it to make random numbers to match up with an inputted value. The goal of this code is to do the following:
Accept a top number (ie 1000 in order to have a scale of (1-1000)).
Accept an input as the number for the computer to guess.
Computer randomly guesses the first number and checks to see if it is correct.
If it is not correct, it should go through a loop and randomly guess numbers, adding them to an ArrayList, until it guesses the input. It should check to see if the guess is already in the array and will generate another random number until it makes one that isn't in the list.
In the end, it will print out the amount of iterations with the count variable.
Code:
import java.util.*;
public class ArrNumGuess
{
public static Integer top, input, guess, count;
public static ArrayList <Integer> nums;
public static void main ()
{
System.out.println("Please enter the top number");
top = (new Scanner(System.in)).nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
input = Integer.parseInt(((new Scanner(System.in)).nextLine()).trim());
nums = new ArrayList<Integer>(); //use nums.contains(guess);
guess = (new Random()).nextInt(top) + 1;
nums.add(guess);
System.out.println("My first guess is " + guess);
count = 1;
if(guess != input)
{
guesser();
}
System.out.println("It took me " + count + " tries to find " + guess + " and " + input);
}
public static void guesser()
{
boolean check = false;
while(!check)
{
guess = (new Random()).nextInt(top) + 1; //Stack Overflow - null
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
else if(guess.equals(input))
{
check = true;
System.out.println("My guess was " + guess);
// nums.add(guess);
count++;
}
else
{
System.out.println("My guess was " + guess);
nums.add(guess);
count++;
}
}
}
}
In guesser() method, you're invoking itself:
if(nums.contains(guess) && !(guess.equals(input)))
{
count--;
guesser();
}
There is quite a possibility it will never end. But all that is in while loop, so why not get rid of recurrence and do this in an iterative style?
OK - a different approach to your guesser for fun. Enumerate a randomized sequence of numbers in specified range (1 to 'top') and find the guess in the list whose index is effectively the number of "attempts" and return.
(BTW - #Andronicus answer is the correct one.)
/** Pass in 'guess' to find and 'top' limit of numbers and return number of guesses. */
public static int guesser(int guess, int top) {
List<Integer> myNums;
Collections.shuffle((myNums = IntStream.rangeClosed(1, top).boxed().collect(Collectors.toList())), new Random(System.currentTimeMillis()));
return myNums.indexOf(guess);
}
You are making it more complicated than it needs to be and introducing recursion unnecessarily. The recursion is the source of your stack overflow as it gets too deep before it "guesses" correctly.
There is a lot of sloppiness in there as well. Here's a cleaned up version:
import java.util.*;
public class Guess {
public static void main(String args[]) {
System.out.println("Please enter the top number");
Scanner scanner = new Scanner(System.in);
int top = scanner.nextInt();
System.out.println("Please enter the number to guess (1 - " + top + ")");
int input = scanner.nextInt();
if (input < 1 || input > top) {
System.out.println("That's not in range. Aborting.");
return;
}
ArrayList <Integer> nums = new ArrayList<>();
Random rng = new Random(System.currentTimeMillis());
while(true) {
int guess = rng.nextInt(top) + 1;
if (!nums.contains(guess)) {
nums.add(guess);
if (nums.size() == 1) {
System.out.println("My first guess is " + guess);
} else {
System.out.println("My guess was " + guess);
}
if (guess == input) {
System.out.println("It took me " + nums.size() + " tries to find " + guess);
break;
}
}
}
}
}
I am very new to Java Programming. For example, even if I roll the same number i still lose the bet. If I roll like one and fine, I still win the bet amount. I am trying to fix that problem for hours. But can't figure it out. Please, someone, help me. Thanks in advance.
Here is my code.
public class Dice {
private int dice;
public Random number;
//default constructor
public Dice() {
number = new Random();
}
//To generate random number between 1 to 6. random starts from 0. there is no 0 on dice.
//By adding one, it will start at 1 and end at 6
}
//Method to check two dice
public boolean isequal(int dice1,int dice2) {
}
else
}
public class Playgame
{
//
}
public static void main(String[] args) {
//
}
}
{
return false;
}
}
userinput.close();
}
}
At least one problem is here (there may be others) :
if(obj1.isequal(obj1.play(), obj1.play()) == true)
{
System.out.println("You rolled a " + toString(obj1.play()) + " and a "
+ toString(obj1.play()) );
When you print the message, you are calling obj1.play() again and generating 2 new random numbers. If you need to use the value twice (once for comparison and once for printing) then you should store it in a variable.
int firstRoll = obj1.play();
int secondRoll = obj1.play();
if(obj1.isequal(firstRoll, secondRoll) == true)
{
System.out.println("You rolled a " + toString(firstRoll) + " and a "
+ toString(secondRoll) );
//...
Each call to obj1.play() return a different values.
Hence your test: obj1.isEqual(obj1.play(), obj1.play()) will mostly not return true.
no need for the dice class if it is to generate the random number and checks whether two number is equal or not. try the code below it will work
Random random = new Random();
int n1 = random.nextInt(6) + 1;
int n2 = random.nextInt(6) + 1;
System.out.println("You rolled a " + toString(n1)+ " and a " +toString(n2));
if (n1 == n2) {
double win = betmoney * 2;
System.out.println("You win $" + win);
startmoney += win;
} else {
startmoney -= betmoney;
System.out.println("You lose $" + betmoney);
System.out.println("You left only $" + startmoney);
}
problem with your code is your generating random numbers two times 1.during condition check and 2. in the sysout statement. your program is working fine only. but due to this your confusing yourself that it.
Each time you call ob1.play() method, it will give you different numbers.
in if clause:
if(obj1.isequal(obj1.play(), obj1.play()) == true)
will give you two random values that different from two random values in if block:
System.out.println("You rolled a " + toString(obj1.play()) + " and a " + toString(obj1.play()) );
So I have the game already programmed. You take turns against the computer picking 1-3 straws and the point of the game is to leave the opponent with 1 straw. That entire section works, but now I have to program the Computer to get smarter through consecutive play.
I'm not entirely sure how this is done, however. The way it was explained to me was that you have 4 "cups", which I assume are arrays. Each cup contains the moves, (1, 2, 3). During the computer's turn it randomly picks a cup and randomly chooses one of the three moves. If that move doesn't work then it removes it from the cup.
After several games the computer should become unbeatable.I'm going to keep working on this but I'm having a lot of trouble. I've been at it for a couple hours now so I'll just post the raw code without my broken parts.
EDIT: I've added the Cup class at the bottom.
import java.util.*;
public class Nim
{
public static void main(String[] args)
{
Random r = new Random();
Scanner kb = new Scanner(System.in);
String reply;
int straws, cupNum, prevCupNum, prevComputerMove,
computerMove, humanMove, gameNumber = 0, humanWin = 0;
// create an array of four cups
Cup[] cup = new Cup[4];
for (int i = 0; i < cup.length; i++)
cup[i] = new Cup();
System.out.println("Let's play Nim");
System.out.println();
do
{
gameNumber++;
straws = r.nextInt(11) + 10;
// add 1 if necessary so computer nevers starts in losing config
if (straws%4 == 1)
straws++;
System.out.println("Straws to start = " + straws);
System.out.println();
// set to -1 to indicate just starting so no previous move
prevCupNum = -1; // no prev move so init to -1
prevComputerMove = -1;
do
{
cupNum = straws%4; // get cup number
// if cup is empty, then use 1 for move
if (cup[cupNum].count() == 0) // cup empty then move = 1
computerMove = 1;
else
computerMove = cup[cupNum].select(); // get move from cup
/*MISSING CODE
If cup is cup number 1, then remove the previous move
from the previous cup unless already empty*/
System.out.println
("Computer picks up " + computerMove + " straws");
straws = straws - computerMove;
if (straws < 0)
straws = 0;
System.out.println(straws + " left");
System.out.println();
// save this move so it can be removed later if necessary
prevCupNum = cupNum;
prevComputerMove = computerMove;
if (straws == 0)
{
System.out.println("Wow. You win!");
humanWin++;
/* MISSING CODE
Remove last move computer made from cup*/
}
else // get move from human
{
System.out.println();
do
{
System.out.print("Your move: enter ");
if (straws == 1)
System.out.println("1");
else
if (straws == 2)
System.out.println("1 or 2");
else
if (straws >= 3)
System.out.println("1, 2, or 3");
humanMove = kb.nextInt();
} while
(humanMove > 3 || humanMove < 1 || straws - humanMove < 0);
straws = straws - humanMove;
System.out.println(straws + " left");
if (straws == 0)
{
System.out.println();
System.out.println("Ha, ha. You lose!");
}
}
} while (straws > 0);
System.out.println
("Score: Human " + humanWin + " Computer " +
(gameNumber - humanWin));
if (kb.hasNextLine()) // get rid of stray newline
kb.nextLine();
System.out.println();
System.out.println("Want to play another game? Hit enter.");
System.out.println
("Or are you too CHICKEN? In that case, type in quit.");
reply = kb.nextLine();
reply = reply.trim();
if (reply.length() > 4) // require only 1st 4 to be quit
reply = reply.substring(0, 4);
}
while (!reply.toLowerCase().equals("quit"));
}
public class Cup
{
ArrayList<Integer> c = new ArrayList<Integer>();
public Cup()
{
c.add(1);
c.add(2);
c.add(3);
}
//-----------------------
public int count()
{
return c.size();
}
//-----------------------
public int select()
{
// random is a static method in Math that returns a double
// value greater than or equal to 0.0 and less than 1.0.
int index = (int)(c.size()*Math.random());
return c.get(index);
}
//-----------------------
public void remove(Integer move)
{
c.remove(move);
}
}
I'm afraid I don't understand the 'cup' strategy. There is a much simpler strategy to force the machine to learn through play, however. As it plays, record the number of straws it leaves after its turn. If it loses then ensure that it doesn't leave that many straws in turns in subsequent games.
Your code would look something like:
class AI_Player {
private final Set<Integer> losingMoves = new HashSet<>();
private final Set<Integer> currentGameMoves = new HashSet<>();
public void startGame() {
currentGameMoves.clear();
}
public int nextMove(int strawsRemaining) {
List<Integer> possibleMoves = Stream.of(1, 2, 3)
.filter(move -> move < strawsRemaining)
.filter(move -> !losingMoves.contains(strawsRemaining - move))
.collect(Collectors.toList());
int move = possibleMoves.get(Random.nextInt(possibleMoves.size()));
currentGameMoves.add(strawsRemaining - move);
return move;
}
public void registerLoss() {
losingMoves.addAll(currentGameMoves);
}
public void registerWin() {
losingMoves.removeAll(currentGameMoves);
}
}
This uses Java 8 streams but it's fairly trivial to convert if you haven't used them yet.
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.