Score calculator - java

Ok, so, I am very new to java.
I am designing a score calculator, for a project that I have long left aside. Still, I would like to know how to do this, for my own knowledge.
The program is supposed to ask for a dice roll, and add it to the previous rolls, for each player.
I assumed a while loop would accomplish this, but every time it goes through the loop it resets the variable to the current roll. As such, I cannot get a total...
Below is some code:
static int players;
static String p1;
static String p2;
static String p3;
static String p4;
static int maxScore;
static int roll1;
static int roll2;
static int roll3;
static int roll4;
static int total1;
static int total2;
static int total3;
static int total4;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter number of players: ");
players=keyboard.nextInt();
System.out.print("Enter Maximum Score: ");
maxScore=keyboard.nextInt();
if(players==2){ //will add more ifs when i get the code right
System.out.println("Please enter players names.");
System.out.print("Player 1: ");
p1=keyboard.next();
System.out.print("Player 2: ");
p2=keyboard.next();
System.out.println(p1 + "\t \t " + p2 + "\n"
+ "_______ \t _______ \n" ); //displays scorecard look with players names
{
while (total1 < maxScore && total2<maxScore) {
//scorecard quits when maxScore is reached by either player
int roll;
total1=(roll+roll1);
System.out.print("");
roll=keyboard.nextInt(); //asks for current roll
System.out.print("\n"+"_____"+"\n");
System.out.print(roll+"+"+"\n"+roll1+"\n"+"_____"+"\n"+(roll+roll1)+"\n");
/*i want this to display total score + last roll and then
*total it again on the next line*/
roll1=roll;
}

Some hints for your programming progress in Java:
The variable roll serves no purpose. roll1, and so on, will store the last roll for each player.
Initialize your variables, if possible. Relying on default values should be avoided, as it may bring you problems as you learn (NullPointerException will pay you a visit sometime).
In your loop, you had total1=(roll+roll1);. This is wrong. Your variables, total1, roll, roll1 are not initialized by the time the program reaches this point. As they are integers, they are (silently) initialized to 0, so total1 yields 0 at this point, which does not accomplish much. After this, you proceed to retrieve the roll. Try the other way around, first the roll, then adding up.
You mentioned you're new to Java, but, at some point in the future, you might consider implementing this same program with arrays. You'll notice it saves you much of the repeating code you wrote now.
Summing up, and translating to code guidelines (for 2 players):
public class MyScoreCalculator {
static String p1 = "";
static String p2 = "";
static int maxScore = 0;
static int roll1 = 0;
static int roll2 = 0;
static int total1 = 0;
static int total2 = 0;
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
// Dialogue to get data...
// Display scorecard look with players names
while (total1 < maxScore && total2 < maxScore) {
//scorecard quits when maxScore is reached by either player
roll1 = keyboard.nextInt(); // ask for current roll
System.out.println(total1 + "+");
System.out.println(roll1);
System.out.println("_____");
System.out.println(roll1 + total1);
total1 = total1 + roll1;
// Do the same for next player.
}
}
}

If I am reading your question correctly then the solution is
total1+=(roll+roll1);
which is the same thing as
total1= total1+(roll+roll1);
Your just not adding the rolls to the total value!
Also as a point of note, it is not a good idea to have your instance variables as public and static. It would be better if they were private and not static. For example
private int players;
Hope the answer helps

Your total1 calculation should be total1 += roll and happen after the new roll input. Also if roll1 represents the last roll, name the variable accordingly, it's much more readable.
Since you have many players, try to abstract the concepts and separate the input from the "accounting". For example, you could create a PlayerScore class that holds a total and the last input (and the player's name), with a method that takes care of adding and saving the last input, as well as prettyprinting the infos. You can then have a collection of PlayerScore and iterate over it, ask the current roll and have the infos updated.

Related

Java while loop repeats and doesn’t exit when code reaches the end

I'm very inexperienced with coding, and am trying to make a very basic text based rpg combat system using my limited knowledge and the internet. Ideally the program should allow you to choose a type of attack, take the stamina cost away from your max stamina, then tell you how much damage you've done. As of now I am just trying to get the "normal attack" to work, but whenever you run the code and choose an attack it continuously just repeats the instructions on how to attack. I have included both the code and a screenshot of what displays when running. I assume the problem lies with me misusing the while loop, as I don't know much about it.
import java.util.Scanner;
import java.util.Random;
public class RPGv1 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Random rand = new Random();
System.out.println("What is your name?");
String name = scan.nextLine();
System.out.println("\nWelcome to RPGv1 " + name + "!");
// Max Stats
int MaxHP = rand.nextInt(25) + 1;
int MaxMP = rand.nextInt(20) + 1;
int MaxStam = 15;
// Enemy 1 Stats
int En1HP = rand.nextInt(10) + 1;
int En1Stam = rand.nextInt(5) + 1;
// Combat
System.out.println("You are being approached by the evil Enemy 1!");
while (En1HP > 0) {
System.out.println("Type \"n\" to use your Normal Attack, \"h\" for your Heavy Attack, and \"f\" for your fireball.");
String combat = scan.nextLine();
if (combat == "n")
if (MaxStam >= 2) { //required stamina
int nDam = rand.nextInt(3) + 1; //damage
int nStam = rand.nextInt(5) + 1; //stamina use
MaxStam = MaxStam - nStam; //stamina being taken
System.out.println("You have dealt " + nDam + " damage, and have " + MaxStam + " Stamina remaining.");
} else {
System.out.println("You do not have enough stamina.");
}
}
}
}
enter image description here
You are never updating the value of En1HP variable, so it always remaings greater than 0, and thus loops goes for infinite.
To break the loop, you must need to update En1HP variable and set its value to less than zero on some condition.
Also as a code conventions, you should use camel-case naming convention for naming variable names.

Replace 'menu' with input from user

In the interest of learning I decided to write up a coin flipping program. The coin is an enum and i have the program return that enum value. I also have the user input from a menu style but this was helped by following along in a Barnes and Nobles book I purchased a while back.
I think I have come to a weird cross road. i was wanting to basically return the enum value and such but remove the 'menu' aspect and replace it with the ability for the user to input how many flips they would like to do and also repeat the program if they want to (so instead of pressing 1 to flip each time they can input say 20000 and it would flip that many times i also think doing this would help with a fairness check as a true test of fairness would return almost even amounts of heads and tails if it were to flip that many times then pressing 0 for no flips would end the program) and i want to prompt the user and ask if they would like to repeat.
here is the program I have written:
import java.util.*;
public class CoinTossing
{
private enum Coin { HEADS, TAILS };
private static final Random randomNumbers = new Random();
private static final int HEAD = 1;
private static final int TAIL = 2;
public static void main(String[] args)
{
Scanner input = new Scanner( System.in );
int choice;
int toss = 0;
int tosses = 0;
int frontflip = 0;
int backflip = 0;
Coin gameStatus;
System.out.println("Welcome to the Coin Toss Program.\n");
System.out.println("Choose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
while ( choice != 0 )
{
if ( choice == 1 )
{
int CoinTossed = Flip();
switch ( CoinTossed )
{
//added tosses to switch statement to make the counter work perfect.
case HEAD:
gameStatus = Coin.HEADS;
tosses++; // add amount of tosses
break;
default: // changed case TAIL to default. Easy and works.
gameStatus = Coin.TAILS;
tosses++; // add amount of tosses
break;
}
if ( gameStatus == Coin.HEADS )
{
frontflip++; //Add amount of heads
}
else // gameStatus == TAILS
backflip++; //Add amount of tails
}
// A try to make an real exit out of a program
if ( choice == 2 )
{
EndProgram( frontflip, backflip, tosses );
}
System.out.println("\nChoose from the menu what you want to do.");
System.out.print("1. Toss the coin\n2. Quit program\n");
choice = input.nextInt();
}
}
//Toss the coin to determine 1 or 2.
public static int Flip()
{
int toss;
toss = 1 + randomNumbers.nextInt( 2 );
if ( toss == 1 )
{
System.out.println("You toss the coin and it lands on head!");
}
else
{
System.out.println("You toss the coin and it lands on tail!");
}
return toss;
}
public static void EndProgram( int frontflip, int backflip, int tosses )
{
System.out.printf("You have tossed %d times.\n", tosses);
System.out.printf("Of all those tosses, %d landed on heads, and %d on tails.\n", frontflip, backflip);
System.exit(0);
}
}
I think I need a do / while loop so that I can have the user answer the yes or no question of do you want to play again? and inside the loop I have a switch statement that also says if the user inputs 0 for the number of flips the program ends?
I thought I could add this snippet to get input:
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
number = input.nextInt();
I was thinking of creating a new variable and have the user set the number of tosses. Then compound the while loop check like so
while(choice != 0 && numTosses !=0)
and then decrease the count and I'll have to check that count and once it reaches 0 print results as far as how many heads and how many tails then prompt the user if they would like to play the game again but I am having trouble getting the right. honestly I don't even know why I'm trying to do this if but for the knowledge aspect so if you don't wanna help a broski out I understand. I feel like I am on the right track.
You can use 2 loops:
public class CoinFlip {
private enum Coin {
HEADS,
TAILS
};
public static void main(String[] arguments) {
new CoinFlip();
}
CoinFlip() {
Scanner input = new Scanner(System.in);
int heads = 0, tails = 0;
while (true) {
System.out.println("How many flips do you want?");
System.out.println("(0 will exit the program)");
int number = input.nextInt();
if (number == 0)
break; // or System.exit
for (int i = 0; i < number; i++) {
Coin flipResult = flip();
switch (flipResult) {
case HEADS:
heads++;
break;
case TAILS:
tails++;
break;
}
}
System.out.println("Heads: " + heads);
System.out.println("Tails: " + tails);
}
}
private Coin flip() {
return Coin.values()[(int) (Math.random() * Coin.values().length)];
}
}
The while loop continues to ask the user to play again and again, if they put 0 your break it or exit it. In that loop, a for loop will iterate over the flips.

How to program a dice race

I'm taking a programming II class in which we've been working on programming classes. Now we've been assigned homework to write a driver class to incorporate these classes. The homework states
Using the die, dice, and player classes completed in class, write a
driver class to have three players taking turns rolling the dice.
First player to accumulate a total score of 35 or more is the winner."
For example, if player 1 rolls a 3, their score is 3. Then player 2
rolls. Then player 3. As each player rolls, their roll is added to
their previous score.
I've started writing it, but have been given the error that several items in my program cannot be resolved to a type. I also have absolutely no idea how to even begin creating a loop to do what is being asked. This is what I have so far:
import java.util.Scanner;
public class DiceRace {
public static void main(String[] args){
Player player1;
Player player2;
Player player3;
Dice dice;
Scanner keyboard;
keyboard=new Scanner(System.in);
dice=new Dice();
System.out.print("First player's name: ");
player1=keyboard.next();
System.out.print("Second player's name: ");
player2=keyboard.next();
System.out.print("Third player's name: ");
player3=keyboard.next();
}//Ending bracket of method main
}//Ending bracket of class DiceRace
You can create 3 methods, for each player, and a method that plays the game. In each player's method, it first calls the play method with a parameter containing the player name, and the play method prints it out so that the player knows who's turn it is. once the play method is done, it will call the next player method, then the player after that, and finally back to player 1.
It looks like you're a beginner. You should do some tutorials or stuff like that to know the basics :) Also, if you start getting familiar with an IDE (like Eclipse) then programming will be far more easy for you as IDEs can give you detailed descriptions of errors, even while writing the code.
In your above example you need to create two classes by yourself Dice and Player, as they are not in Java by default.
The method keyboard.next() reads an input from the console and returns it as object of the type String, not Player. Thus, you can not assign the variable player1 the result, a String.
What you probably want is a Player object having a member variable String name. Here's an example:
public final class Player {
private String mName;
public Player(final String name) {
mName = name;
}
public String getName() {
return mName;
}
}
Then you can do something like this in your main-method:
player1 = new Player(keyboard.next());
System.out.println("Name of player1 is: " + player1.getName());
Next you probably want a Dice to have a roll method:
public final class Dice() {
private Random mRandom;
public Dice() {
mRandom = new Random();
}
public int roll() {
// Returns a random number between 1 and 6 (inclusive)
return mRandom.nextInt(6) + 1;
}
}
Then, in your main you can do:
Dice dice = new Dice();
System.out.println("Let's roll the dice: " dice.roll());
Now to the games logic, let's keep it very simple, beginner friendly:
int player1Score = 0;
int player2Score = 0;
int player3Score = 0;
boolean finished = false;
boolean player1One = false;
boolean player2One = false;
boolean player3One = false;
// 0 is first player, 1 second and 2 third
int currentPlayer = 0;
while(!finished) {
int rollValue = dice.roll();
if (currentPlayer == 0) {
player1Score += rollValue;
} else if (currentPlayer == 1) {
player2Score += rollValue;
} else {
player3Score += rollValue;
}
player1One = player1Score >= 35;
player2One = player2Score >= 35;
player3One = player3Score >= 35;
finished = player1One || player2One || player3One;
// Increment and modulo 3 (numbers between 0 and 2)
currentPlayer = ((currentPlayer + 1) % 3);
}
Good luck :)

Cmputer not following rules

I'm trying to come up with a reverse guessing game. Computer to guess my selected number with a range of 1-100. I do have the binary search algorithm, but when I tell the computer it's first guess is Too High, it will give me another High guess instead of going lower.
import java.util.Random;
import java.util.Scanner;
public class ComputersGuessGame {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random value = new Random();
int computerGuess;
int highValue = 100;
int lowValue = 1;
String myAnswer;
do {
computerGuess = value.nextInt(highValue - lowValue +1)/2;
/*
*Above line should use the binary algorithm so the computer can
*make guesses and not just guess my number by going one number at a time
*/
System.out.println("I'm guessing that your number is " + computerGuess);
myAnswer = in.nextLine();
if (myAnswer.equals("tl")){
highValue = computerGuess + 1;//Too Low Answer
}
else if (myAnswer.equals ("th")){
lowValue = computerGuess - 1;//To High Answer
}
} while (!myAnswer.equals("y")); //Answer is correct
in.close();
System.out.println("Thank you, Good Game.");
}
}//Comptuer keeps making random guesses, but if I say too high, it will guess another high number instead of going low.
I think your logic to guess the next number was wrong. You should have interchange the setting the lower & high value,and change the logic to generate next guess.
here is the working solution of your problem
import java.util.Random;
import java.util.Scanner;
public class Guess {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random value = new Random();
int computerGuess;
int highValue = 100;
int lowValue = 1;
String myAnswer;
do {
computerGuess = value.nextInt(highValue - lowValue)+lowValue;
System.out.println("I'm guessing that your number is " + computerGuess);
myAnswer = in.nextLine();
if (myAnswer.equals("tl")){
lowValue = computerGuess + 1;
} else if (myAnswer.equals ("th")){
highValue = computerGuess - 1;
}
} while (!myAnswer.equals("y"));
in.close();
System.out.println("Thank you, Good Game.");
}
}
you should try to approximate to your guess. you should try nested intervals. your working with class random, of course your computer could guess another high number again, when only lowering the range by one.
you should work with at least 2 new variables, rangeLow and rangeHigh. when to high, your new rangeHigh is your last guess. when to low, your new rangeLow is your last guess.
computerGuess = value.nextInt(rangeLow,rangeHigh);

Methods Help in Java

public static void main(String[] args)
{
int i = 0;
i = rollDice(11);
System.out.print(" \nThe number of rolls it took: " + i);
i = rollDice(5);
System.out.print(" \nThe number of rolls it took: " + i);
}
public static int rollDice(int desiredNum)
{
int dice1 = 0;
int dice2 = 0;
Random rand = new Random();
int sum = 0;
int count = 0;
do
{
dice1 = rand.nextInt(6) +1;
dice2 = rand.nextInt(6) +1;
sum = dice1 + dice2;
count++;
} while(sum != desiredNum);
return count;
}
}
Im wanting to make it where the user can enter their own desired sum of the numbers to be rolled .Also I'm wanting it to display the value of each rolled die as its rolled. It needs to allow the user to call the rollDice method as many times as they want to.
Heres my exmaple output
EX- Please enter the Desired number: 8
Roll 1: 4 6 Sum: 10
Roll 2: 3 5 Sum: 8
It took 2 rolls to get the Desired number.
The original code above WAS a lab i had to do a few weeks ago. But we have just started this. And im trying to get ahead of the class. And this community helps alot. Thanks in advance.
The simplest solution here is to read user input using a Scanner, until the user enters a nominated character which ends the program.
e.g.
public static void Main(String[] args) {
Scanner scan = new Scanner(System.in);
do {
System.out.println("Enter desired number:");
String in = scan.nextLine();
rollDice(Integer.parseInt(in));
// Implement console output formatting here
} while(!in.equalsIgnoreCase("q"))
}
Here, the user can roll the dice for their desired number as many times as they want. When they are finished, entering "q" or "Q" in the console will end the program.
Also see the Javadoc for Scanner.
Try separating it into a few different methods like this. It'll help you think about the problem in smaller parts.
public static void main(String[] args) {
String input = "";
while(true) {
//Request input
System.out.println("Please enter the Desired number:");
input = getInput();
//Try to turn the string into an integer
try {
int parsed = Integer.parseInt(input);
rollDice(parsed);
} catch (Exception e) {
break; //Stop asking when they enter something other than a number
}
}
}
private static String getInput() {
//Write the method for getting user input
}
private static void rollDice(int desiredNum) {
//Roll the dice and print the output until you get desiredNum
}
To repeat, add a statement where the user enters a character that determines whether or not the program repeats itself. For example:
char repeat = 'Y';
while (repeat == 'Y' || repeat == 'y') {
// Previous code goes here
System.out.println("Try again? {Y/N} --> ");
String temp = input.nextLine();
repeat = temp.charAt(0);
}

Categories