Java- Integer in program not being updated - java

Recently, I've been assigned to do a file by my teacher to make a program that simulates a TV.
I am supposed to add volume when the raiseVolume method is called. However, upon calling it, it looks like volume is not being affected whatsoever.
I have no clue as to why this could be.
(myTv is the object of the constructor in Tv)
Here is the Code for the TV Driver Class-
System.out.println ("Crank it up!");
int oldVolume = myTv.getVolume();
do {
oldVolume = myTv.getVolume();
myTv.raiseVolume();
} while (myTv.getVolume() != oldVolume);
System.out.println ("\t\tThe TV is " + myTv.getPower() +
" on channel " + myTv.getChannel() +
" at volume " + myTv.getVolume());
System.out.println ("That's a bit too loud");
myTv.lowerVolume();
myTv.lowerVolume();
and here is my code for the Tv Class-
private int volume = 0;
...
//Volume
public int getVolume(){
return volume;
}
public void raiseVolume(){
volume+=5;
}
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
If you need additional code, I will post it!
I've been called out for putting entire classes in here before, I don't wish to make the same error!

Because when you call lowerVolume after raiseVolume:
public void lowerVolume(){
volume-=1;
if (volume > 0){
volume = 0;
}
}
it will always set the volume to 0, as volume > 0 (at least 5) at that moment, you should change it to:
if (volume < 0){
volume = 0;
}

The two values will never be equal, and your while loop just terminates. Print the volume before and after the call and you'll see that it changes (assuming you're using the code you've posted)
System.out.printf("oldVolume = %d%n", myTv.getVolume());
myTv.raiseVolume();
System.out.printf("newVolume = %d%n", myTv.getVolume());
Also, your lowerVolume method always sets volume to 0 (if it's greater than zero). I think you mean less than
public void lowerVolume(){
volume--; // <-- does - 1
if (volume < 0){ // <-- less than
volume = 0;
}
}
It might be a good idea to add a max for raiseVolume(). Finally, I suggest you set the increment (and decrement) to be the same value (or pass that value in to the method); that is something like
private static final int MAX_VALUE = 100;
private static final int MIN_VALUE = 0;
public void lowerVolume(int change) {
volume -= change;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume(int change) {
volume += change;
volume = Math.min(volume, MAX_VALUE);
}
Or,
public void lowerVolume() {
volume--;
volume = Math.max(volume, MIN_VALUE);
}
public void raiseVolume() {
volume++;
volume = Math.min(volume, MAX_VALUE);
}

try something along the lines of a start volume of 0 so when you getVolume you can write in something like
if(tv.getvolume == 0){
volume++
}

Related

The "if" condition in "set" method isn't working

So which floor the lift is on should be able to be read and changed, but only within the allowed range for just that house the lift is installed in. I'm trying to get an "If" condition working looking for a boolean true value from method "validFloor".
Based on my very beginner knowledge of Java, I assume putting an "If" condition in the set-method is a proper attempt?
private int currentFloor = 0;
private int numberOfFloors;
private boolean validFloor = false;
public Elevator(int numberOfFloors) {
this.numberOfFloors = numberOfFloors;
}
//Sets the allowed number of floors (0 to 100)
public void allowedNumberOfFloors() {
if (numberOfFloors < 2) {
numberOfFloors = 2;
} else if (numberOfFloors > 100) {
numberOfFloors = 100;
}
}
//Checks validity of the elevator floor in relation to total floors.
public void validFloor() {
if (currentFloor > numberOfFloors && currentFloor < 0) {
this.validFloor = false;
}
}
//Checks whether the specified floor is in reasonable range.
public void setFloor(int currentFloor) {
if (validFloor) {
this.currentFloor = currentFloor;
}
}
public int getFloor() {
return currentFloor;
}
public String toString() {
return "Number of floors: " + numberOfFloors + "\nCurrent floor: " + currentFloor;
}
For example, if you try to move the lift to floor 74 in a house that only has 5 floors, it should not work. I want the hiss to start at bottom floor 0, hence the 0 value in class variable "currentFloor".
The If condition in the "validFloor" method doesn't seem to be recognized at all. Instead all that matters is the boolean value I put on the class variable validFloor.
You never call the validFloor() method, so the value of validFloor is never changed. Also, you code never sets validFloor to true anywhere, so it wouldn't even matter if you called validFloor(), because it can only set validFloor to false, or leave it at the initial value of false.
The "correct" way to do something like this is:
public boolean isValidFloor(floor) {
// It seems weird to me that 0 is a valid floor. Is that correct?
// If floors are zero-indexed, the top floor should actually be numberOfFloors-1.
return floor >= 0 && floor <= this.numberOfFloors;
}
public void setFloor(int newFloor) {
if (isValidFloor(newFloor)) {
this.currentFloor = newFloor;
}
}
Notice that there's no need to even keep around a validFloor variable. We can just check whether or not a floor is valid every time we need to without saving the result.

System.out.println doesn't show text in console (IntelliJ)

I am writing a program which part is presented below:
public class Portal {
private String name;
private int[] positions; // positions of "ship"
private static int moves = 0; // moves made by player to sink a ship
public static int shot; // the value of position given by player
private int hits = 0; // number of hits
private int maxSize = 4; // max size of ship (the size will be randomized)
int first; // position of 1st ship block
int size; // real size of ship (randomized in setPortal method)
public void checkIfHit(){
for (int i : positions){
if (i == shot){
System.out.println("Hit confirmed");
hits++;
} else if (hits == positions.length){
System.out.println("Sunk");
} else {
System.out.println("Missed it");
}
}
moves++;
}
public void setPortal(){
size = 1 + (int)Math.random()*maxSize;
for (int i = 0; i < size - 1; i++){
if (i == 0){
positions[i]= 1 + (int)Math.random()*positions.length;
first = positions[i];
System.out.println(positions[i]);
continue;
}
positions[i]= first + 1;
System.out.println(positions[i]);
}
}
}
public class Main{
public static void main(String[] args){
// write your code here
Portal p1 = new Portal();
p1.setPortal();
}
}
code is split in two Java .class files.
The problem I'm dealing with is that using p1.setPortal(); doesn't show up text in IntelliJ console. The program works though and returns 0.
I don't have such problem in another program when I've put System.out.println in method other than main (also in separate class file).
What may be the cause of such issue?
It should properly throw an exception, because you forgot to initialize the integer array.
Have a look at this thread: Do we need to initialize an array in Java?
The Java's default value is null for an integer array. So your for wont even loop trough. The only thing that wonders me is why there is no exception..

How to recover the stored value in the preferences libgdx

My save:
static final String PREFS_NAME = "ScoreGame";
Preferences preferences;
one variable temp
to output to the Class A
**Preferences preferences;**
int tempGameScore = 0;//class B
int dropsGatchered = 0;
**in create**
preferences = Gdx.app.getPreferences(Drop.PREFS_NAME);
in game scene i make this , class B
if ((raindrop.y < 0) && !(index >= 15)) {
iter.remove();
game.tempGameScore = game.dropsGatchered;
game.preferences.putInteger("score", game.tempGameScore);
game.preferences.flush();
game.dropsGatchered = 0;
stopGame();
}
Class C
I get the value and draw on the screen
#Override
public void create() {
game.tempGameScore = game.preferences.getInteger("score");
}
textFont.draw(game.batch, " " + game.tempGameScore, (Drop.WIDTH / 2) - 55,
(Drop.HEIGHT / 2) + 50);
When I close the app that my speed is lost and I want her to recover their variable game.tempGameScore
Your code and the comment seem disjointed. Why are you doing a getInteger("Save"), that doesn't line up with your code of putInteger("score").
In create(), you initialize your preferences, that is fine:
game.preferences = Gdx.app.getPreferences(Drop.PREFS_NAME);
But your get/put need to line up. They work like a hashmap, so you have to use the same key.
game.tempGameScore = game.preferences.getInteger("score");
Then later, to "save":
game.preferences.putInteger("score", game.tempGameScore);
game.preferences.flush();

How to add different arraylist variables together into a single variable in a while loop?

So I have a list of doubles that I am trying to add up. I am rather new to Java so this might be a dumb question: how do I return the arraylist's doubles together in a single variable? Any help is appreciated :)
public double totalVolume(){
double volume = 0;
if (cList.size() != 0) {
volume = cList.get(0).volume();
}
else {
return 0;
}
int indexVolume = 0;
while (indexVolume < cList.size()) {
if (!(indexVolume < cList.get(indexVolume).volume())) {
volume = cList.get(indexVolume).volume();
}
// how do I take volume and add it to itself after each while loop?
indexVolume++;
}
return volume;
}
Are you just trying to keep a running total?
You could just type this:
volume = volume + cList.get(indexVolume).volume();
or, shorter,
volume += cList.get(indexVolume).volume();

How would I store the health values and run again until either player health == 0 or enemy health == 0

What would be the best way for me to code the the actual attack / defend between the two characters and how would I store the health value so that re attacks could be stored until either player health or enemy health reached 0, and then declare the victor. This is my first ever attempt at any kind programming after self teaching from various sources, please also give me feed back on any improvement I could make, I'm sure there will be many.
Thank you in advance.
:-)
package test;
public class BattleClass {
public static void main(String[] args) {
PlayerStats ps = new PlayerStats();
EnemyStats es = new EnemyStats();
int eh = es.getEnemyHealth();
int ph = ps.getPlayerHealth();
ps.PlayerAttackDefend();
es.AttackDefend();
System.out.println("You chose to " + ps.getpInput() + " and rolled "
+ ps.getPlayerRoll());
System.out.println("The enemy chose to " + es.getEaod()
+ " and rolled " + es.getEnemyRoll() + ".");
if (ps.getpInput().equals("Attack")) {
if (es.getEaod().equals("Attack")) {
System.out
.println("YOUR SWORDS BOUNCE OFF EACHOUTHERS... TRY AGAIN!");
System.exit(0);
}
if (es.getEaod().equals("Defend")) {
if (ps.getPlayerRoll() > es.getEnemyRoll())
eh -= ps.getPlayerRoll() - es.getEnemyRoll();
System.out.println("Enemy Health is " + eh);
}
}
if (ps.getpInput().equals("Defend")) {
if (es.getEaod().equals("Defend")) {
System.out
.println("YOUR SHIELDS BOUNCE OFF EACHOTHERS... TRY AGAIN!");
System.exit(0);
}
}
if (es.getEaod().equals("Attack")) {
if (es.getEnemyRoll() > ps.getPlayerRoll())
ph -= es.getEnemyRoll() - ps.getPlayerRoll();
System.out.println("Your Health is " + ph);
}
}
}
package test;
import java.util.Random;
import java.util.Scanner;
public class PlayerStats {
static Scanner paod = new Scanner(System.in);
//Players initial health value.
private int playerHealth = 10;
//RNG for attack value / defence value using dice as object.
private int playerRoll = new Random().nextInt(6) + 1;
private String pInput;
//Method for selecting Attack or Defence.
public void PlayerAttackDefend() {
System.out.println("Do you want to Attack or Defend?");
System.out.println("a = Attack / d = Defend");
//Player selects attack or defend.
String userInput = paod.nextLine();
if (userInput.equals("a")) {
pInput = "Attack";
}
if (userInput.equals("d")) {
pInput = "Defend";
}
}
public static Scanner getPaod() {
return paod;
}
public int getPlayerHealth() {
return playerHealth;
}
public int getPlayerRoll() {
return playerRoll;
}
public String getpInput() {
return pInput;
}
public static void setPaod(Scanner paod) {
PlayerStats.paod = paod;
}
public void setPlayerHealth(int playerHealth) {
this.playerHealth = playerHealth;
}
public void setPlayerRoll(int playerRoll) {
this.playerRoll = playerRoll;
}
public void setpInput(String pInput) {
this.pInput = pInput;
}
}
package test;
import java.util.Random;
public class EnemyStats {
//Enemy initial health value.
private int enemyHealth = 10;
//RNG for attack value / defence value using dice as object.
private static int enemyRoll = new Random().nextInt(6) + 1;
//RNG for enemy decision to Attack or Defend.
private static int eAttackDefend = new Random().nextInt(2) + 1;
//Used for returning attack or defend string.
private static String eaod;
//Attack or Defend method.
public void AttackDefend() {
if (eAttackDefend == 1) {
eaod = "Attack";
} else {
eaod = "Defend";
}
}
public int getEnemyHealth() {
return enemyHealth;
}
public int getEnemyRoll() {
return enemyRoll;
}
public int geteAttackDefend() {
return eAttackDefend;
}
public String getEaod() {
return eaod;
}
public void setEnemyHealth(int enemyHealth) {
this.enemyHealth = enemyHealth;
}
public void setEnemyRoll(int enemyRoll) {
EnemyStats.enemyRoll = enemyRoll;
}
public void seteAttackDefend(int eAttackDefend) {
EnemyStats.eAttackDefend = eAttackDefend;
}
public void setEaod(String eaod) {
EnemyStats.eaod = eaod;
}
}
An easy way would to be to set maxHp and actualHp values, if you want to be able to "heal".
If you just decrease until one is dead, you can just decrease the actual health variable you already have.
You might wanna take a look at Inheritance in general, as you have a lot of duplicate code.
In general, just make a loop
while(ps.getHealth() > 0 && es.getHealth() > 0) {
// your battle code
}
you might want to remove the System.exit(0) calls, as they terminate the program.
Add to the player/enemy a dealDamage(int damage) method to actually be able to reduce their health
The health values should be in the objects, and you should not need to store them in your BattleClass.
I could give you the short answer but I guess you get more out of a detailed explanation :-)
You want to run your code "until either player health or enemy health reached 0" so you need a loop.
In java you have 3 kinds of loops:
The for loop
for(int i=1;i<=3;i++) System.out.println("Hello Musketeer Nr. "+i);
The most elaborate loop, the for loop consists of three parts, the initialization, the condition, and the afterthought. While the for loop can be used differently, it is mostly is used in the fashion shown here, that is, you have a counter variable whose value you need somehow.
If you don't need the counter variable value, you can use the short form with collections and arrays:
for(Person p: persons) System.out.println("Hello, "+person.getName()+"!");
The while loop
The second most commonly used (at least by me) loop, it has an initial condition and iterates, as long as it is true.
while(ph>0&&eh>0)
{
...
}
As you see, it fits your problem very well. For completeness, I will however describe the third loop which is the
do-while loop
do
{
...
}
while(ph>0&&eh>0)
You use this loop like the while loop but if you want to have at least one run through.
Other Remarks
Why have two classes PlayerStats and EnemyStats in combat system (they both seem to have the same actions and values) ? You could just have:
Stats playerStats=new Stats();
Stats enemyStats=new Stats();

Categories

Resources