I'm working on a cows and bulls game with two different classes:
The first class looks like this:
import java.util.*;
import java.util.Scanner;
public class CowsAndBulls {
int UserNumber=0;
int CompNumber=0;
int bulls=0;
int cows=0;
Scanner input = new Scanner(System.in);
public void getUserNumber() {
System.out.println("Please enter your guess!");
int UserValue=input.nextInt();
UserNumber=UserNumber+ UserValue;
System.out.println("Your guess is : " + UserNumber);
}
public void getCompNumber() {
Random generator= new Random();
int pickedNumber=generator.nextInt(10000) + 1000;
CompNumber =CompNumber+ pickedNumber;
System.out.println("The computer has guessed : " + CompNumber );
}
}
It just generates a random number for the computer and asks the user to input their guess.
I'm having a lot of trouble with my play class, specifically, I can't get my while loop to run,
public class CowsAndBullsPlay {
public void play() {
int GuessCount=0;
int UserNumber = 0;
int CompNumber = 0;
int cows = 0;
int bullcount=0;
int cowcount=0;
int bulls = 0;
Boolean GameEnds;
GameEnds=false;
while (GameEnds=false) {
CowsAndBulls user= new CowsAndBulls();
user.getUserNumber();
CowsAndBulls comp= new CowsAndBulls();
comp.getCompNumber();
String UserString=String.valueOf(UserNumber);
String CompString=String.valueOf(CompNumber);
String U=UserString;
String C=CompString;
for (int i=0; i<4; i++)
for (int k=i+1; k<4; k++) {
if(U.charAt(i)==C.charAt(k)) {
bullcount ++;
bulls=bulls + bullcount;
}
else if(U.contains(C.charAt(i) + U)) {
//for (int v=0; v<4; v++)
//for (int j=0; j<4; j++) {
cowcount ++;
cows=cows + cowcount;
}
GuessCount++;
}
if (bulls==4) {
GameEnds= true;
System.out.println("Congratulations!");
System.out.println("it took you:" + GuessCount);
}
else {
System.out.println("cows: " + cows);
System.out.println("Bulls:" + bulls);
}
}
}
}
It's supposed to check for cows and then check for bulls, then if bulls is not equal to four, the loop should reiterate--calling the first two methods that ask for user input and ask computer to randomly generate a number and then guesscount should keep track of loop iterations.
The code compiles, but it just won't run the while loop
here is my tester class:
public class CowsAndBullsTester {
public static void main(String[] args) {
int bears = 0;
int cows = 0;
Boolean GameEnds = false;
System.out.println("welcome to Cows Versus Bulls death match!");
CowsAndBulls user= new CowsAndBulls ();
user.getUserNumber();
System.out.println("Now the computer will pick a number!");
CowsAndBulls comp= new CowsAndBulls ();
comp.getCompNumber();
System.out.println("Let's see how you did!");
CowsAndBullsPlay game= new CowsAndBullsPlay();
game.play();
}
}
Really appreciate any help. I'm sure there's some stupid mistake, I'm just not sure what. This is only my third assignment and I'm having some trouble figuring out what's wrong on my own :)
thanks!
You need to change while (GameEnds=false) to while (GameEnds==false).
The first is an assignment, while the second is a comparison. So in the first, false will be assigned to GameEnds, and then GameEnds will evaluate to false for your while condition, meaning that the loop will never enter.
Also, see #AndrewMao's comment below. Generally, you will see booleans used in conditions directly, with or without negation (!), because they already hold truth values and a further comparison is redundant.
Small side note: you may want to rename your variable in camelCase for clarity.
Related
So I need to create one class with an enum in it, then use a second class to randomly select one of those enum values and do that as many times as the user wants.
Here's the main code
while (loop){
System.out.println("Enter the number of times you want to toss the coin, enter '0' to end the program: ");
num = s.nextInt();
int tails = 0;
int heads = 0;
if (num == 0){
loop = false;
continue;
}
else if (num < 0){
System.out.println("That's a negative number");
continue;
}
for (int count = 0; count < num; count++)
{
if (rand.nextInt(2) == 0)
tails = tails + 1;
else
heads = heads + 1;
}
System.out.println("Heads: " + heads + " Tails: " + tails);
}
and then here's the enum code
public class Coin{
public enum CoinEnum {
HEADS,TAILS;
}
}
I cut out some stuff because it was unneeded.
I think I have the general idea on how to randomly select, you can see I already wrote a quick calculation on how to do if there wasn't an enum value but I have no idea how to access the enum values from my main program, I tried making the class a package but that didn't work, I'm just not sure how. Any help would be great.
Thanks
The following code should work - randomly generate HEAD or TAIL enum; comments added to the code. Edited to change this to a working standalone example.
public class CoinEnumDemo {
public static void main(String[] args) {
// print 10 random values
for (int i = 0; i < 10; i++) {
int val = (int) Math.round(Math.random());
System.out.println(CoinEnum.values()[val]);
}
}
enum CoinEnum {
HEAD, TAIL;
}
}
I'm trying to make a program which asks the user a particular bird then how many of them they had seen at that point. If the use at any point enters the word 'END' then the system should print out the most seen bird and the number seen. However, when running my program if I enter 'END' at random points it instead returns that the most seen was END with 0 seen. I can't figure out how to make it work. I've tried different methods but it's just not working properly. Also, I've set the maximum array limit to 10 possitions but it continues after 10 and if i enter a value the system crashes. Have I written the limit part properly? Or am I missing something important?
import java.util.Scanner;
public class testing
{
public static void main (String[] param)
{
birdInput();
most();
System.exit(0);
}
public static void birdInput()
{
int i = 0;
String birdInput;
int numberInput;
Scanner scanner = new Scanner(System.in);
int maxVal = Integer.MIN_VALUE;
int maxValIndex = -1;
while (true)
{
System.out.println("What bird did you see?");
birdInput = scanner.nextLine();
if (birdInput.equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.exit(0);
}
else
{
String[] birds = new String[10];
int[] numbers = new int[10];
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
if (birds[i].equals("END"))
{
maxVal = numbers[i];
maxValIndex = i;
System.out.print("\nThe most common bird that you saw was the " + birds[maxValIndex] + " with " + maxVal + " being seen in total\n");
System.exit(0);
}
}
}
}
public static void most()
{
System.out.println("fdff");
}
}
This is my edit of Till Hemmerich's answer to my issue. I tried to remove the global variables and so combine the entire code into 1 method. However, I'm still having some issues. Been working at it but really confused.
import java.util.Scanner;
public class birds2
{
public static void main(String[] param)
{
birdInput();
System.exit(0);
}
public static void birdInput()
{
Scanner scanner = new Scanner(System.in);
String[] birds = new String[99999999];
int[] numbers = new int[99999999];
int i = 0;
int maxIndex;
while (i <= birds.length)
{
System.out.println("What bird did you see?");
birds[i] = scanner.nextLine();
System.out.println("How many did you see?");
numbers[i] = scanner.nextInt();
i++;
}
int newnumber = numbers[i];
if ((newnumber > numbers.length))
{
maxIndex = i;
i++;
}
if (birds[i].toUpperCase().equals("END"))
{
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
}
}
You're re-declaring the birds and numbers arrays in each iteration of the loop. They should be declared and initialized only once, before the loop.
I changed a lot so im going to explain my changes here in total.
First of all i had to move the Array Definition out of your while-loop as >mentioned above, since other wise you would override these Arrays every time.
I also made them globally accessible to work with them in other methods.
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
in general I re structured the whole code a little bit to make it more readable and a little bit more object-orientated.
For example I created an method called inputCheck() which returns our input as a String and check if it equals END so you do not have to write your logic for this twice. (it also considers writing end lower or Uppercased by just Upper our input before checking it"if (input.toUpperCase().equals("END"))")
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
this method can now be called every time you need an input like this:
birds[i] = inputCheck();
but you need to be carefull if you want to get an integer out of it you first have to parse it like this:Integer.parseInt(inputCheck())
after that I wrote a method to search for the biggest Value in your numbers Array and getting its index:
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
it takes an int array as parameter and returns the index of the highest element in there as an Integer. Called like this:maxIndex = getMaxIndex(numbers);
Then after that I rewrote your end method. It now just calles our getMaxIndex method and prints some output to the console.
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
to fix your last problem (crashing after more then 10 inputs)I changed your while-loop. Since your array only has 10 places to put things it crashes if you try to put information in place number 11. it not looks like this:while (i <= birds.length) instead of while (true) this way the max loops it can take is the amout of places Array birds has and it wont crash anymore.
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
Here is the whole code in total:
import java.util.Scanner;
/**
*
* #author E0268617
*/
public class JavaApplication1 {
public static int maxIndex;
public static String[] birds = new String[10];
public static int[] numbers = new int[10];
public static void main(String[] param) {
birdInput();
most();
System.exit(0);
}
public static void birdInput() {
int i = 0;
while (i <= birds.length) {
System.out.println("What bird did you see?");
birds[i] = inputCheck();
System.out.println("How many did you see?");
numbers[i] = Integer.parseInt(inputCheck()); //you should check here if its actuall a number otherwiese your programm will crash
i++;
}
}
static String inputCheck() {
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.toUpperCase().equals("END")) {
end();
}
return input;
}
public static int getMaxIndex(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int newnumber = numbers[i];
if ((newnumber > numbers.length)) {
maxIndex = i;
}
}
return maxIndex;
}
public static void end() {
maxIndex = getMaxIndex(numbers);
System.out.print("\nWell....I guess thanks for using this program?\n");
System.out.print("\nThe most common bird that you saw was the " + birds[maxIndex] + " with " + numbers[maxIndex] + " being seen in total\n");
System.exit(0);
}
public static void most() {
System.out.println("fdff");
}
}
I hope you understand where the Problems had been hidden if you have any Questions hit me up.
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));
}
}
}
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.
I have written a program with minimal errors but do not know where I should place the Average or Letter grade function:
package org.education.tutorial;
import java.util.Scanner;
public class GradingScale
{
public static void main (String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter the number of students attending your current session :");
int numberOfStudents = keyboard.nextInt();
System.out.println();
System.out.print("Also, please enter the amount of exams taken during the duration of the course : ");
int examScores = keyboard.nextInt();
AssignValueToArray(numberOfStudents, examScores);
keyboard.close();
}
public static void AssignValueToArray(int amountOfStudents, int amountOfExams)
{
int[][] overallScore = new int[amountOfStudents][amountOfExams];
Scanner keyboardArray = new Scanner(System.in);
int numberValue = 1;
for (int index = 0; index < amountOfStudents; index++)
{
System.out.println ("\n" + "Please submit Student #" + numberValue + " 's score :" );
for(int indexOfHomeWork=0; indexOfHomeWork < amountOfExams; indexOfHomeWork++)
{
overallScore[index][indexOfHomeWork] = keyboardArray.nextInt();
}
numberValue++;
}
DisplayvalueInArray(overallScore);
keyboardArray.close();
}
public static void DisplayvalueInArray(int[][] overallScoreArray)
{
System.out.println ("The students' scores are posted below : " + "\n");
int studentCount = 1;
for (int index = 0; index < overallScoreArray.length; index++)
{
System.out.print("Grades for student " + studentCount +": ");
for (int indexOfHomeWork = 0; indexOfHomeWork < overallScoreArray[index].length;
indexOfHomeWork++)
{
System.out.print(overallScoreArray[index][indexOfHomeWork]+"\t");
}
System.out.println();
studentCount++;
}
}
I would highly recommend learning how to use variable scope and possibly objects before doing something such as this.
You never declare any variables in the class's scope.
Most of your functions don't affect anything outside their own scope, and therefore shouldn't be functions. Instead use comments to encapsulate.
Many of your variables are named poorly, instead of keyboardArray, which is not an array at all, do something like kb, or keyboardScanner
For computing average and lettergrades, think 'what am i averaging' and use that as your parameter, with the average as your return type, so something like static int average(int[] scores)