I'm very new to Java, and am having trouble with an assignment. For some reason, I'm only getting null. Is there something I did wrong?
public class Dieprint
{
public static void main(String[]args)
{
Die die1 = new Die();
die1.roll();
die1.toString();
die1.print();
}
}
class Die
{
//instance variables
private int faceValue;
private int numSides;
private String faceValue2;
//constructor
public Die()
{
numSides = 6;
faceValue = roll();
}
//accessors
public int getValue() { return faceValue; }
//mutators
public int roll()
{
faceValue = (int)(Math.random()*numSides + 1);
return faceValue;
}
//methods
public String toString()
{
String faceValue2 = ("" + faceValue);
return faceValue2;
}
public String print()
{
System.out.println("Result is: " + faceValue2);
return faceValue2;
}
}
I've tried to make the toString method return faceValue itself, but that didn't work at all.
I'd really appreciate any help with this.
In the method public String toString() what you did is initiate a new variable faceValue2. Even though you already have that variable in your field, when you wrote String faceValue2 = {"" + faceValue) (emphasis on the word String) you are now pointing to a another variable called faceValue2, and it is no longer the faceValue2 in your field.
If you walk through your code, the printing is happening in your print method, where there exists a variable called faceValue2. This variable points towards the faceValue2 in your field, which since it has not been changed in your toString() method is still null. Therefore when you print, you get null.
What you can do to solve this problem is simply remove the keyword String, making your code
public String toString(){
faceValue2 = "" + faceValue;
return faceValue2;
}
This will guarantee that you are changing the variable in your field which will in turn change the variable in your print() method, and therefore, change the output you get after running the code.
Suggestions:
Get rid of the faceValue2 variable and the print() method as they serve no purpose other than to confuse.
Instead, print out the toString result: System.out.println(die1);. This will print out the value returned from Die's toString method.
For example
public class DiePrint {
public static void main(String[] args) {
Die die = new Die();
System.out.println(die);
die.roll();
System.out.println(die);
}
}
class Die {
private static final int DEFAULT_NUM_SIDES = 6;
private int faceValue;
private int numSides;
// default constructor
public Die() {
this(DEFAULT_NUM_SIDES);
}
// if numSides can vary, then have a constructor that will
// allow one to set it.
public Die(int numSides) {
this.numSides = numSides;
roll(); // no need to set numSides when rolling. it's already done
}
// accessors should reflect the field name
public int getFaceValue() {
return faceValue;
}
public int getNumSides() {
return numSides;
}
// mutators
public int roll() {
faceValue = (int) (Math.random() * numSides + 1);
return faceValue;
}
// methods
public String toString() {
String faceValue2 = ("" + faceValue);
return faceValue2;
}
}
Related
I need to know:
Why can't I pass maxSpeed to method as an int rather than Integer?
Why does it work using "getMaxSpeed.equals(speed)" method but can't compare less than/greater than? (I think because of maxSpeed being Integer rather than int, right?). The code doesn't compile with compareTo.
I need to get a list of all cars with maxSpeed greater than 'speed', how do I do this?
How can I return not only the name(BMW, Mercedes) but also the engineCc?
Tried using both normal operators for primitives and methods for objects.
enum CarData {
BMW (230, 3000),
Mercedes (220, 2500);
private int maxSpeed;
private int engineCc;
CarData (int maxSpeed, int engineCc) {
this.maxSpeed = maxSpeed;
this.engineCc = engineCc;
}
Integer getMaxSpeed(){
return maxSpeed;
}
int getEngineCc() {
return engineCc;
}
public static CarData getByMaxSpeed (int speed) {
for (CarData carData : CarData.values()){
if (carData.getMaxSpeed() => speed)
return carData;
}
return null;
}
}
public class VehicleInfo {
public static void main (String [] args){
System.out.println (CarData.getByMaxSpeed(200));
}
}
Expected result is "BMW, Mercedes" or "3000, 2500", whichever one I need.
int is a primitive data type in Java.
Integer is a wrapper class. You can't compare instances of a wrapper class (like Integer) in the same way you do with primitives, with Integer you have to use methods, with primitives it is simpler.
For the output try overriding the toString method in your enum, this toString method is inherited from the Object class.
The complete class would be
enum CarData {
BMW(230, 3000),
Mercedes(220, 2500);
private int maxSpeed;
private int engineCc;
/* This method was added/overwritten */
#Override
public String toString() {
return name() + ", Cc: " + engineCc;
}
CarData(int maxSpeed, int engineCc) {
this.maxSpeed = maxSpeed;
this.engineCc = engineCc;
}
Integer getMaxSpeed() {
return maxSpeed;
}
int getEngineCc() {
return engineCc;
}
public static CarData getByMaxSpeed(int speed) {
for (CarData carData : CarData.values()) {
//Here I replaced the => by >=
if (carData.getMaxSpeed() >= speed) {
return carData;
}
}
return null;
}
}
public class VehicleInfo {
public static void main(String[] args) {
System.out.println(CarData.getByMaxSpeed(200));
}
}
}
And the output:
BMW, Cc: 3000
If you want a different string just customize the return in the toString method, also you have to replace the => by >= to make the comparison.
Hope this helps.
I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}
I'd appreciate it if anyone could help. Just what seems like a novice question but I can't figure it out.
I have 3 classes Class1, Class2, UseClass.
In Class1 I have a get/set method (COST is used elsewhere in Class1 but not in those methods)
int class1Num;
final double COST = 120;
public int getNum()
{
return class1Num;
}
public void setNum(int newNum)
{
class1Num = newNum;
}
In Class2 I have a final variable and a normal variable and another get/set method.
Class2 extends Class1.
final double FINALNUM = 50;
double totalNum;
public double getTotalNum()
{
return totalNum;
}
public void setTotalNum(int class1Num)
{
totalNum = COST * getNum() + FINALNUM;
}
public void display()
{
System.out.println("Final Number: " + getTotalNum() );
}
Basically what I need to do is I need to in Class2. First multiply COST by the getNum() method from Class1 and then add FINALNUM to that total. This is just my recent attempt but I've tried adding FINALNUM in the system.out to no avail (although multiplication works fine for some reason).
display() is called in the UseClass to output the final result.
I have no other ideas and not exactly sure what I'm looking for when searching online so I figured asking here may help
Any help would be great
Thanks.
According to your statements, the classes are following I guess:
public class Class1 {
int class1Num;
final double COST = 120;
public int getNum()
{
return class1Num;
}
public void setNum(int newNum)
{
class1Num = newNum;
}
}
public class Class2 extends Class1{
final double FINALNUM = 50;
double totalNum;
public double getTotalNum()
{
return totalNum;
}
public void setTotalNum(int class1Num)
{
// Note: need assign field member "class1Num" inherited from Class1.
// Otherwise, it will be zero and cause incorrect value of getNum()
totalNum = COST * getNum() + FINALNUM;
}
public void display()
{
System.out.println("Final Number: " + getTotalNum() );
}
}
The problem is that "setTotalNum(int class1Num)" doesn't assign class1Num which inherited from Class1. You can call "setNum(class1Num);" before" totalNum = COST * getNum() + FINALNUM;"
public class Class2 {
...
public void setTotalNum(int class1Num) {
setNum(class1Num);
totalNum = COST * getNum() + FINALNUM;
}
....
}
I am trying to use the Die class when writing a PairOfDice class. Here is the Die class:
public static class Die {
private final int MAX = 6;
private int faceValue;
public Die()
{
faceValue = 1;
}
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
public void setFaceValue(int value)
{
if(value > 0 && value <= MAX)
faceValue = value;
}
public int getFaceValue()
{
return faceValue;
}
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
Now what I am trying to do is to use this class to write a similar class called PairOfDice. I want similar methods of rolling the dice, setting the face value, and so on. However I have never done this before so I'm not sure how to approach this. Here is what I have so far:
public static class PairOfDice {
Die die1 = new Die();
Die die2 = new Die();
public PairOfDice()
{
????
}
public int rollPair()
{
????
}
}
I'm not sure how to appropriately use these objects. Please keep in mind I am a beginner in java/programming.
You don't appear to need anything in the constructor, you've initialized the die fields where you declared them. Just call them in your method. Something like,
public int rollPair()
{
return die1.roll() + die2.roll();
}
I have a problem with the inheritance of classes.
here is my Java code:
public class spaarRekening extends rekening{
private double rente;
public double getRente(){
return rente;
}
spaarRekening(String rN, int s, double d){
super(rN, s);
rente = d;
}
spaarRekening sR = new spaarRekening("456", 999999, 2.5);
}
public static class rekening implements rekeningIF{
int saldo;
static String rekeningNummer;
rekening(String rN, int s){
rekeningNummer = rN;
saldo = s;
}
public static String getRekeningNummer(){
return rekeningNummer;
}
public int getSaldo(){
return saldo;
}
}
I want to let the spaarRekening be printed out by:
System.out.printf("Uw rekeningnummer is: %s\n", spaarRekening.getRekeningNummer());
But it prints out null.
Why is this?
Thanks.
Don't use static. Not until you understand how it works and where it is applicable.
Since you never create any object of type spaarRekening or rekening the variable rekeningNummer never gets initialized, because you do intialization inside the constructor.
You most probably want to make your rekeningNummer non-static when you initialize it inside the constructor.
When you really want it to be static then you should initialize it in a static way, too. Therefore remove the code from the constructor and initialize it right away when declaring.
public class SpaarRekening extends Rekening{
private double rente;
SpaarRekening(String rN, int s, double d){
super(rN, s);
rente = d;
}
public double getRente(){
return rente;
}
public static void main(String[] args) {
SpaarRekening sR = new SpaarRekening("456", 999999, 2.5d);
System.out.println(sR.getRekeningNummer());
}
}
public class Rekening implements RekeningIF{
protected int saldo;
protected String rekeningNummer;
Rekening(String rN, int s){
rekeningNummer = rN;
saldo = s;
}
public String getRekeningNummer(){
return rekeningNummer;
}
public int getSaldo(){
return saldo;
}
}
Your rekeningNummer is a static variable and of typeObject and in your code. The variable has not been intialized, hence it printed null.
You have to initialize the static variable before using it:
public static class Rekening implements RekeningIF{
int saldo;
static String rekeningNummer = ""; // initialized to empty String
Rekening(String rN, int s){
rekeningNummer = rN;
saldo = s;
}
public static String getRekeningNummer(){
return rekeningNummer;
}
// Provide method for setting value of rekeningNumber
public static void setRekeningNumber(String number) {
rekening.rekeningNummer = number;
}
public int getSaldo(){
return saldo;
}
}
You never initialize rekeningNummer, and the default value is null.
You never initialized the rekeningNummer, you may think that the statement spaarRekening sR = new spaarRekening("456", 999999, 2.5);within yourspaarRekening class will initialize it, but you are putting it within class definition, you are not actually instantiating any spaarRekening instance. Remove that statement, and instantiating it at some other places in your code