Why are object values not being stored? - java

***After bottle3 is .set() to 0, all of the values seem to be set to zero. Even took the bottle3.set(0); bit of the driver and it the other bottle objects still seem to lose the value that they are supposed to be set to.
import java.util.Scanner;
test driver for the Bottle class
public class BottleDriver extends Bottle
{
static Scanner scan = new Scanner(System.in);
public static void main(String[] args)
{
int x;
Bottle bottle1 = new Bottle();
Bottle bottle2 = new Bottle();
Bottle bottle3 = new Bottle();
Bottle bottle4 = new Bottle();
Bottle bottle5 = new Bottle();
System.out.println("please enter a number for bottle1:");
bottle1.read();
System.out.println("Bottle1 is this value " + bottle1.marbles + ".");
System.out.println("Please enter a number for bottle2:");
bottle2.read();
System.out.println("Bottle2 is this value " + bottle2.marbles + ".");
bottle3.set(0);
System.out.println("Bottle3 is set to " + bottle3.marbles + ".");
bottle3 = bottle3.add(bottle1);
System.out.println(bottle3.marbles);
bottle3 = bottle3.add(bottle2);
bottle3 = bottle3.divide(2);
System.out.println("The 2 bottle average is: " + bottle3 + ".");
System.out.print("Subtracting bottle1 from bottle2 is: " );
bottle3 = bottle2.subtract(bottle1);
System.out.println( bottle3);
bottle3 = bottle2.divide(bottle1);
System.out.println("Dividing bottle2 with bottle1 is: " + bottle3 + ".");
if (bottle1.equals(bottle2))
{
System.out.println("Bottle1 and bottle2 are equal.");
}
else
{
System.out.println("Bottle1 and bottle2 are not equal.");
}
System.out.println("Bottle4 is now given the value of 10 with the set()method.");
bottle4.set(10);
System.out.println("The value of bottle4 is " + bottle4 + ".");
System.out.println("Bottle4 is now multiplied with bottle1. The value is placed in bottle5.");
bottle5 = bottle1.multiply(bottle4);
System.out.println("The value of bottle5 is " + bottle5 + ".");
System.out.println("Enter an integer to add to the value bottle1 has.");
System.out.println("The sum will be put in bottle3.");
x = scan.nextInt();
bottle3 = bottle1.add(x);
System.out.println("Adding your number " + x +
" to bottle1 gives a new Bottle with " + bottle3 + " in it.");
System.out.print("Adding the number " + bottle2 + " which is the number" +
" in bottle2 to the\nnumber in ");
bottle2 = bottle1.add(bottle2);
System.out.println("bottle1 which is " + bottle1 +" gives " + bottle2 + ".");
}
}
//***Bottle Class
import java.util.Scanner;
public class Bottle
{
public static final int MAX = 75;
public static final int MIN = 0;
public static int marbles;
Bottle()
{
marbles = 0;
}
public int get()
{
return this.marbles;
}
public void read() {
Scanner keyboard = new Scanner(System.in);
marbles = keyboard.nextInt();
set(marbles);
}
public void set(int marbles)
{
if(marbles > MAX || marbles < MIN)
{
System.out.println("Below or exceeded capacity of the bottle.");
System.exit(0);
}
else
{
this.marbles = marbles;
}
}
public Bottle add(Bottle bottle)
{
Bottle newBottle = new Bottle();
newBottle.set(newBottle.marbles + bottle.marbles);
return newBottle;
}
public int subtract(int bottle)
{
}
public int multiply(int bottle)
{
}
public int divide(int bottle)
{
}
}

The issue is that marbles is a static field. Static fields are shared between all instances of the class, to help save on memory. Remove the static annotation and it should fix your issue.
public static int marbles;

Related

I am stuck, trying to make a turn based game but have been having trouble ending a turn and starting a new one

I can end the first. I am trying to make it on odd turns player goes and even turns CPU goes.
public static void main(String[] args) {
Random random = new Random();
Scanner keyboard = new Scanner(System.in);
String mage = "mage";
System.out.println("mage, warrior, assassin, ranger?");
String input = keyboard.nextLine();
int playerAttackDice = random.nextInt(20) + 1;
int cpuAttackDice = random.nextInt(20) + 1;
int playerDefenseDice = random.nextInt(5) + 1;
int cpuDefenseDice = random.nextInt(5) + 1;
int turn = 1;
while(mage.equalsIgnoreCase(input)) {
Mage player = new Mage();
Warrior CPU = new Warrior();
System.out.println("You have selected: mage");
System.out.println("Your Attack Power is: " + player.getMageAttack());
System.out.println("Your Defense is: " + player.getMageDefense());
System.out.println("Your Health is: " + player.getMageHealth());
System.out.println("Your enemy is a: warrior");
System.out.println("Enemy Attack Power is: " + CPU.getMageAttack());
System.out.println("Enemy Defense is: " + CPU.getMageDefense());
System.out.println("Enemy Health is: " + CPU.getMageHealth());
System.out.println();
This is where the turn begins. I was trying to set it to make it player goes on odd numbers in the when the CPU goes. Am I even approaching this in the right way? Any help would be very much appreciated.
while(player.mageHealth != 0) {
System.out.println("Your health is: " + player.mageHealth);
for(turn = 1; turn % 1 ==0; turn++) {
if(turn % 1==0) {
System.out.println("Your dice roll is:" + playerAttackDice);
int playerDamage = playerAttackDice + player.mageAttack;
int cpuDefense = cpuDefenseDice + CPU.mageDefense;
System.out.println(playerDamage);
System.out.println(cpuDefense);
System.out.println("CPU health is: " + (CPU.mageHealth + cpuDefense - playerDamage ));
return;
}
}
turn++;
for(turn = 2; turn % 2 ==0; turn++) {
while(turn % 2==0) {
System.out.println("CPU dice roll is:" + cpuAttackDice);
System.out.println("Your dice roll is:" + playerDefenseDice);
int cpuDamage = playerDefenseDice + player.mageAttack;
int playerDefense = cpuAttackDice + CPU.mageHealth;
System.out.println(cpuDamage);
System.out.println(playerDefense);
}
}
}
System.out.println("end loop");
break;
}
}
If you want Player and CPU to play their move one after another - just put their actions one after another with no inner loops and complex conditions around
while (!game.isOver()) {
player.makeMove();
cpu.makeMove();
}
or having your code there
while(player.mageHealth > 0) { // game over condition
//player move
System.out.println("Your health is: " + player.mageHealth);
System.out.println("Your dice roll is:" + playerAttackDice);
int playerDamage = playerAttackDice + player.mageAttack;
int cpuDefense = cpuDefenseDice + CPU.mageDefense;
System.out.println(playerDamage);
System.out.println(cpuDefense);
System.out.println("CPU health is: " + (CPU.mageHealth + cpuDefense - playerDamage ));
//cpu move
System.out.println("CPU dice roll is:" + cpuAttackDice);
System.out.println("Your dice roll is:" + playerDefenseDice);
int cpuDamage = playerDefenseDice + player.mageAttack;
int playerDefense = cpuAttackDice + CPU.mageHealth;
System.out.println(cpuDamage);
System.out.println(playerDefense);
player.mageHealth = player.mageHealth + playerDefence - cpuDamage;
}

Certain "if" statements containing print lines not being executed and thus not printing onto the console

I am coding a text-based java game where the user types in certain inputs to ultimately defeat an enemy. I want to create a score by writing out if statements that state if the damage done on the enemy was x amount, then award x points. However, I believe the if statement is being skipped over because it is not printing the print statements.
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args) {
game gameObject = new game();
gameObject.runGame();
}
}
class game {
public void runGame() {
// System Objects
Scanner in = new Scanner(System.in);
Random rand = new Random();
// Game Variables
String[] enemies = {"Skeleton", "Zombie", "Warrior", "Assasain"};
int maxEnemyHealth = 100;
int enemyAttackDamage = 50;
// Player Variables
int health = 100;
int attackDamage = 50;
int numHealthPotions = 3;
int healthPotionHealAmount = 30;
int healthPotionDropChance = 50; // Percentage
int counter = 0;
int points =0;
boolean running = true;
System.out.println("Welcome to the Dungeon!");
GAME:
while (running) {
System.out.println("-----------------------------------");
int enemyHealth = rand.nextInt(maxEnemyHealth);
String enemy = enemies[rand.nextInt(enemies.length)];
System.out.println("\t# " + enemy + " has appeared! #\n");
while (enemyHealth > 0) {
System.out.println("\tYour HP: " + health);
System.out.println("\t" + enemy + "'s HP: " + enemyHealth);
System.out.println("\n\tWhat would you like to do?");
System.out.println("\t1. Attack");
System.out.println("\t2. Drink health potion");
System.out.println("\t3. Run!");
String input = in.nextLine();
if (input.equals("1")) {
int damageDealt = rand.nextInt(attackDamage);
int damageTaken = rand.nextInt(enemyAttackDamage);
enemyHealth -= damageDealt;
health -= damageTaken;
System.out.println("\t> You strike the " + enemy + " for " + damageDealt);
System.out.println("\t> You recieve " + damageTaken + " in retaliation!");
if (health < 1) {
System.out.println("\t> You have taken too much damage, you are too weak to move on!");
break;
}
if (damageDealt > 20) {
points += 50;
System.out.print("You gained 50 points. You have" + points + " points in total.");
}
else if (damageDealt > 30) {
points += 60;
System.out.print("You gained 60 points. You have" + points + " points in total.");
}
else if (damageDealt >50) {
points += 100;
System.out.print("You gained 100 points. You have" + points + " points in total.");
}
}
else if (input.equals("2")) {
if (numHealthPotions > 0) {
health += healthPotionHealAmount;
numHealthPotions--;
System.out.println("\t> You drink a health potion, healing yourself for " + healthPotionHealAmount + "."
+ "\n\t> You now have " + health + " HP."
+ "\n\t> You have " + numHealthPotions + " health potionsleft.\n");
}
else {
System.out.println("\t> You have no health potions left! Defeat enemies to get a chance to get one.\n");
}
}
else if (input.equals("3")) {
System.out.println("\tYou run away from the " + enemy + "!");
continue GAME;
}
else {
System.out.println("\tInvalid command.");
}
}
if (health < 1) {
System.out.println("You limp out of the dungeon, weak from battle!");
break;
}
System.out.println("-----------------------------------");
System.out.println(" # " + enemy + " was defeated! #");
System.out.println(" # You have " + health + " HP left. #");
if (rand.nextInt(100) < healthPotionDropChance) {
numHealthPotions++;
System.out.println(" # The " + enemy + " dropped a health potion! # ");
System.out.println(" # You now have " + numHealthPotions + " health potion(s). #");
}
System.out.println("-----------------------------------");
System.out.println("What would you like to do now?");
System.out.println("1. Continue fighting");
System.out.println("1. Exit the dungeon");
String input = in.nextLine();
while (!input.equals("1") && !input.equals("2")) {
System.out.print("Invalid command!");
input = in.nextLine();
}
if (input.contentEquals("1")) {
System.out.println("You continue on your adventure!");
}
else if (input.equals("2")) {
System.out.println("You exit the dungeon, successful from your adventures!");
break;
}
counter++;
}
}
class exit {
public String byeStatements () {
String format;
String thanks;
format = "###########";
thanks = "Thanks for playing!";
System.out.println(format);
System.out.println(thanks);
return (format + thanks);
}
}

I have 2 errors compiling my java Lottery program using arrays

import java.util.Random;
import java.util.Scanner;
public class LotteryGame{
public static void main(String[] args) {
int NUM_DIGITS = 6;
int[] userDigits = new int[NUM_DIGITS];
int[] lotteryNumbers = new int[NUM_DIGITS];
int sameNum;
generateNumbers(lotteryNumbers);
getUserData(userDigits);
sameNum = compareArrays(lotteryNumbers, userDigits);
System.out.println("Winning numbers: " + lotteryNumbers[0] + " "
+ lotteryNumbers[1] + " " + lotteryNumbers[2] + " "
+ lotteryNumbers[3] + " " + lotteryNumbers[4] + " " + lotteryNumbers[5] + " ");
System.out.println("Your numbers: " + userDigits[0] + " "
+ userDigits[1] + " " + userDigits[2] + " " + userDigits[3]
+ " " + userDigits[4] + " " + userDigits[5] +" ");
System.out.println("Number of matching digits: " + sameNum);
if (sameNum == 6) {
System.out.println("First prize!!!");
}
if (sameNum == 5) {
System.out.println("Second prize!!!");
}
if (sameNum == 0) {
System.out.println("No matching numbers, you lost.");
}
}
public static void generateNumbers(int[] lotteryNumbers) {
Random randNum = new Random();
lotteryNumbers[0] = randNum.nextInt(59);
lotteryNumbers[1] = randNum.nextInt(59);
lotteryNumbers[2] = randNum.nextInt(59);
lotteryNumbers[3] = randNum.nextInt(59);
lotteryNumbers[4] = randNum.nextInt(59);
lotteryNumbers[5] = randNum.nextInt(59);
return lotteryNumbers[5];
}
public static void getUserData(int[] userDigits) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter first digit: ");
userDigits[0] = keyboard.nextInt();
System.out.print("Enter second digit: ");
userDigits[1] = keyboard.nextInt();
System.out.print("Enter third digit: ");
userDigits[2] = keyboard.nextInt();
System.out.print("Enter fourth digit: ");
userDigits[3] = keyboard.nextInt();
System.out.print("Enter fifth digit: ");
userDigits[4] = keyboard.nextInt();
System.out.print("Enter sixth digit: ");
userDigits[5] = keyboard.nextInt();
return userDigits[5];
}
public static int compareArrays(int[] userDigits, int[] lotteryNumbers) {
int sameNum = 0;
for (int i = 0; i < 6; i++) {
for (int x = 0; x < 5; x++) {
if (lotteryNumbers[i] == userDigits[x]) {
sameNum++;
}
}
}
return sameNum;
}
}
When I compile I get the following errors-
LotteryGame.java:51: error: incompatible types: unexpected return value
return lotteryNumbers[5];
^
LotteryGame.java:72: error: incompatible types: unexpected return value
return userDigits[5];
^
2 errors
Can any of you help me with these compilation errors? I'm trying to get this to work. The user is supposed to input 6 numbers, and the program is supposed to pick randomly 6 numbers. Using these numbers, the program will compare the numbers with echoed input.
generateNumbers and getUserData are void functions, meaning they don't return anything, so you can't return anything from them.
You probably want to declare them as functions returning int instead:
public static int generateNumbers(int[] lotteryNumbers)
Univerio is correct in answering your original question.
Looking at your test code you might consider removing the return statement on those two functions since you are just populating both arrays.

How do I make this if statement?

Apologies for the silly question, I am currently struggling to learn java. I need this code to work so that it will repeat unless '0' is entered for the studentNumber, I'm unsure of how to get the "please enter student number" part to work when I have to declare the int for that before the if statement? I'm not sure if I've approached this completely wrong or what, but I need to be able to repeat the data entry unless "0" is entered as the studentNumber. Thanks for any help!
class Main {
public static void main( String args[] ) {
int studentNumber = BIO.getInt();
if(studentNumber > 0) {
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
}
Use while()
while(studentNumber > 0){
studentNumber = BIO.getInt();
.........
........
}
See also
while in Java
Use while() instead of if, along with the following changes:
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.getInt();
while(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
System.out.print("#Please enter the student number : ");
studentNumber = BIO.getInt();
}
System.out.print("#End of data");
This, as opposed to the other answers, will ensure that even in the first iteration, you perform the check (and promt the user for the student number).
Using Scanner to get the input from the user and process the input value
import java.util.Scanner;
public class ConditionCheck {
public static void main(String[] args) {
Scanner BIO = new Scanner(System.in);
System.out.print("#Please enter the student number : ");
int studentNumber = BIO.nextInt();
if(studentNumber > 0) {
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.nextInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.nextInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber
+ " ex = " + examMark + " cw = " + courseWork
+ " mark = " + average);
} else {
System.out.print("#End of data");
}
}
}
You should be using a while statement and do something as below:
class Main
{
public static void main( String args[] )
{
int studentNumber = 1;
While(studentNumber > 0)
{
studentNumber = BIO.getInt();
System.out.print("#Please enter the student number : ");
System.out.print("#Please enter the coursework mark : ");
int courseWork = BIO.getInt();
System.out.print("#Please enter the exam mark : ");
int examMark = BIO.getInt();
double average = (double)(courseWork + examMark) / 2;
System.out.printf("sn = " + studentNumber + " ex = " + examMark + " cw = " + courseWork + " mark = " + average);
}
else
{
System.out.print("#End of data");
}
}
}

Methods and arrays

Here is my code:
import java.util.*;
import java.text.*;
public class zadanko4
{
int ile;
public static final int vat8 = 8;
public static final int vat23 = 23;
public static final int vat5 = 5;
//deklaracje zmiennych tablicowych
static double[] price;
static String[] name;
static int[] quantity;
static int[] vat;
//tworzenie tablic
price = new double[ile];
name = new String[ile];
quantity = new int[ile];
vat = new int[ile];
public static void printSellerData(String tekst)
{
System.out.print(tekst);
}
public static void printBuyerData(String company, String taxNo, String phone, String email)
{
System.out.print(company + taxNo + phone + email);
}
public static void printInvoiceDate(Date data)
{
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.print(dateFormat.format(data));
}
public static void printInvoiceHeader(String naglowek)
{
System.out.print(naglowek);
}
public static void printInvoiceProduct(String name, int quantity, double price, int vat)
{
System.out.printf(name + quantity + price + vat);
}
public static void readProductsData()
{
//uzytkownik wprowadza liczbe produktow
System.out.println("podaj liczbe produktow");
Scanner scanner = new Scanner(System. in );
ile = scanner.nextInt();
}
public static void main(String[] args)
{
int i;
String line;
for (i = 0; i < ile; i++)
{
System.out.print("Podaj cene produktu nr " + (i + 1) + ": ");
price[i] = scanner.nextDouble();
System.out.print("Podaj nazwe produktu nr " + (i + 1) + ": ");
name[i] = scanner.next();
System.out.print("Podaj ilosc produktu nr " + (i + 1) + ": ");
quantity[i] = scanner.nextInt();
System.out.print("Podaj vat produktu nr " + (i + 1) + ": ");
vat[i] = scanner.nextInt();
System.out.printf("Dane sprzedajacego\n");
printSellerData("Company: MaxDom Ltd, Kochanowskiego 17, 31-782 Krakow, Poland\n");
printSellerData("Tax no: 677-000-21-39\n");
printSellerData("Phone: +48123454943\n");
printSellerData("Email: office#maxdom.pl\n\n");
System.out.printf("Dane kupujacego\n");
printBuyerData("Softpol Ltd, Mickiewicza 5, 31-009 Krakow, Poland\n", "342-909-33-12\n", "+48505392100\n", "office#softpol.eu\n");
// printInvoiceNumber(+numer+);
Date data = new Date();
printInvoiceDate(data);
printInvoiceHeader("|No.|Product desciptrion |Quantity |Unit price |Total |VAT rate |VAT |Gross|");
printInvoiceHeader("|______________________________________________________________________________________________________|");
//printInvoiceProduct("name[i]", ilosc[prod], cena[prod], vat[prod]");
printInvoiceProduct("|" + (i + 1) + " |" + name[i] + " |" + quantity[i] + " |" + price[i] + " |" + (quantity[i] * price[i]) + " |" + (vat[i] / 100.0) + " |" + (quantity[i] * price[i] * (vat[i] / 100.0)) + " |" + (quantity[i] * price[i]) * (1 + (vat[i] / 100.0)));
}
}
}
and my problems:
I have 4 errors like: error: <identifier> expected. It is connected
with arrays but i have no idea what is wrong.
By the last line: printInvoiceProduct.... I want to display 1 product which user entered, but nothing displays.
Why is that?
Create new memory addresses for arrays as you refer them. Like;
static double[] price = new double[ile];
This is also not enough because these static arrays trying to make a static reference to a non-static variable, "ile". So if you want your arrays to be static, just make "ile" static also.
printInvoiceProduct method is declared to pass 4 arguments to it but you've called it by only one String object.
Even if you solve compilation errors you will face again problems.
For example you are creating an array with size zero This will fail. So instead of creating your array objects above; create in the main function after knowing size of array.
So get rid of ile variable. Take input in the main and then instantiate all the array.
Even I don't see a need of class level arrays all can be method local.
On top of that I don't think this is correct platform to solve such problem. Consider putting your problem on
https://codereview.stackexchange.com/

Categories

Resources