Im working with a stand-alone class, and a main driver, here's the stand-alone class:
public class Bugs{
private String bugType;
private int legs;
private int arms;
private String nativeTo;
public Bugs(String bt, int l, int a, String nt){
bt=bugType;
l=legs;
a=arms;
nt=nativeTo;
}
public Bugs(String bt, int l, int a){
bt=bugType;
l=legs;
a=arms;
nativeTo="Not known";
}
public String getbt(){
return bugType;
}
public void setbugType(String bugType){
this.bugType=bugType;
}
public int getlegs(){
return legs;
}
public void setlegs(int legs){
this.legs=legs;
}
public int getarms(){
return arms;
}
public void setarms(int arms){
this.arms=arms;
}
public String getnativeTo(){
return nativeTo;
}
public void setnativeTo(String nativeTo){
this.nativeTo=nativeTo;
}
public String toString(){
return bugType + " has " + legs + arms + nativeTo;
}
}
And here's the main driver:
public class myBugs{
public static void main (String args[]){
Bugs asiaBeetle = new Bugs("Asian Beetle", 2, 2, "Japan");
Bugs spider = new Bugs("Spider", 1000, 0);
Bugs americanBeetle = new Bugs("American Beetle", 2, 2, "USA");
System.out.println(asiaBeetle);
}
}
JGRASP keeps returning "null has 00null", every time I run the main driver. What am I doing wrong?
Swap your assignments in your constructors :
public Bugs(String bt, int l, int a, String nt){
bugType = bt;
legs = l;
arms = a;
nativeTo = nt;
}
You have to do the same for the other :
public Bugs(String bt, int l, int a){
bugType = bt;
legs = l;
arms = a;
nativeTo="Not known";
}
Change your constructor to this offcourse do the same for the other as well
public Bugs(String bt, int l, int a, String nt){
bugType=bt;
legs=l;
arms=a;
nativeTo= nt;
}
Related
I have a CSV conversion class. It's job is to muck with values and produce few outputs. The CSV row has around 30 columns. I've modelled via immutable objects:
In(i1, i2, ..., iM)
OutA(a1, a2, ..., aN)
OutB(b1, b2, ..., bO)
...
OutK(k1, k2, ..., kP)
OutX(x1, x2, ..., xQ)
There are inter-dependencies: b1 is the same as a1, b2 is calculated based on a2, they combine to the final result (OutX). Some calculations are expensive.
The end result is a huge method that looks similar to this simplified monster:
OutX method(In in) {
I1 i1 = in.getI1();
I1 i2 = in.getI2();
...
I1 iM = in.getIM();
A1 a1 = fa1(i1, i2);
A2 a2 = fa2(i2, i5, iM);
...
AN aN = ...;
OutA outA = new OutA(
a1,
a2,
...,
aN);
A1 b1 = a1;
B2 b2 = fb2(a2, i5, i13);
...
BO bO = ...;
OutB outB = new OutB(
b1,
b2,
...,
bO);
...
return new OutX(
outA,
outB,
...,
outK);
}
'Tis wonderful being immutable and type-checked and stuff. 'Tis also 300 lines and this is for each "flavor" of CSV. Ugh. Breaking up just creates methods that are mostly parameters + constructor calls.
Are there patterns or libraries to un-Frankenstein this?
The Adapter pattern might be helpful. Each layer/shell delegates as much as possible to build up to the final result. Here's an example:
public class App {
public static void main(String[] args) {
App app = new App();
app.process();
}
private void process() {
In in = new In(1, 2, 3);
OutA a = new OutA(in);
OutB b = new OutB(a);
System.out.println(b);
}
public class In {
private final int i1;
private final int i2;
private final int i3;
public In(int i1, int i2, int i3) {
this.i1 = i1;
this.i2 = i2;
this.i3 = i3;
}
public int getI1() {
return i1;
}
public int getI2() {
return i2;
}
public int getI3() {
return i3;
}
}
public class OutA {
private final In in;
private Integer a3;
public OutA(In in) {
this.in = in;
}
public int getA1() {
return in.getI1();
}
public int getA2() {
return in.getI2() * 2;
}
public int getA3() {
if (a3 == null) {
// a3 = some expensive calculation
a3 = 1; // hold the value to avoid expensive calculation next time method is called
}
return a3;
}
}
public class OutB {
private final OutA a;
public OutB(OutA a) {
this.a = a;
}
public int getB1() {
return a.getA1();
}
public int getB2() {
// a.getA3() is expensive, but only the first time it's called
return a.getA3() + 4;
}
public int getB3() {
// a.getA3() is expensive, but only the first time it's called
return a.getA3() + 9;
}
public String toString() {
return "b1: " + getB1() + " b2: " + getB2() + " b3: " + getB3();
}
}
}
Output: b1: 1 b2: 5 b3: 10
UPDATE: here's a more interesting example using a factory to have different calculations, but still using the same interface.
public class App {
public static void main(String[] args) {
App app = new App();
app.process();
}
private void process() {
In in = new In(1, 2, 3);
OutXFactory factory = new OutXFactory();
OutX resultType1 = factory.create(in, CSVType.TYPE_1);
System.out.println(resultType1);
OutX resultType2 = factory.create(in, CSVType.TYPE_2);
System.out.println(resultType2);
}
public class In {
private final int i1;
private final int i2;
private final int i3;
public In(int i1, int i2, int i3) {
this.i1 = i1;
this.i2 = i2;
this.i3 = i3;
}
public int getI1() {
return i1;
}
public int getI2() {
return i2;
}
public int getI3() {
return i3;
}
}
public enum CSVType {
TYPE_1, TYPE_2;
}
public class OutA {
private final In in;
private Integer a3;
public OutA(In in) {
this.in = in;
}
public int getA1() {
return in.getI1();
}
public int getA2() {
return in.getI2() * 2;
}
public int getA3() {
if (a3 == null) {
// a3 = some expensive calculation
a3 = 1; // hold the value to avoid expensive calculation next time method is called
}
return a3;
}
}
public class OutB {
private final OutA a;
public OutB(OutA a) {
this.a = a;
}
public int getB1() {
return a.getA1();
}
public int getB2() {
// a.getA3() is expensive, but only the first time it's called
return a.getA3() + 4;
}
public int getB3() {
// a.getA3() is expensive, but only the first time it's called
return a.getA3() + 9;
}
}
public interface OutX {
public int getX1();
public int getX2();
public int getX3();
}
public abstract class AbstractOutX implements OutX {
#Override
public String toString() {
return "x1: " + getX1() + " x2: " + getX2() + " x3: " + getX3();
}
}
public class OutXA extends AbstractOutX {
private final OutA a;
public OutXA(OutA a) {
this.a = a;
}
#Override
public int getX1() {
return a.getA1() + 1;
}
#Override
public int getX2() {
return a.getA2() + a.getA3() + 2;
}
#Override
public int getX3() {
return a.getA1() + a.getA2() + 3;
}
}
public class OutXAB extends AbstractOutX {
private final OutA a;
private final OutB b;
public OutXAB(OutA a, OutB b) {
this.a = a;
this.b = b;
}
#Override
public int getX1() {
return a.getA1() + b.getB1();
}
#Override
public int getX2() {
return a.getA2() * b.getB2();
}
#Override
public int getX3() {
return (int) Math.pow(a.getA3(), b.getB3());
}
}
public class OutXFactory {
public OutX create(In in, CSVType type) {
if (type == CSVType.TYPE_1) {
OutA a = new OutA(in);
return new OutXA(a);
} else {
OutA a = new OutA(in);
OutB b = new OutB(a);
return new OutXAB(a, b);
}
}
}
}
I try to:
Create a Car object in the Main.
Send the object as an argument to the carOwners class.
Print the entire carOwners data from main.
Name and Address will be printed, but not the Car.
What is wrong with my code?
public class TestProgram {
public static void main(String [] args){
Car Saab = createCar();
carOwners guy = createCarOwners (Saab);
printAll(guy);
}
public static Car createCar (){
//user input a, b, c, d
Car temporary = new Car (a, b, c, d);
return temporary;
}
public static carOwners createCarOwners (Car x){
//user input a, b
Car c = x;
carOwners temporary = new carOwners (a, b, c);
return temporary;
}
public static void printAll (carOwners x){
x.printCarData();
x.printNameAddress();
}
}
public class Car {
private String model;
private String Year;
private String licensePlate;
private String color;
public Car (String x, int y, String z, String q){
model = x;
Year = y;
licensePlate = z;
color = q;
}
}
public class carOwners {
private String name;
private String address;
private Car TheCar;
public carOwners (String n, String a, Car b){
name = n;
address = a;
TheCar = b;
}
public void printNameAddress(){
System.out.println();
System.out.println(name);
System.out.println(address);
}
public void printCarData(){
System.out.println(TheCar);
}
}
override toString(), so you can custom the output format of Car
public String toString(){
return "Model :" + this.model + ",Year :" + year;
}
Your Problem is here:
public void printCarData(){
System.out.println(TheCar);
}
You want to print an Object. That doens't work because Java uses the toString-Method for that. If you want to do it like that you have to override the toString()-Method of your car class like that:
public String toString()
{
return "CarModel: " + this.model + ", Production Year: " + year;
}
I do not know why the if statement is not working in the program.
When order is greater than bulkorder, it still returns 0.
Do you think there is a problem with the code I have written which is shown below?
public class ShoeStoreOrder{ //ShoeStoreOrder .java
// private method
private String typeofshoe ;
private String season ;
private double cost ;
private int bulkOrderQuantity;
private int discount;
private int order;
//constructor
public ShoeStoreOrder(String t,String s,double c,int b,int d,int o){
typeofshoe = t;
season = s;
cost = c;
bulkOrderQuantity = b;
discount = d;
order = o;
}
//get Method
public String gettypeofshoe(){
return typeofshoe;
}
public String getseason(){
return season;
}
public double getcost(){
return cost;
}
public int getbulkOrderQuantity(){
return bulkOrderQuantity;
}
public int getdiscount(){
return discount;
}
public int getorder(){
return order;
}
//set method
public void settypeofshoe(String t){
typeofshoe=t;
}
public void setseason(String s){
season=s;
}
public void setcost(double c){
cost=c;
}
public void setbulkOrderQuantity(int b){
bulkOrderQuantity=b;
}
public void setorder(int o){
order=o;
}
//other method
//overload method
public double gettotaldiscount(){
if(order()>bulkOrderQuantity()){
return order*cost*(discount/100);
}
else{
return 0;
}
}
public double gettotalamount(){
return order*cost-gettotaldiscount();
}
}
order and bulkOrderQuantity are instance variable and not a method. () are used when calling a method and not when referencing a variable:
if(order()>bulkOrderQuantity()){
change it to
if(order>bulkOrderQuantity){
You have skipped case when order value equals bulkOrderQuantity:
public double gettotaldiscount() {
if (order >= bulkOrderQuantity) {
return order * cost * discount / 100;
} else {
return 0;
}
}
//Check input and results:
public static void main(String[] args) {
ShoeStoreOrder sso;
System.out.println("No discount");
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 1);
System.out.println(sso.gettotalamount());
System.out.println("After discount");
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 5);
System.out.println(sso.gettotalamount());
sso = new ShoeStoreOrder("vertical", "winter", 20, 5, 10, 50);
System.out.println(sso.gettotalamount());
}
Output:
No discount
20.0
After discount
90.0
900.0
When I run javac Hero.java Then java Hero The program spits out tons of lines that look like this:
Hero#322ba3e4
Hero#4f14e777
Hero#65685e30
Hero#26ffd553
Hero#660e5025
Hero#35afe17b
What is this? Hero#322ba3e4
Then it shows,
Exception in thread "main" java.lang.StackOverflowError
at sun.nio.cs.UTF_8.updatePositions(UTF_8.java:77)
at sun.nio.cs.UTF_8$Encoder.encodeArrayLoop(UTF_8.java:564)
at sun.nio.cs.UTF_8$Encoder.encodeLoop(UTF_8.java:619)
at java.nio.charset.CharsetEncoder.encode(CharsetEncoder.java:561)
at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:271)
at sun.nio.cs.StreamEncoder.write(StreamEncoder.java:125)
at java.io.OutputStreamWriter.write(OutputStreamWriter.java:207)
at java.io.BufferedWriter.flushBuffer(BufferedWriter.java:129)
at java.io.PrintStream.write(PrintStream.java:526)
at java.io.PrintStream.print(PrintStream.java:669)
at java.io.PrintStream.println(PrintStream.java:823)
at Hero.DrowRanger(Hero.java:78)
at Hero.DrowRanger(Hero.java:79)
This line repeats 100s of times:
at Hero.DrowRanger(Hero.java:79)
This is the method at that line,
private static Object DrowRanger() {
Hero DrowRanger = new Hero(
0,
"Agility",
"Ranged",
"Frost Arrows",
"Gust",
"Precision Aura",
"Marksmanship",
17,
1.9,
26,
1.9,
15,
1.4,
473,
195,
44,
55,
625,
0.64,
300);
System.out.println(DrowRanger);
return DrowRanger(); // Line 79 Is Here
}
This is the full class
public class Hero implements NPC {
private int level;
private String primaryAttribute;
private String attackType;
private String ability1;
private String ability2;
private String ability3;
private String ability4;
private double strength;
private double strengthMultiplier;
private double agility;
private double agilityMultiplier;
private double intelligence;
private double intelligenceMultiplier;
private int health;
private int mana;
private int damageMin;
private int damageMax;
private int range;
private double armor;
private int movement;
//default constructor
public Hero(
int level,
String primaryAttribute,
String attackType,
String ability1,
String ability2,
String ability3,
String ability4,
double strength,
double strengthMultiplier,
double agility,
double agilityMultiplier,
double intelligence,
double intelligenceMultiplier,
int health,
int mana,
int damageMin,
int damageMax,
int range,
double armor,
int movement
) {
} // End Constructor
public static void main (String[] args) {
DrowRanger();
}
private static Object DrowRanger() {
Hero DrowRanger = new Hero(
0,
"Agility",
"Ranged",
"Frost Arrows",
"Gust",
"Precision Aura",
"Marksmanship",
17,
1.9,
26,
1.9,
15,
1.4,
473,
195,
44,
55,
625,
0.64,
300);
System.out.println(DrowRanger);
return DrowRanger();
}
// getters and setters - required to implement ALL from interface
public int getLevel() {
return this.level;
}
public String getPrimaryAttribute() {
return this.primaryAttribute;
}
public String getAttackType() {
return this.attackType;
}
public String getAbility1() {
return this.ability1;
}
public String getAbility2() {
return this.ability2;
}
public String getAbility3() {
return this.ability3;
}
public String getAbility4() {
return this.ability4;
}
public double getStrength() {
return this.strength;
}
public double getStrengthMultiplier() {
return this.strengthMultiplier;
}
public double getAgility() {
return this.agility;
}
public double getAgilityMultiplier() {
return this.agilityMultiplier;
}
public double getIntelligence() {
return this.intelligence;
}
public double getIntelligenceMultiplier() {
return this.intelligenceMultiplier;
}
public int getHealth() {
return this.health;
}
public int getMana() {
return this.mana;
}
public int getDamageMin() {
return this.damageMin;
}
public int getDamageMax() {
return this.damageMax;
}
public int getRange() {
return this.range;
}
public double getArmor() {
return this.armor;
}
public int getMovement() {
return this.movement;
}
// This is where the setters are.
public void setLevel(int level) {
this.level = level;
}
public void setPrimaryAttribute(String primaryAttribute) {
this.primaryAttribute = primaryAttribute;
}
public void setAttackType(String attackType) {
this.attackType = attackType;
}
public void setAbility1(String ability1) {
this.ability1 = ability1;
}
public void setAbility2(String ability2) {
this.ability2 = ability2;
}
public void setAbility3String(String ability3) {
this.ability3 = ability3;
}
public void setAbility4(String ability4) {
this.ability4 = ability4;
}
public void setStrength(double strength) {
this.strength = strength;
}
public void setStrengthMultiplier(double strengthMultiplier) {
this.strengthMultiplier = strengthMultiplier;
}
public void setAgility(double agility) {
this.agility = agility;
}
public void setAgilityMultiplier(double agilityMultiplier) {
this.agilityMultiplier = agilityMultiplier;
}
public void setIntelligence(double intelligence) {
this.intelligence = intelligence;
}
public void setIntelligenceMultiplier(double intelligenceMultiplier) {
this.intelligenceMultiplier = intelligenceMultiplier;
}
public void setHealth(int health) {
this.health = health;
}
public void setMana(int mana) {
this.mana = mana;
}
public void setDamageMin(int damageMin) {
this.damageMin = damageMin;
}
public void setDamageMax(int damageMax) {
this.damageMax = damageMax;
}
public void setRange(int range) {
this.range = range;
}
public void setArmor(double armor) {
this.armor = armor;
}
public void setMovement(int movement) {
this.movement = movement;
}
} // End Character Class
`
Your DrowRanger method is calling itself infinitely. This is almost always the cause of a StackOverflowException.
This line:
return DrowRanger();
Calls the DrowRanger method, but since you're inside the DrowRanger method it just keeps calling itself infinitely. I think you meant to return the local object:
return DrowRanger;
In general, it is a bad idea to give methods and objects the same name. Also, it is java convention always start method and variable/field names with a lowercase letter.
The output you're seeing is how java prints objects that have not overridden the toString() method. See this post for an explanation of how the toString() method works.
To the first: println prints the output of the toString method of the object. As it is just the normal method inherited by the Object class it just returns the name of the class and the hash of the object.
To your error: it looks like there is an infinite loop somewhere (which has been found).
public class Operations {
private int add;
private int sub;
private int mul;
private int div;
private double sqrt;
public void setadd(int a, int b) {
add = a + b;
}
public void setsub(int a, int b) {
sub = a - b;
}
public void setmul(int a, int b) {
mul = a * b;
}
public void setdiv(int a, int b) {
div = a / b;
}
public void setsqrt(double sqt) {
sqrt = Math.sqrt(sqt);
}
public int getadd() {
return add;
}
public int getsub() {
return sub;
}
public int getmul() {
return mul;
}
public int getdiv() {
return div;
}
public double getsqrt() {
return sqrt;
}
}
Do I have to do a prototype of this or in Java that's not necessary, also how do I use static methods here instead of setter and getter.. I'm trying to do a calculator.. Are my methods ok?
Make all the operations (addition, multiplication, division, etc ) static methods of a Calculator class:
class Calculator{
public static int add(int a, int b){
return a+b;
}
...
I don't really understand the point of setting and getting, why not have your calculator like this:
public class Calculator {
public int add(int a, int b){
return a + b;
}
public int sub(int a , int b){
return a - b;
}
public int mul(int a, int b){
return a * b;
}
public int div(int a, int b){
return a/b;
}
public double sqrt(double sqt){
return Math.sqrt(sqt);
}
Your methods are all wrong, because you modeled your operation incorrectly. It is not supposed to contain its result, and it should do only one operation, not all of them. Operation object should be immutable, and it should produce an answer to a specific operation given two operands. You should separate binary operations from unary as well.
interface BinaryOp {
double calculate(double left, double right);
}
interface UnaryOp {
double calculate(double operand);
}
private static final BinaryOp ADD = new BinaryOp() {
double calculate(double left, double right) {
return left + right;
}
};
private static final BinaryOp SUB = new BinaryOp() {
double calculate(double left, double right) {
return left - right;
}
};
private static final BinaryOp MUL = new BinaryOp() {
double calculate(double left, double right) {
return left * right;
}
};
private static final BinaryOp DIV = new BinaryOp() {
double calculate(double left, double right) {
return left / right;
}
};
private static final UnaryOp SQRT = new UnaryOp() {
double calculate(double operand) {
return Math.sqrt(operand);
}
};
Now you can organize your operators by name:
private static final Map<String,BinaryOp> opByName = new HashMap<String,BinaryOp>();
static {
opByName.put("+", ADD);
opByName.put("-", SUB);
opByName.put("*", MUL);
opByName.put("/", DIV);
}
With this map, you can use your operations to perform calculations for you:
String op = "+";
double left = 123;
double right = 456;
double res = opByName.get(op).calculate(left, right);
Just to answer the part of the question not answered yet:
You do not need prototypes in java.
This looks like a good use for an enum or two:
enum BinOp {
ADD {
#Override
public int eval(int leftArg, int rightArg) {
return leftArg + rightArg;
}
#Override
public String symbol() {
return "+";
}
},
SUBTRACT {
#Override
public int eval(int leftArg, int rightArg) {
return leftArg - rightArg;
}
#Override
public String symbol() {
return "-";
}
}
// etc.
;
public abstract int eval(int leftArg, int rightArg);
public abstract String symbol();
}
And a similar enum for unary operators (only SQRT, at the moment).
You could use these as follows:
int left = 3;
int right = 2;
for (BinOp op : BinOp.values()) {
System.out.println("The value of "
+ left + " " + op.symbol() + " " + right " is "
+ op.eval(left, right)
);
}