Java - Store the changing int variable - java

So I'm trying to write the most simple game , everytime "the monster" attacks "the player" I want the variable "int totalHealth" to be lowered .
public void attack(Player somePlayer) {
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
int remainingHealth = totalHealth - damage;
if (remainingHealth == 0 || remainingHealth < 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
System.out.println("Your remaining health is - " + (remainingHealth - somePlayer.getStrength()));
}
}
But the problem is that variable "remainingHealth" stays same , only the first time when I run the code it lowers , every next time it stays same, I guess the problem is in this line :
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
I guess everytime I run the code
somePlayer.getHitpoints()
takes the inserted integer from constructor and that's the problem.
I need to figure out the way to store the remaining health in a variable somehow
Player class :
public class Player implements ISavable{
private String name;
private int hitPoints ;
private int strength ;
private String weapon;
private int damage;
private int totalHealth = hitPoints + strength;
public Player(String name, int damage , int hitPoints , int strength) {
this.name = name;
this.damage = damage;
this.weapon = "Sword";
this.hitPoints = hitPoints;
this.strength = strength;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHitPoints() {
return hitPoints;
}
public void setHitPoints(int hitPoints) {
this.hitPoints = hitPoints;
}
public int getStrength() {
return strength;
}
public void setStrength(int strength) {
this.strength = strength;
}
public String getWeapon() {
return weapon;
}
public void setWeapon(String weapon) {
this.weapon = weapon;
}
public int getTotalHealth() {
return totalHealth;
}
public void setTotalHealth(int totalHealth) {
this.totalHealth = totalHealth;
}
#Override
public String toString() {
return "Player{" +
"name='" + name + '\'' +
", hitPoints=" + hitPoints +
", strength=" + strength +
", weapon='" + weapon + '\'' +
'}';
}
#Override
public List<String> write() {
List<String> values = new ArrayList<String>();
values.add(0, this.name);
values.add(1, "" + this.hitPoints);
values.add(2, "" + this.strength);
values.add(3, "" + this.weapon);
values.add(4,"" + this.damage);
return values;
}
#Override
public void read(List<String> savedValues) {
if (savedValues != null && savedValues.size()>0){
this.name = savedValues.get(0);
this.hitPoints = Integer.parseInt(savedValues.get(1));
this.strength = Integer.parseInt(savedValues.get(2));
this.weapon = savedValues.get(3);
}
}
public void attack(Monster someMonster){
int health = someMonster.getHitPoints();
int remainingHealth = health - damage;
if (remainingHealth == 0 || remainingHealth < 0) {
System.out.println("You killed the monster !!!");
} else {
System.out.println("You attacked the monster " + " and made " + this.damage + " damage");
System.out.println("Monsters remaining health is - " + remainingHealth);
}
if (someMonster.isDead()){
this.hitPoints = 100;
this.strength = 50;
}
}
public void healPlayer(Player somePlayer){
int hp = somePlayer.getHitPoints();
hp += 10;
System.out.println("You healed the player for 10hp , your current hp is " + hp);
}
}

You are not updating the value of totalHealth, you initialize it everytime that attack() method is called, so you always have the same Health.
You can solve it putting out of the attack() method the line:
int totalHealth = somePlayer.getHitPoints() + somePlayer.getStrength();
EDIT:
public void attack(Player somePlayer) {
somePlayer.totalHealth = somePlayer.totalHealth - this.damage;
if (somePlayer.totalHealth.equals(0) || somePlayer.totalHealth < 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked " + somePlayer.getName() + " and made " + this.damage + " damage");
System.out.println("Your remaining health is - " + (somePlayer.totalHealth - somePlayer.getStrength()));
}
}

On Player create a function updateHealth(int newHealth) that sets the variable returned from getHitPoints() to newHealth. Then just append somePlayer.updateHealth(somePlayer.getHitPoints() - damage); at the end of the attack function.

You should have a representation of health, defining in Player totalHealth.
You may use a method which calculate the total health (cause your player could get an item that increases strenght or an item that allow heal you).
Then you should use another variable in Player, remainingHealth and initialize it as remainingHealth = totalHealth
public class Player {
float totalHealth;
float remainingHealth;
...
public Player(...) {
this.remainingHealth = this.totalHealth;
...
}
...
}
When you want decrease the health of your player you should use remainingHealth.
public void attack(Player somePlayer) {
somePlayer.remainingHealth -= this.damage;
if (somePlayer.remainingHealth <= 0) {
System.out.println("Your player died");
} else {
System.out.println("The monster attacked ...");
System.out.println("Your remaining health is - " + somePlayer.remainingHealth);
}
}

Related

im trying to have the player move to one square to another square and take turns and have the properties have those affects and im really stuck?

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class Monopoly {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
Player p1 = new Player();
p1.Player("","",0,1500);
System.out.println("please enter your name:");
String newName = input.nextLine();
p1.setName(newName);
System.out.println("the name is " + p1.getName());
System.out.println("please enter your token: ");
String newToken= input.nextLine();
p1.setToken(newToken);
System.out.println("the token is " + p1.getToken());
System.out.println("your location is "+p1.getLocation());
System.out.println("your balance is "+p1.getBalance());
System.out.println(p1);
Player p2 = new Player();
p2.Player("","",0 ,1500);
System.out.println("please enter your name:");
String NewName = input.nextLine();
p2.setName(NewName);
System.out.println("please enter your token: ");
String coolToken= input.nextLine();
p1.setToken(coolToken);
System.out.println("the token is " + p2.getToken());
System.out.println("your location is "+p2.getLocation());
System.out.println("your balance is "+p2.getBalance());
System.out.println(p2);
int die1;
int die2;
die1 = (int)(Math.random()*6) + 1;
die2 = (int)(Math.random()*6) + 1;
int roll = die1 + die2;
int roll2 = die1 + die2;
System.out.println("here are your rolls: "+ roll);
System.out.println("Here is the rolls for player 2: " + roll2);
// Array of 40 monopoly squares
BoardSquare[] square = new BoardSquare[40];
for (int i = 0; i < square.length; i++) {
loadArray(square);
if( roll == 2 && roll2 == 2){
p1.setLocation(i++ - 38);
p2.setLocation(i++ - 38);
System.out.println("Here is the location for the first player" );
}
else if (roll == 4 && roll2 == 4){
p1.setLocation(i++ - 36);
p2.setLocation(i++ - 36);
System.out.println("Here is the location for the first player" );
}
else if (roll == 5 && roll2 == 5){
p1.setLocation(i++ - 35);
p2.setLocation(i++ - 35);
System.out.println("Here is the location for the first player" );
}
else if (roll == 6 && roll2 == 6){
p1.setLocation(i++ - 34);
p2.setLocation(i++ - 34);
System.out.println("Here is the location for the first player" );
}
else if (roll == 7 && roll2 == 7){
p1.setLocation(i++ - 33);
p2.setLocation(i++ - 33);
System.out.println("Here is the location for the first player" );
}
else if (roll == 8 && roll2 == 8){
p1.setLocation(i++ - 32);
p2.setLocation(i++ - 32);
System.out.println("Here is the location for the first player" );
}
else if (roll == 9 && roll2 == 9){
p1.setLocation(i++ - 31);
p2.setLocation(i++ - 31);
System.out.println("Here is the location for the first player" );
}
else if (roll == 10 && roll2 == 10){
p1.setLocation(i++ - 30);
p2.setLocation(i++ - 30);
System.out.println("Here is the location for the first player" );
}
else if (roll == 11 && roll2 == 11){
p1.setLocation(i++ - 29);
p2.setLocation(i++ - 29);
System.out.println("Here is the location for the first player" );
}
else if (roll == 12 && roll2 == 12){
p1.setLocation(i++ - 28);
p2.setLocation(i++ - 28);
System.out.println("Here is the location for the first player" );
}
}
}
// Method to load the BoardSquare array from a data file
public static void loadArray(BoardSquare[] square) {
// declare temporary variables to hold BoardSquare properties read from a file
String inName;
String inType;
int inPrice;
int inRent;
String inColor;
try {
// Create a File class object linked to the name of the file to be read
File squareFile = new File("squares.txt");
// Create a Scanner named infile to read the input stream from the file
Scanner infile = new Scanner(squareFile);
for (int i = 0; i < 40; i++) {
// Read data from the file into temporary variables.
// Read Strings directly; parse integers.
inName = infile.nextLine();
inType = infile.nextLine();
inRent = Integer.parseInt(infile.nextLine());
inPrice = Integer.parseInt(infile.nextLine());
inColor = infile.nextLine();
// initialize each square with the BoardSquare constructor
square[i] = new BoardSquare(inName, inType, inPrice, inRent, inColor);
}
infile.close();
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
System.exit(1);
}
}
}
heres the player class
package edu.ccp.csci111;
public class Player {
private String name;
private String token;
private int location = 0;
private int balance = 1500;
public void player(){
}
public void Player(String name,String token,int location,int balance){
this.name = name;
this.token =token;
this.location = location;
this.balance = balance;
}
public String getName() {
return name;
}
public String getToken() {
return token;
}
public int getLocation() {
return location;
}
public int getBalance() {
return balance;
}
public void setName(String name) {
this.name = name;
}
public void setToken(String token) {
this.token = token;
}
public void setLocation(int newlocation) {
this.location = newlocation;
}
public void setBalance(int newbalance) {
this.balance = newbalance;
}
public String toString() {
return "Player" + " There name is = " + name + " " + ", token= ' " + token + " " + ", location= " + location + " that's the location, balance= " + balance + " that's the balance";
}
}
here is the bordersquare class
package edu.ccp.csci111;
/**
* Class to create a monopoly board square.
*/
class BoardSquare {
private String name; // the name of the square
private String type; // property, railroad, utility, plain, tax, or toJail
private int price; // cost to buy the square; zero means not for sale
private int rent; // rent paid by a player who lands on the square
private String color; // many are null; this is not the Java Color class
// Constructors
public BoardSquare() {
name = "";
type = "";
price = 0;
rent = 0;
color = "";
}
public BoardSquare(String name, String type, int price, int rent, String color) {
this.name = name;
this.type = type;
this.price = price;
this.rent = rent;
this.color = color;
}
// Accesors for each property
public String getName() {
return this.name;
}
public String getType() {
return this.type;
}
public int getPrice() {
return this.price;
}
public int getRent() {
return this.rent;
}
public String getColor() {
return this.color;
}
// A method to return the BoardSquare's data as a String
public String toString() {
return ("Property: " + this.name + ", Type: " + this.type +
", Price: " + this.price + ", Rent: " + this.rent +
", Color: " + this.color);
}
}
so basically what im trying to do is make two players move from one square to another and im really stuck and i try using while loops within the for loops i have my dice and players and board i just need to find away to make the turns and just away for each of the players go one at time and play the game properly can anyone help me ?

Making specific moves in a turn based fighting game

I'm trying to make a turn based fighting game in Java Eclipse. Right now there's nothing wrong with my code but I just needed help figuring out a way to add multiple attacks to each of my characters in the game.
This is my main method
public class Main {
public static Random generator = new Random();
public static void main(String[] args) {
String answer = "yes";
while(answer.equals("yes")) {
Character player1 = new Wraith();
Character player2 = new Paladin();
Scanner charInput = new Scanner(System.in);
System.out.println("Player1, Choose your character");
String choice = charInput.nextLine();
if(choice.equals("Paladin")) {
player1 = new Paladin();
}
if(choice.equals("Wizard")) {
player1 = new Wizard();
}
if(choice.equals("Wraith")) {
player1 = new Wraith();
}
System.out.println("Player2, Choose your character");
String choice2 = charInput.nextLine();
if(choice2.equals("Paladin")) {
player2 = new Paladin();
}
if(choice2.equals("Wizard")) {
player2 = new Wizard();
}
if(choice2.equals("Wraith")) {
player2 = new Wraith();
}
//player1.name = input("Player1 pick your character(Paladin, Wraith, Wizard)", charInput);
//player2.name = input("Player2 pick your character(Paladin, Wraith, Wizard)", charInput);
System.out.println(player1.name + " vs. " + player2.name);
System.out.println(player1.health + " vs. " + player2.health);
while (player1.isAlive() && player2.isAlive()) {
System.out.println(player1.name + ": " + player1.health);
System.out.println(player2.name + ": " + player2.health);
int damage;
damage = player1.attack(player2);
System.out.println(player1.name + " hits " + player2.name + " for " + damage);
damage = player2.attack(player1);
System.out.println(player2.name + " hits " + player1.name + " for " + damage);
}
if(player1.isAlive()) {
System.out.println(player1.name + " wins!");
} else if (player2.isAlive()) {
System.out.println(player2.name + " wins!");
} else {
System.out.println("It's a draw!");
}
}
}
private static String input(String string, Scanner charInput) {
return null;
}
}
This is one of my character classes
public class Wizard extends Character {
public int dexterity = 25;
public static Random generator = new Random();
public Wizard(){
super();
this.name = "Wizard";
this.strength = 10;
this.defense = 8;
this.health = 95;
}
public int attack(Character target){
boolean criticalHit =Main.generator.nextInt(150) < dexterity;
int damage = this.strength * 2;
if(criticalHit){
damage *= 2;
System.out.println("*** Critical Hit ***");
}
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
}```
And this is my main character class
public class Character {
public String name;
public int strength;
public int health;
public int defense;
public int takeDamage(int damage){
int damageTaken = damage - this.defense;
this.health -= damageTaken;
return damageTaken;
}
public int attack(Character target){
int damage = this.strength * 2;
int damageDealt = target.takeDamage(damage);
return damageDealt;
}
public boolean isAlive(){
return health > 0;
}
}```
also I'm new to coding and stack overflow so and suggestions on how to make my posts make more sense or something like that is much appreciated
nice implemention of a battle system.
when a Character performs an attack you choose which attack that should be and execute:
public int attack(Character target){
AttackMode mode = determineAttackMode(target); // the charater chooses what kind of attack he will execute during this attack
switch(mode){
case AttackMode.DOUBLESTRIKE: return attackDoubleStrike(target);
case AttackMode.BURST: return attackBurst(target);
default: return attackDefault(target); // your previously implemented method attack(target)
}
}
The AttackMode is an Enum class:
enum AttackMode {DEFAULT, DOUBLESTRIKE, BURST}
i'm not sure how double damage is dealt, so this is a guess here
public int attackDoubleStrike(Character target){
int firstStrike = attackDefault(target);
int secondStrike = attackDefault(target);
return firstStrike + secondStrike;
}

Simple turn-based game fight system

I am a beginner in Java. I am making a basic turn-based game, but I have problems with the fight system. I attack the randomly selected enemy with the chosen weapon until it dies, however I can't figure out how to decrease my HP.
I tried the following method in the Character class:
public void attack(int damageAmount, int myHealth) {
if (damageAmount >= this.health || myHealth<=0) {
this.health = 0;
System.out.println( this.name + " is dead!");
this.dead = true;
} else {
this.health -= damageAmount;
System.out.println("The remaining life of " + this.name + " is: " + this.health);
player.setHealth(myHealth-this.damage);
System.out.println("Your remaining HP: "+ myHealth);
It doesn't work, because the " player.setHealth()" is not reachable in the Character class.
How could I solve this? Should I make another class for the fight system?
Also, canI make my code simplier by using inheritance or interfaces?
Thanks in advance guys!
MAIN CLASS
package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static int size = 0;
public static void main(String[] args) {
int myHealth = 1000;
int myDamage = 5;
Scanner sc = new Scanner(System.in);
Character zombie = new Character("Zombie", 500, 10);
Character wolf = new Character("Wolf", 200, 30);
Character dragon = new Character("Dragon", 1000, 200);
Character bigDragon = new Character("Big Dragon", 2000, 400);
Character vampire = new Character("Vampire", 1000, 250);
ArrayList<Character> characterList = new ArrayList<>();
characterList.addAll(Arrays.asList(
zombie,
wolf,
dragon,
bigDragon,
vampire
));
Weapon fist = new Weapon("Fist", 5);
Weapon sword = new Weapon("Sword", 50);
Weapon bow = new Weapon("Bow", 40);
Weapon crossBow = new Weapon("Crossbow", 35);
Weapon revolver = new Weapon("Revolver", 100);
ArrayList<Weapon> weaponList = new ArrayList<>();
weaponList.addAll(Arrays.asList(
fist,
sword,
bow,
crossBow,
revolver
));
size = characterList.size();
int whichCharacter = random();
for (int i = 0; i < characterList.size(); i++) {
System.out.println((i + 1) + ". character: " + characterList.get(random()).getName());
}
System.out.println("Your name!");
String myName = sc.nextLine();
Character player = new Character(myName, 1000, myDamage);
System.out.println("Your name: " + myName);
System.out.println("Your HP: " + myHealth);
System.out.println("Your attack power: " + myDamage);
System.out.println();
System.out.println();
System.out.println("You were attacked by a(n):");
System.out.println("Name: " + characterList.get(whichCharacter).getName());
System.out.println("HP: " + characterList.get(whichCharacter).getHealth());
System.out.println("Attack power: " + characterList.get(whichCharacter).getDamage());
System.out.println();
System.out.println("You attack with...");
System.out.println();
System.out.println("1. fist");
System.out.println("2. sword");
System.out.println("3. bow");
System.out.println("4. crossbow");
System.out.println("5. revolver");
int choice = sc.nextInt();
while (!characterList.get(whichCharacter).isDead()) {
switch (choice) {
case 1:
myDamage = 5;
break;
case 2:
myDamage = sword.getWeaponDamage();
break;
case 3:
myDamage = bow.getWeaponDamage();
break;
case 4:
myDamage = crossBow.getWeaponDamage();
break;
case 5:
myDamage = revolver.getWeaponDamage();
break;
default:
myDamage = 5;
}
while (!characterList.get(whichCharacter).isDead()) {
characterList.get(whichCharacter).attack(myDamage, myHealth);
//characterList.get(whichCharacter).attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
}
}
}
public static int random() {
int szam = (int) (Math.random() * size);
return szam;
}
}
CHARACTER CLASS
package com.company;
/**
* Created by Norbi on 2017.04.29..
*/
public class Character {
private String name;
private int health;
private int damage;
private boolean dead = false;
public boolean isDead() {
return dead;
}
public void setDead(boolean dead) {
this.dead = dead;
}
public Character(boolean dead) {
this.dead = dead;
}
public Character(String name, int health, int damage) {
this.name = name;
this.health = health;
this.damage = damage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public int getDamage() {
return damage;
}
public void setDamage(int damage) {
this.damage = damage;
}
public void attack(int damageAmount, int myHealth) {
if (damageAmount >= this.health || myHealth<=0) {
// this.health = 0;
System.out.println(this.name + " is dead!");
this.dead = true;
} else {
this.health -= damageAmount;
System.out.println("The remaining life of " + this.name + " is: " + this.health);
System.out.println("Your remaining HP: "+ myHealth);
}
}}
WEAPON CLASS
package com.company;
/**
* Created by Norbi on 2017.04.29..
*/
public class Weapon {
private String name;
private int weaponDamage;
public Weapon(String name, int weaponDamage) {
this.name = name;
this.weaponDamage = weaponDamage;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getWeaponDamage() {
return weaponDamage;
}
public void setWeaponDamage(int weaponDamage) {
this.weaponDamage = weaponDamage;
}
}
I have made some changes in looping logic, I hope it would help :
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
switch (choice) {
case 1:
myDamage = 5;
break;
case 2:
myDamage = sword.getWeaponDamage();
break;
case 3:
myDamage = bow.getWeaponDamage();
break;
case 4:
myDamage = crossBow.getWeaponDamage();
break;
case 5:
myDamage = revolver.getWeaponDamage();
break;
default:
myDamage = 5;
}
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
characterList.get(whichCharacter).attack(myDamage, myHealth);
player.attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
//characterList.get(whichCharacter).attack(characterList.get(whichCharacter).getDamage(), player.getHealth());
}
}
Since you need an instance of player to call its methods, you could pass it as an input parameter, for example you could call the attack method like this:
characterList.get(whichCharacter).attack(player);
and modify it like this (simply replacing damageAmount and myHealth with the corresponding methods from Character):
public void attack(Character characterAttacked) {
if (characterAttacked.getDamage() >= this.health || characterAttacked.getHealth() <= 0) {
this.health = 0;
System.out.println( this.name + " is dead!");
this.dead = true;
} else {
this.health -= characterAttacked.getDamage();
System.out.println("The remaining life of " + this.name + " is: " + this.health);
characterAttacked.setHealth(characterAttacked.getHealth() - this.damage);
System.out.println("Your remaining HP: "+ characterAttacked.getHealth());
}
}
As I tried to prepare an answer with a suggestion for a working attack method I found out, that your attack method does not work for me.
So here some general suggestions to improve your code:
Use an instance of Character for the player too.
pass that instance to the attack method.
Improve the use of lists (I will add an example below.)
use a Map with the user entered number as key instead of the switch statement.
Improved use of lists:
// Use the generic interface List instead of implementation class.
// You don't need extra ArrayList, just use the result of Arrays.asList
// - if you don't need to change the list afterwards.
List<Character> characterList =
Arrays.asList(
zombie,
wolf,
dragon,
bigDragon,
vampire);
Use Map for weapons:
Map<Integer, Weapon> weapons = new HashMap<>();
weapons.put(1, fist);
weapons.put(2, sword);
// and so on - you get the idea
while (!characterList.get(whichCharacter).isDead() && !player.isDead()) {
Weapon weapon = weapons.get(choice);
if (null == weapon) {
weapon = fist;
}
myDamage = weapon.getDamage();
// and here you can continue your code
}
Hope that above suggestions also help you a bit further.

How to get the total of each column

Its been a ridiculous task especially to build the total of each vertical column & to show it on screen. Though, calculating the total of horizontal row never seemed to be a challenge.
The problem I'm having is three-fold.
How do I calculate the total of each vertical column ?
The index (id) is getting printed in descending order. How do I make it print in ascending order ?
Further, in the percentage column the value after the decimal point is being discarded. How do I get that displayed? For eg.. if
answer is supposed to be 78.25% it exhibits as 78.0%
P.S : (2 places after the decimal point is what I'm aiming at.)
POJO class -- StudentsProg.java
package com.students.marks;
import java.util.Arrays;
public class StudentsProg {
private int id = 0;
private String name;
private int english;
private int german;
private int french;
private int arabic;
private double percentage;
private int total_marks;
private int rowHighest;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getEnglish() {
return english;
}
public void setEnglish(int english) {
this.english = english;
}
public int getGerman() {
return german;
}
public void setGerman(int german) {
this.german = german;
}
public int getFrench() {
return french;
}
public void setFrench(int french) {
this.french = french;
}
public int getArabic() {
return arabic;
}
public void setArabic(int arabic) {
this.arabic = arabic;
}
public double getPercentage() {
return percentage;
}
public void setPercentage(double percentage) {
this.percentage = percentage;
}
public int getTotal_marks() {
return total_marks;
}
public void setTotal_marks(int total_marks) {
this.total_marks = total_marks;
}
public int getRowHighest() {
return rowHighest;
}
public void setRowHighest(int rowHighest) {
this.rowHighest = rowHighest;
}
public String toString() {
id = id+1;
return (id + "\t" +name+ "\t\t" +english+ "\t" + " " +german+ "\t" + " "+ french+ "\t" + " " +arabic+ "\t" +" " +total_marks+ "\t\t" + " " +percentage+ "\t\t" +rowHighest);
}
}
StudentsProgMain.java
import java.util.Scanner;
public class StudentsProgMain {
#SuppressWarnings("resource")
public static void main(String[] args) {
int count = 0;
StudentsProg[] stud = new StudentsProg[15];
int choice=0;
int max = 0;
Scanner scanner = new Scanner(System.in);
do{
System.out.println("1: Add new Student");
System.out.println("2: List Student");
System.out.println("3: List Student By Name.");
System.out.println("4: Delete Student");
System.out.println("5: Exit");
System.out.println("Please enter your choice \n\n");
choice=scanner.nextInt();
switch(choice){
case 1:
stud[count] = new StudentsProg();
System.out.println("Enter student name");
stud[count].setName(scanner.next());
System.out.println("Enter marks in English");
stud[count].setEnglish(scanner.nextInt());
System.out.println("Enter marks in German");
stud[count].setGerman(scanner.nextInt());
System.out.println("Enter marks in French");
stud[count].setFrench(scanner.nextInt());
System.out.println("Enter marks in Arabic");
stud[count].setArabic(scanner.nextInt());
count++;
break;
case 2:
System.out.println("ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i=0; i<count; i++){
if(stud[i]!=null){
int total_marks = stud[i].getEnglish()+stud[i].getGerman()+ stud[i].getFrench()+stud[i].getArabic();
stud[i].setTotal_marks(total_marks);
double calc_per = ((total_marks*100)/400);
stud[i].setPercentage(calc_per);
int arrayListMarks [] = {stud[i].getEnglish(), stud[i].getFrench(), stud[i].getGerman(), stud[i].getArabic()};
max = arrayListMarks[0];
for (int j = 1; j < arrayListMarks.length; j++) {
if(arrayListMarks[j] > max)
max = arrayListMarks[j]; }
stud[i].setRowHighest(max);
System.out.println(stud[i].toString());
System.out.println("\n");}
}
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
System.out.println("\tTotal :" +"\n");
break;
case 3 :
System.out.println("Please enter your name");
String name = scanner.next();
System.out.println("\n" + "ID\t" + "Name \t\t\t" + "English\t" + " " + "German\t"+ " " + "French\t" + " " + "Arabic\t"
+" "+ "Total Marks\t" + " " + "Percentage\t" + "Highest Marks(Row)\n" +
"------------------------------------------------------------------------"
+ "------------------------------------------- \n ");
for(int i =0 ; i<count; i++){
if(stud[i]!=null && stud[i].getName().equals(name))
System.out.println(stud[i].toString()); }
System.out.println("--------------------------------------------------------------"
+ "----------------------------------------------------- \n");
break;
case 4 :
System.out.println("Please enter your name");
String naam = scanner.next();
for (int i = 0; i<count; i++) {
if(stud[i]!=null && stud[i].getName()==naam)
stud[i]=null;
}
break;
case 5:
System.exit(0);
System.out.println("You have exited successfully");
default :
System.out.println("Invalid choice");
}
}while(true);
}
}
The problem with the percentage calculation is that the line of code double calc_per = ((total_marks*100)/400); will do integer arithmetic and truncate each intermediate result as an integer. To fix this you need to include a floating point number somewhere in the calculation either by converting total_marks to double like so:
double calc_per = ((Integer.valueOf(total_marks).doubleValue()*100)/400);
Or using a float constant like so:
double calc_per = ((total_marks*100.0)/400);
Vertical totals should just be a matter of adding the row value to a variable inside your print loop.
I'm not really sure about your index order problem but the code in toString() that reads id = id+1; looks wrong. This will increment the Id each time you call toString(). Instead of that, your creation code should set the value of id just after creating the object, something like:
stud[count] = new StudentsProg();
// add the following line of code.
stud[count].setId(count);
System.out.println("Enter student name");
stud[count].setName(scanner.next());

Polymorphism and instanceof

I have programed a Worker and MachineWorker class. It complies fine. but when i run it, after three consecutive statements the program stops. I cannot find the problem, and I dont know how and when to use 'instanceof'.
I am writing the question below and with all the classes...
Question:- (i)Declare an array that can store the references of up to 5 Worker or MachineWorker objects.
a)Allow user to enter the type of object and the data for that type of object(3 values for Worker and 4 values for MachineWorker).
b)Construct the appropriate object storing the reference in the common array.
ii)Now allow the users to enter the weekly data repeatedly. If it is Worker object user must enter ID and hours-worked. If it is a MachineWorker object user must enter ID,hoursWorked and pieces. Once these values read search through the array to locate the object with the given ID before calling the addWeekly().The number of arguments either(1 or 2) to be passed to addWeekly depends on the type of objects being referred. To determine the type of object being referred(Worker or MachineWorker)you may use the instanceof operator.
Please see my codes below:-
//Worker.java
public class Worker {
public final double bonus=100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked,tax,grossSalary,netSalary;
public Worker(){
}
public Worker(String name, String workerID, double hourlyRate){
this.name = name;
this.workerID = workerID;
this.hourlyRate = hourlyRate;
}
public void addWeekly(double hoursWorked){
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross(){
grossSalary = (totalHoursWorked*hourlyRate);
if(totalHoursWorked>=150){
grossSalary = grossSalary +100;
}
return grossSalary;
}
public double netAndTax(){
netSalary = grossSalary;
if(grossSalary>500){
tax = (grossSalary - 500) *0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName(){
return this.name;
}
public String getWorkerID(){
return this.workerID;
}
public double getHourlyRate(){
return this.hourlyRate;
}
public double getTotalHours(){
return totalHoursWorked;
}
public double getGrossSalary(){
return grossSalary;
}
public void addToGross(double amt){
grossSalary = grossSalary + amt;
}
public void displaySalary(){
System.out.print("Name: " +getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate()+ "\nTotalHours Worked" + getTotalHours() +
"\nGross pay" + getGrossSalary() + "\nTax: " + netAndTax() +
"\nNet Pay: " + netAndTax());
}
}
//MachineWorker.java
public class MachineWorker extends Worker{
private double targetAmount;
private double totalPieces, productivityBonus;
public MachineWorker(String workerName, String workerID, double hourlyRate, double targetAmount)
{
super(workerName, workerID, hourlyRate);
//this.productivityBonus = productivityBonus;
this.targetAmount = targetAmount;
}
public void addWeekly(double hoursWorked, double weeklyAmount)
{
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus()
{
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross()
{
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if(totalHoursWorked >= 150)
{
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt)
{
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
public void displaySalary()
{
System.out.println("Name " + super.name + "\nID " +
super.workerID + "\nHourly rate " + super.hourlyRate + "\nTotal Hours Worked " +
super.totalHoursWorked + "\nGross Pay $" + super.grossSalary + "\nTax $" + super.tax + "\nNetpay $" + super.netSalary);
System.out.println("Productivity Bonus " + productivityBonus);
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers
{
public static void main(String args[])
{
Scanner input = new Scanner(System.in);
Worker[] a = new Worker[5];
MachineWorker[] b = new MachineWorker[5];
char option = '0';
String choice;
boolean nChar = false;
for (int i = 0; i < 5; i++){
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1)
{
option = choice.charAt(0); //pick the first character
if (option == 'w' || option == 'W')
{
System.out.println("\n\tEnter name, ID and hours: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
a[i] = new Worker(name, id, hours);
System.out.println();
}
if (option == 'm' || option == 'M')
{
System.out.print("\n\tEnter name, ID, hours and pieces: ");
String name = input.nextLine();
System.out.print(" ");
String id = input.nextLine();
System.out.print(" ");
double hours = input.nextDouble();
System.out.print(" ");
double pieces = input.nextDouble();
b[i] = new MachineWorker(name, id, hours, pieces);
System.out.println();
}
System.out.print("\tType of object " + (i+1) + " [W/M]: ");
choice = input.nextLine();
}
a[i].displaySalary();
b[i].displaySalary();
b[i].productivityBonus();
}
}
}
You might want to use overriden methods readfromInput and displaySalary to distinguish between what Worker and Machinworker does.
The different behaviour should be implemented within the classes and not in the calling Polyworker class.
If Machineworker displaySalary shows the bonus this should be called in displaySalary of MachineWorker
see modified code below
//Worker.java
import java.util.Scanner;
/**
* a generic worker
*/
public class Worker {
public final double bonus = 100;
protected String name, workerID;
protected double hourlyRate, totalHoursWorked, tax, grossSalary, netSalary;
public void addWeekly(double hoursWorked) {
this.totalHoursWorked = this.totalHoursWorked + hoursWorked;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate);
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + 100;
}
return grossSalary;
}
public double netAndTax() {
netSalary = grossSalary;
if (grossSalary > 500) {
tax = (grossSalary - 500) * 0.3;
netSalary = (grossSalary - tax);
}
return netSalary;
}
public String getName() {
return this.name;
}
public String getWorkerID() {
return this.workerID;
}
public double getHourlyRate() {
return this.hourlyRate;
}
public double getTotalHours() {
return totalHoursWorked;
}
public double getGrossSalary() {
return grossSalary;
}
public void addToGross(double amt) {
grossSalary = grossSalary + amt;
}
public void displaySalary() {
System.out.print("Name: " + getName() + "\nID :" + getWorkerID()
+ "\nHourly Rate: " + getHourlyRate() + "\nTotalHours Worked"
+ getTotalHours() + "\nGross pay" + getGrossSalary() + "\nTax: "
+ netAndTax() + "\nNet Pay: " + netAndTax());
}
public void readFromInput(Scanner input) {
name = input.nextLine();
System.out.print(" ");
this.workerID= input.nextLine();
System.out.print(" ");
this.totalHoursWorked = input.nextDouble();
System.out.println();
}
} // Worker
//MachineWorker.java
import java.util.Scanner;
public class MachineWorker extends Worker {
private double targetAmount;
private double totalPieces, productivityBonus;
public void addWeekly(double hoursWorked, double weeklyAmount) {
totalHoursWorked = hoursWorked + totalHoursWorked;
totalPieces = weeklyAmount + totalPieces;
}
public double productivityBonus() {
productivityBonus = 100 + (totalPieces - targetAmount);
return productivityBonus;
}
public double gross() {
grossSalary = (totalHoursWorked * hourlyRate) + productivityBonus;
if (totalHoursWorked >= 150) {
grossSalary = grossSalary + bonus;
}
return grossSalary;
}
public void addToGross(double amt) {
amt = productivityBonus;
grossSalary = grossSalary + amt;
}
#Override
public void displaySalary() {
super.displaySalary();
System.out.println("Productivity Bonus " + productivityBonus);
}
#Override
public void readFromInput(Scanner input) {
super.readFromInput(input);
this.totalPieces = input.nextDouble();
}
}
//Polymorphism PolyWorker.java
import java.util.*;
public class PolyWorkers {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
Worker[] workers = new Worker[5];
char option = '0';
String choice;
for (int i = 0; i < 5; i++) {
System.out.print("\tType of object " + (i + 1) + " [W/M]: ");
choice = input.nextLine();
if (choice.length() == 1) {
option = choice.toLowerCase().charAt(0); // pick the first character
switch (option) {
case 'w': {
workers[i] = new Worker();
System.out.println("\n\tEnter name, ID and hours: ");
}
break;
case 'm': {
System.out.print("\n\tEnter name, ID, hours and pieces: ");
}
break;
} // switch
workers[i].readFromInput(input);
}
workers[i].displaySalary();
}
}
}
Your question states that you have to store the references in a common array, where as you are storing them in 2 different arrays a and b. As you have different arrays for different type of objects, you don't have the need to use instanceOf operator. More about instanceOf is here.
Also, you do not check for null while printing salary or bonus. As at any point of the loop, only one type of object will be created, one of a[i] or b[i] will be definitely null, causing a NullPointerException.
You need another loop after the one you have already written that will allow the user to input the worker's hours. This will presumably be a while loop that will continually ask for input. You would then choose some sort of input that would quit the loop. Inside the loop you ask for hours and take either 2 or 3 arguments.
At the moment you are not storing your Workers/MachineWorkers. You need to create an array to store them in. You also need to create either a base class or an interface that they will both extend/implement. This will allow you to create a single array to store them all.
You then loop through your array of Workers/MachineWorkers and when you find a matching id you use your instanceof to work out whether you need to pass 1 or 2 arguments. If it is a MachineWorker you should cast it as such and then call the appropriate method with 2 arguments.

Categories

Resources