Ok, so this test work individually fine, but for some reason, they fail when running together, as you can see, I real a String of values from a File.
When running together, it looks like the app stops reading the commands of the file after a few entries.
Any ideas?
One example of the file text:
10
10
5
5
e
3
3
3
1
5
at the second 3 of the sequence, the app stops reading the values.
All this test work individually.
#TestInstance(TestInstance.Lifecycle.PER_METHOD)
public class MarsRoverTest {
#BeforeEach
public void setUp() {
cleanUpMars();
}
//Test rover's movement
#Test
public void roverSetUp_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_SET_UP_OK)));
MarsRover.main(new String[]{});
assertEquals(RIGHT, Mars.getInstance().getMars()[5][5]);
}
#Test()
public void roverSetUp_OutOfMars() {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_SET_UP_ERROR)));
OutOfMarsException exception = assertThrows(OutOfMarsException.class, () ->
MarsRover.main(new String[]{}));
assertEquals("You set the Rover in the Space!", exception.getMessage());
}
#Test
public void roverMoveAround_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_MOVE_AROUND_OK)));
MarsRover.main(new String[]{});
assertEquals(RIGHT, Mars.getInstance().getMars()[5][0]);
}
//Test rover's rotation
#Test
public void roverRotateUp_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_ROTATE_UP_OK)));
MarsRover.main(new String[]{});
assertEquals(UP, Mars.getInstance().getMars()[4][5]);
}
//Test rover's rotation
#Test
public void roverRotateLeft_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_ROTATE_LEFT_OK)));
MarsRover.main(new String[]{});
assertEquals(LEFT, Mars.getInstance().getMars()[5][4]);
}
//Test rover's rotation
#Test
public void roverRotateDown_OK() throws OutOfMarsException {
System.setIn(new ByteArrayInputStream(getInstructions(ROVER_ROTATE_DOWN_OK)));
MarsRover.main(new String[]{});
assertEquals(DOWN, Mars.getInstance().getMars()[6][5]);
}
private byte[] getInstructions(String path) {
try {
return Files.readString(Path.of(path)).getBytes();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void cleanUpMars() {
Mars.getInstance().setMarsReady(true);
}
Mars is a Singleton instance
public class Mars {
private static Mars INSTANCE;
private int sizeX;
private int sizeY;
private String[][] mars; //Map of Mars
private boolean marsReady = false; //I hade to add this for the testing, needs improvement
private Mars(){
}
public static Mars getInstance() {
if(INSTANCE == null) {
INSTANCE = new Mars();
}
return INSTANCE;
}
Mars class is this:
package org.mars.entities;
import static org.mars.constants.MarsConstants.OBSTACLE;
import static org.mars.utils.ReaderUtils.requestInt;
/**
* Singleton class
*/
public class Mars {
private static Mars INSTANCE;
private int sizeX;
private int sizeY;
private String[][] mars; //Map of Mars
private boolean marsReady = false; //I hade to add this for the testing, needs improvement
private Mars(){
}
public static Mars getInstance() {
if(INSTANCE == null) {
INSTANCE = new Mars();
}
return INSTANCE;
}
public static void removeInstance() {
INSTANCE = null;
}
public int getSizeX() {
return sizeX;
}
public void setSizeX(int sizeX) {
this.sizeX = sizeX;
}
public int getSizeY() {
return sizeY;
}
public void setSizeY(int sizeY) {
this.sizeY = sizeY;
}
public String[][] getMars() {
return mars;
}
public void setMars(String[][] mars) {
this.mars = mars;
}
public boolean isMarsReady() {
return marsReady;
}
public void setMarsReady(boolean marsReady) {
this.marsReady = marsReady;
}
/**
* Define the size of the map for the rover
*/
public static void setMarsSize() {
System.out.println("Insert horizontal map size:");
getInstance().sizeX = requestInt();
System.out.println("Insert vertical map size:");
getInstance().sizeY = requestInt();
getInstance().mars = new String[INSTANCE.sizeX][INSTANCE.sizeY];
if(!getInstance().isMarsReady())
addObstacles();
}
/**
* Shows the map of Mars with the rover and obstacles
*/
public static void printMars(){
for (String[] placeX: INSTANCE.mars) {
System.out.print("|");
for (String placeY: placeX) {
if(placeY != null && !placeY.isBlank())
System.out.print("_" + placeY + "_");
else System.out.print("___");
System.out.print("|");
}
System.out.println();
}
}
/**
* Add obstacles for the mars Map
*/
private static void addObstacles() {
int min = 0;
int numberOfObstacles = (int)(Math.random() * getInstance().sizeX * getInstance().sizeY / 10) + min;
for (int i = 0; i < numberOfObstacles; i++) {
int randomX = (int)(Math.random() * getInstance().sizeX -1) + min;
int randomY = (int)(Math.random() * getInstance().sizeY -1) + min;
getInstance().mars[randomX][randomY] = OBSTACLE;
}
}
}
And the main app:
public static void main(String[] args) throws OutOfMarsException {
try {
reader = new Scanner(System.in);
//Map size configured
setMarsSize();
//Rover initial position
roverCar.setRoverPosition();
//Show mars map
printMars();
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I started to learn java and i cant get past my problem with method getting default vaules from class. The code is about cars and garage. Everything works just as I intended with the execption of returning default values for Samochod s1 instead of the values that were set in the main function.
Main:
public static void main(String[] args) {
Samochod s1 = new Samochod("Fiat", "126p", 2, 650, 6.0);
Samochod s2 = new Samochod("Syrena", "105", 2, 800, 7.6);
Garaz g1 = new Garaz();
g1.setAdres( "ul. Garażowa 1" );
g1.setPojemnosc( 1 );
Garaz g2 = new Garaz("ul. Garażowa 2", 2);
g1.wprowadzSamochod(s1);
g1.wypiszInfo();
g1.wprowadzSamochod(s2);
g2.wprowadzSamochod(s2);
g2.wprowadzSamochod(s1);
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wypiszInfo();
g2.wyprowadzSamochod();
g2.wyprowadzSamochod();
}
package Lab2_02;
public class Samochod {
private String marka;
private String model;
private int iloscDrzwi;
private int pojemnoscSilnika;
private double srednieSpalanie;
private static int iloscSamochodow = 0;
public String getMarka() {
return marka;
}
public String getModel() {
return model;
}
public int getIloscDrzwi() {
return iloscDrzwi;
}
public int getPojemnoscSilnika() {
return pojemnoscSilnika;
}
public double getSrednieSpalanie() {
return srednieSpalanie;
}
public void setMarka(String marka) {
this.marka = marka;
}
public void setModel(String model) {
this.model = model;
}
public void setIloscDrzwi(int iloscDrzwi) {
this.iloscDrzwi = iloscDrzwi;
}
public void setPojemnoscSilnika(int pojemnoscSilnika) {
this.pojemnoscSilnika = pojemnoscSilnika;
}
public void setSrednieSpalanie(double stednieSpalanie) {
this.srednieSpalanie = stednieSpalanie;
}
public Samochod() {
marka = "nieznany";
model = "nieznany";
iloscDrzwi = 0;
pojemnoscSilnika = 0;
srednieSpalanie = 0.0;
iloscSamochodow++;
}
public Samochod(String marka_, String model_, int iloscDrzwi_, int pojemnoscSilnika_, double srednieSpalanie_) {
marka = marka_;
model = model_;
iloscDrzwi = iloscDrzwi_;
pojemnoscSilnika = pojemnoscSilnika_;
srednieSpalanie = srednieSpalanie_;
iloscSamochodow++;
}
public double obliczSpalanie(double dlugoscTrasy) {
double spalanie = (srednieSpalanie * dlugoscTrasy)/100;
return spalanie;
}
public double obliczKosztPrzejazdu(double dlugoscTrasy, double cenaPaliwa) {
double kosztPrzejazdu = obliczSpalanie(dlugoscTrasy) * cenaPaliwa;
return kosztPrzejazdu;
}
public void wypiszInfo() {
System.out.println("Marka: " + marka);
System.out.println("Model: " + model);
System.out.println("Ilosc drzwi: " + iloscDrzwi);
System.out.println("Pojemnosc silnika: " + pojemnoscSilnika);
System.out.println("Srednie spalanie: " + srednieSpalanie);
}
public static void wypiszIloscSamochodow() {
System.out.println("Ilosc samochodow: " + iloscSamochodow);
}
}
package Lab2_02;
public class Garaz {
private String adres;
private int pojemnosc;
private int liczbaSamochodow = 0;
private Samochod [] samochody;
public String getAdres() {
return adres;
}
public int getPojemnosc() {
return pojemnosc;
}
public void setAdres(String adres) {
this.adres = adres;
}
public void setPojemnosc(int pojemnosc) {
this.pojemnosc = pojemnosc;
samochody = new Samochod[pojemnosc];
}
public Garaz() {
adres = "nieznany";
pojemnosc = 0;
samochody = null;
}
public Garaz(String adres_, int pojemnosc_) {
adres = adres_;
pojemnosc = pojemnosc_;
samochody = new Samochod[pojemnosc];
}
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod();
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
public void wyprowadzSamochod() {
if(liczbaSamochodow == 0) {
System.out.println("W garazu nie ma zadnego auta.");
}
else {
samochody [liczbaSamochodow-1] = null;
liczbaSamochodow--;
System.out.println("Samochod zostal wyprowadzony.");
}
}
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
}
}
}
So my problem is that instead of returning in console info about my car "Fiat", it say "nieznany" from default class. I know it is simple problem but i can't get past it for a few days. My problem is with this line:
public void wypiszInfo(){
for(int i = 0; i <= liczbaSamochodow-1; i++){
samochody[i].wypiszInfo();
Instead of showing this:
Samochod zostal wprowadzony.
Marka: nieznany
Model: nieznany
Ilosc drzwi: 0
Pojemnosc silnika: 0
Srednie spalanie: 0.0
I can't make it show this:
Marka: Fiat
Model: 126p
Ilosc drzwi: 2
Pojemnosc silnika: 650
Srednie spalanie: 6.0
In wprowadzSamochod(Samochod s) method you're creating a new Samochod instance, instead of using the one passed as parameter. Since you have a default constructor, you are always using it, setting information to default values:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = new Samochod(); // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
How it should be:
public void wprowadzSamochod(Samochod s) {
if(liczbaSamochodow >= pojemnosc) {
System.out.println("W garazu jest maksymalna ilość pojazdow.");
}
else {
samochody [liczbaSamochodow] = s; // <-- there
liczbaSamochodow++;
System.out.println("Samochod zostal wprowadzony.");
}
}
Just a micro-suggestion: inside the exit condition of a for loop you can just use i < max, instead of i <= max-1 (e.g. in wypiszInfo()).
I need to test the BasketBallGame class, ive written multiple tests who work and now I want to test the final IF statement in the method: public BasketResult play(String category) {}
I have written test for the other two IF statements and used Mockito to mock the ShotAttempt method.
#ParameterizedTest
#CsvSource({ "0, 1,0", "1,1,1", "0, 0,1" })
public void MockShotAttempt(int firstValue, int secondValue, int derdeWaarde) {
Mockito.when(inHoop.ShotAttempt(3)).thenReturn(new int[] {firstValue,secondValue,derdeWaarde});
}
#ParameterizedTest
#NullAndEmptySource
#ValueSource(strings = {" ", "TodDDleR", "LoWWeR","#!|#" })
public void Invalid_EmptyCategory(String category) {
Assertions.assertThrows(IllegalArgumentException.class, () -> {
BasketBallGame.Play(category);
});
}
Now i'm not really sure how I can use the sum of the array value, and the string category in order to test the last IF statement and return a BasketResult.
public class BasketResult {
private final boolean won;
private final int amountInHoop;
BasketResultaat(boolean won, int amountInHoop) {
this.won = won;
this.amountInHoop = amountInHoop;
}
public boolean isWon() {
return won;
}
public int getAmountInHoop() {
return amountInHoop;
}
}
import java.security.SecureRandom;
public class InHoop {
private final SecureRandom random = new SecureRandom();
public int[] shotAttempt(int amountAttempts) {
int[] score = new int[amountAttempts];
for (int index = 0; index < amountAttempts; index++) {
score[index] = random.nextInt(2); // 1 = in hoop, 0 = not in hoop
}
return score;
}
}
import java.util.Arrays;
public class BasketBallGame {
private InHoop inHoop;
private final int AMOUNT_TRIES = 3;
private final String TODDLER = "toddler";
private final String LOWER = "lower";
public BasketBallGame() {
this(new InHoop());
}
public BasketBallGame(InHoop inHoop) {
this.inHoop = inHoop;
}
public double Calculate(int x, double y) {
if (x <= 0 || y < 0)
throw new IllegalArgumentException("x must be stricly positive and y must be positive");
return (AMOUNT_TRIES * 10) - x - y;
}
public BasketResult play(String category) {
if (category == null || category.isBlank()) {
throw new IllegalArgumentException("category must be filled in");
}
if (!categorie.equalsIgnoreCase(TODDLER) && !categorie.equalsIgnoreCase(LOWER)) {
throw new IllegalArgumentException("INVALID category");
}
int[] result = inHoop.shotAttempt(AMOUNT_TRIES);
int amountInHoop = Arrays.stream(result).sum();
// IF toddler And 1x in hoop ==> WIN
// IF LOWER AND 2X IN HOOP ==> WIN
if ((category.equals(TODDLER) && amountInHoop >= 1)
|| (categorie.equals(LOWER) && amountInHoop >= 2)) {
return new BasketResult(true, amountInHoop);
}
// did not win
return new BasketResult(false, amountInHoop);
}
}
Pay attention to #InjectMocks and #Mock.
In addition, the statement initMocks is necessary.
#InjectMocks
BasketBallGame basketBallGame;
#Mock
private InHoop inHoop;
#BeforeEach
void before() {
MockitoAnnotations.initMocks(this);
}
#ParameterizedTest
#CsvSource({
"toddler, '0,0,0', false",
"toddler, '1,0,0', true",
"toddler, '1,1,0', true",
"lower, '1,0,0', false",
"lower, '1,1,0', true",
"lower, '1,1,1', true",
})
public void TestLastIfStatement(String category, String scoreList, Boolean winExp) {
int[] scoreArr = Arrays.stream(scoreList.split(",")).map(String::trim).mapToInt(Integer::parseInt).toArray();
int sumExp = Arrays.stream(scoreArr).sum();
when(inHoop.shotAttempt(anyInt())).thenReturn(scoreArr);
BasketResult result = basketBallGame.play(category);
assertEquals(winExp, result.isWon());
assertEquals(sumExp, result.getAmountInHoop());
}
So, I'm working on a project with a loop (while (true) { //do stuff) and I have values stored in a map (only 2 entries).
First issue: Methods are executing twice (I think it is an issue in the map portion). The VirtualPet.tick and the VirtualPet.feed method is being executed twice per loop.
Second issue: map.get(key) is executing on all keys, not just specified key.
In my main class:
private static VirtualPetShelter shelter = new VirtualPetShelter();
private static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
generatePets();
gameLoop();
}
private static void showPets() {
shelter.showPets();
}
private static void generatePets() {
VirtualPet pet1 = new VirtualPet();
VirtualPet pet2 = new VirtualPet();
shelter.addPet("Max", pet1);
shelter.addPet("Skippy", pet1);
}
private static void gameLoop() {
while (true) {
whatToDo();
shelter.tick();
showPets();
}
}
private static void whatToDo() {
System.out.println("What would you like to do?");
System.out.println("\t 1: Feed");
int response = input.nextInt();
input.nextLine();
switch (response) {
case 1:
feedOptions();
break;
}
}
private static void feedOptions() {
System.out.println("Enter pet name or \"all\" to feed all:");
showPetNames();
String response = input.nextLine();
if (response.toLowerCase().equals("all")) {
shelter.feedAllPets();
} else {
shelter.feedPet(response);
}
}
In my Shelter class:
private Map<String, VirtualPet> pets = new HashMap<>();
public VirtualPetShelter() {
}
public void addPet(String name, VirtualPet pet) {
pets.put(name, pet);
}
public void showPets() {
for (Map.Entry<String, VirtualPet> entry : pets.entrySet())
System.out.println("\t" + entry.getKey() + "\n" +
"\t\tHunger: " + entry.getValue().getHunger());
}
public void showPetNames() {
for (Map.Entry<String, VirtualPet> entry : pets.entrySet())
System.out.println(entry.getKey());
}
public void feedAllPets() {
for (VirtualPet value : pets.values())
value.feed();
}
public void feedPet(String name) {
pets.get(name).feed();
}
public void tick() {
for (VirtualPet value : pets.values())
value.tick();
}
In VirtualPet class:
private int hunger;
public VirtualPet() {
hunger = 5;
}
public int getHunger() {
return hunger;
}
public void feed() {
hunger -= 2;
}
public void tick(){
hunger += 1;
}
I'm doing an assignment in which I have created an Appliance class that has a timePasses()method within it. This method re-directs some values that need to be stored within another method that is inside of another class. Here is where I am up to on this:
Appliance
public class ElectricCooker extends Cooker {
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
#Override
public int currentState() {
if (varPass == 0) {
return isOff;
} else {
return isOn;
}
}
#Override
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
#Override
public void timePasses() {
if (varPass == isOff) {
varPass = 0;
} else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
GasMeter.getInstance().incrementConsumed(gasUse);
WaterMeter.getInstance().incrementConsumed(waterUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
super(electricityUse, gasUse, waterUse, timeOn);
this.electricityUse = 5 * incrementTime;
this.gasUse = 0 * incrementTime;
this.waterUse = 0 * incrementTime;
this.timeOn = 15 * incrementTime;
}
}
Meter
public class ElectricMeter {
ElectricMeter() {
}
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
System.out.println(value);
}
public int incrementGenerated() {
}
public boolean canGenerate() {
}
public String getConsumed() {
}
public String getGenerated() {
}
}
Main method
public class MainCoursework {
public static void main(String[] args) {
ElectricMeter a = new ElectricMeter();
a.incrementConsumed(//what goes here?);
}
}
So the value from timePasses()has been redirected into an ElectricMeter instance but now I need to return that value to the increentConsumed() method in the meter class and I'm stuck on how to do this. Since the value of electricityConsumed is 20, the output should be 20. But instead I have to pass a parameter into a.incrementConsumed(//pass parameter here) and what ever is passed gets printed out onto the screen instead of the 20 from electrictyUse. Any help on how to do this is appreciated, thanks.
Actually, the incrementConsumed method is indeed implemented as you described:
public void incrementConsumed(int value)
{
System.out.println(value);
}
A method called incrementXXX shouldn't really output anything, should it? It should increment a variable/field:
private int electricityUsed = 0;
public void incrementConsumed(int value)
{
electricityUsed += value;
}
You should declare another method that returns electricityUsed:
public int getElectricityUsed() {
return electricityUsed;
}
Now let's fix your main method.
In your main method, you didn't even create anything that consumes electricity! How can the electric meter incrementConsumed? So remove everything from the main method and create a cooker:
// your constructor looks weird. So I passed in some random arguments..
ElectricCooker cooker = new ElectricCooker(20, 0, 0, 60);
Now call timePasses to simulate that some time passed:
cooker.timePasses();
And print the electricity used:
System.out.println(ElectricMeter.getInstance().getElectricityUsed());
you need to create an instance variable in ElectricMeter and update that value on say incrementConsumed. When you want to print that use accessor of this variable.
public class Electric {
public static void main(String[] args) {
ElectricCooker cooker = new ElectricCooker(1,2,3,4);
//opertion on cooker
//ignoring best way for singleton creation
int electricityUse = ElectricMeter.getInstance().getElectricityUse();
System.out.println(electricityUse);
}
}
class ElectricCooker // extends Cooker
{
public int isOn = -1;
public int isOff = 0;
public int incrementTime;
public int varPass = -1;
public int electricityUse = -1;
public int currentState() {
if (varPass == 0)
return isOff;
else {
return isOn;
}
}
public void useTime(int defaultTime) {
defaultTime = 15;
incrementTime = 4;
}
public void timePasses() {
if (varPass == isOff)
varPass = 0;
else {
ElectricMeter.getInstance().incrementConsumed(electricityUse);
}
}
ElectricCooker(int electricityUse, int gasUse, int waterUse, int timeOn) {
this.electricityUse = 5 * incrementTime;
}
}
class ElectricMeter {
public int electricityUse = -1;
private static ElectricMeter instance = new ElectricMeter();
public static ElectricMeter getInstance() {
return instance;
}
public void incrementConsumed(int value) {
this.electricityUse = value;
}
public int getElectricityUse() {
return electricityUse;
}
}
In ElectricMeter, some operations don't perform what they should.
ElectricMeter.getInstance().incrementConsumed(electricityUse);
should increment something but it writes only in the output:
public void incrementConsumed(int value){
System.out.println(value);
}
You should write it rather :
public void incrementConsumed(int value){
consumed+=value;
}
and add a private int consumed field in ElectricMeter class to store the actual consumed.
And your getConsumed() which has a empty implementation :
public String getConsumed(){
}
should simply return the consumed field and you should return a int value and not a String.
public int getConsumed() {
return consumed;
}
In this way, you can do :
public static void main(String[] args){
ElectricMeter.getInstance().incrementConsumed(20);
int consumed = ElectricMeter.getInstance().getConsumed();
}
I'm just learning Java... I have three classes which creates bank account
My first class;
public class Banka {
protected static int pocetUctu = 0;
public Ucet vytvorUcet(Clovek maj, double pocatecni) {
Ucet uc = new Ucet(maj, pocatecni);
pocetUctu++;
System.out.println("Ucet " + uc + " vytvoren");
System.out.println("Pocet uctu " + pocetUctu);
return uc;
}
public static void main(String[] args) {
Banka b1 = new Banka();
Clovek pn = new Clovek("Petr Novotny", 1949);
Clovek jv = new Clovek("Jan Vesely", 1970);
Ucet pu1 = b1.vytvorUcet(pn, 1000);
Ucet pu2 = b1.vytvorUcet(pn, 50000);
Ucet ju = b1.vytvorUcet(jv, 3000);
pu2.prevedNa(ju, 1000);
ju.prevedNa(pu1, 500);
pu1.vypisInfo();
pu2.vypisInfo();
ju.vypisInfo();
}
}
My second class;
public class Clovek {
protected String jmeno;
protected int rokNarozeni;
protected static int pocetLidi = 0;
public Clovek(String j, int rN) {
jmeno = j;
rokNarozeni = rN;
pocetLidi++;
}
public void vypisInfo() {
System.out.println("Clovek:");
System.out.println("Jmeno="+jmeno);
System.out.println("Rok narozeni="+rokNarozeni);
}
}
My third class;
public class Ucet {
static double zustatek;
static Clovek majitel;
public Ucet(Clovek maj, double zus) {
maj = majitel;
zus = zustatek;
}
public void pridej(double pocatecni) {
zustatek += pocatecni;
}
public void vypisZustatek() {
System.out.println(zustatek);
}
public Ucet prevedNa(Ucet kam, float castka) {
zustatek -= castka; // nebo také vhodné je: pridej(-castka);
kam.pridej(castka);
return this;
}
public void vypisInfo() {
System.out.println("Vlastník" + majitel);
System.out.println("Zůstatek" + zustatek);
}
}
pu1.vypisInfo(); should output account owner and his money on it, but It shows owner null and balance 0. Where can be problem ?
Assignment is from right to left
majitel = maj;
zustatek = zus;
You have:
public Ucet(Clovek maj, double zus) {
maj = majitel;
zus = zustatek;
}
But you should have:
public Ucet(Clovek maj, double zus) {
majitel = maj;
zustatek = zus;
}