Hi im a newbie in java programmer also a freshman in our university. I am currently practicing my java program and ran into a problem which is i dont know how to put up the code in which I have an object as parameter and wanting to have a value.
public int transferTo(Account another, int amount)
{
if (amount<=balance)
// I dont know how to use the object another to have the value of amount put into the object.
// another = amount; it causes a compiler error
}
hoping for the insightful responds <3
Your transferTo(Account another, int amount) method will do something like this.
public int transferTo(Account another, int amount) throws Exception{
if(another==null){
throw new NullPointerException("To Account Cannot be Null");
}
if(this.getBal()> amount){
this.setBal(this.getBal() - amount);
another.setBal(another.getBal() + amount);
}else{
throw new InsufficientFundsException("Insufficient funds! for " + this.id + ": " + this.name );
}
return this.getBal(); // return total balance of account;
}
You can create a class called InsufficientFundsException.class and declare is like this
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String msg){
super(msg);
}
}
You use the parameter object just like you would a local object. You should check if the parameter is null before using it.
public int transferTo(Account another, int amount) {
if (another == null) {
return 0;
}
if (another.hasEnough(amount)) {
another.subtractFromBalance(amount);
}
....
}
Related
Is setter method only use to assigning values? or can we perform operations in it. Here in this code the commented part is giving me correct output but while using set and get I am getting output as 0.
I want to avoid calling totalMarksOfStudent() method again and again because it have 5 parameters which I dont want to give again and again. So what is the way to return totalMarksStudent in another class without calling totalMarksOfStudent().
int totalMarksStudent = 0;
public void setMarks(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
}
public int getMarks(){
return totalMarksStudent;
}
// public int totalMarksOfStudent(int englishMarks, int mathsMarks, int physicsMarks, int chemistryMarks, int csMarks) {
// totalMarksStudent = englishMarks + mathsMarks + physicsMarks + chemistryMarks + csMarks;
// return totalMarksStudent;
}
public String displayTotalMarks() {
String totalMarks1 = "Name " + name + "\tRoll No " + rollNo + "\tTotal Marks " + getMarks();//totalMarksOfStudent(englishMarks, mathsMarks, physicsMarks, chemistryMarks, csMarks);
return totalMarks1;
}
Better to avoid that...
I think it's better to have some fields like your parameters in setMarks (englishMarks , mathsMarks , ...) , and give value to them in constructor or setter methods. Also it's better to have a method named something like calculateTotalMarks , and call it without any parameters whenever you need it. Remember that there will be no problem to have operations in setter methods but usually and for better designed program we avoid that. Methods should do the thing their name says : for example , setter just for assigning , getter just for accessing values , calculateTotalMarks for calculating the total marks and so on ...
setter method is usually used to assigning values. It is promise.
You can reduce parameters by using Object
I recommend to make object of MarksStudent. because common attribute can bind to one class. It make understand easily code
for example
// Java is object-oriented language
class marksStudents {
private int english;
private int math;
private int physics;
private int chemistry;
private int cs;
//getMethods is Abbreviation
public int getTotal() {
return english+math+physics+chemistry+cs;
}
//setMethods
public void setEnglish(int english) {
this.english = english;
}
public void setMath(int math) {
this.math = math;
}
public void setPhysics(int physics) {
this.physics = physics;
}
public void setChemistry(int chemistry) {
this.chemistry = chemistry;
}
public void setCs(int cs) {
this.cs = cs;
}
}
To execute
public class Main{
public static void main(String[] args) {
// You can make object marksStudents of studentsA
marksStudents studentsA = new marksStudents();
studentsA.setChemistry(20);
studentsA.setEnglish(30);
studentsA.setMath(40);
studentsA.setCs(50);
studentsA.setPhysics(60);
//200
System.out.println(studentsA.getTotal());
// You can make object marksStudents of studentsB too
marksStudents studentsB = new marksStudents();
studentsB.setChemistry(10);
studentsB.setEnglish(10);
studentsB.setMath(10);
studentsB.setCs(10);
studentsB.setPhysics(10);
//50
System.out.println(studentsB.getTotal());
}
}
The getter/setter method is only a practice. Not bad practice - it just defines a class, whose instances for the external world are handled by a list of independent values. Using them makes your code better comprehensible and easy to understand, what is it doing.
So it is no problem to make other operations with it, in general.
Some frameworks like to use reflection to use getters/setters and also reach the variables directly in them. In these cases, doing any different in the getters/setters than reading/writing the private members is no wise idea. Sometimes you can use a little bit of api/impl interface trickery to handle this problem.
I am trying to write a method which does not take any arguments and then returns a double variable. It is a postcode identifier so when a cost code is entered certain post codes need to return a double.
In my example below i need post codes that start with either "GH6 TXX" or "NC4 LXX". (X stands for any random character or digit) to return 50.0.
If any other postcode is entered then return 100.0.
However i am not getting any results back and just finding errors. I'm sure i have gone massive wrong somewhere as im not great with If Else statements within methods. Any help or knowledge on this would be great!
public class multiPostcodeRange {
//Declaring Variables
String pcode;
public multiPostcodeRange()
{
pcode = "XXX XXX";
}
public void multiPostcodeRange()
{
if (pcode("GH6 TXX", "NC4 LXX")) {
return 100.0; }
else {
return 50.0;}
} }
public class MultiPostcodeRange {
private String pcode;
public MultiPostcodeRange() {
pcode = "XXX XXX";
}
public double multiPostcodeRange() {
if (pcode.equals("GH6 TXX") || pcode.equals("NC4 LXX")) {
return 100.0;
}
else {
return 50.0;
}
}
}
To return double from a function you need to define a return type for the function.
public double multiPostcodeRange
You created a class with his methods (which btw you shouldn't name as the class, but give them unique names).
Then you have to create a new instance object of that class and call the method on a main function.
For example, at the end of your code:
`public static void main(String args[]){
multiPostcodeRange Obj = new
multiPostcodeRange();
Obj.meth1();
Obj.meth2();}`
NB remember to give those methods unique names!
Also change 2nd method body and type as AndyMan's answer
I'm just new to Java OOP, and I hardly understand about the class and stuff. I tried to write some code to understand but I didn't succeed. Here is my code, I expected it to return the number of eggs but I don't know why it returns nothing.
class EggCounter {
private int egg;
{
egg = 0;
}
public void eggAdd()
{
egg = egg + 1;
}
public void eggBreak()
{
egg = egg - 1;
}
public void eggAddDozen()
{
egg = egg + 12;
}
public int getEgg()
{
return egg;
}
}
public class EggTest
{
public static void main(String[]args)
{
EggCounter egg = new EggCounter();
egg.eggAdd();
egg.eggAddDozen();
egg.eggBreak();
egg.getEgg();
}
}
It does return 12. Replace the egg.getEgg(); line in your main method with System.out.println(egg.getEgg()); and you will notice it prints 12.
It is returning, it's just that you do nothing with the return value of getEgg. What you need to do is store it into the variable or do something with it. return <value> only returns the given value to the callee, you must store it to use it. Example:
int eggCount = egg.getEgg();
System.out.println(eggCount);
Here, the assignment of eggCount calls egg.getEgg(). The call resolves when the number of eggs is returned, which assigns the return value to eggCount. Finally, it will print out eggCount. If you need the result of egg.getEgg() later, you can simply just output the following:
System.out.println(egg.getEgg());
How this works is the method egg.getEgg() is called. The return value is then resolved, which is passed into the print statement. This gets rid of storing it into a variable you can use later.
I want to create a set method to insert maximum temperature for a specific place and I want that temperature to be of type Double,the method will check if the entered number is >= to 100 or <= to 100
if yes then it will be inserted in the maximum temperature field..
else I have to throw a user defined exception that will tell me that the number I entered is out of the supposed limits!
I wrote the Exception and the method this way:
public class OutOfSensibleLimits extends Exception
{
private Double max;
public OutOfSensibleLimits(Double max)
{
this.max = max;
}
public Double getMax()
{
return max;
}
public String toString()
{
return "The maximum Tempreture you entered: '" + maxTemp +
"' is out of sensible limits.";
}
}
public void setMaxTemp(Double max){
if ( max >= -100 || max <= 100)
{
maxTemp = max;
}
else throw new OutOfSensibleLimits();
}
and it gives me an error, what am I doing wrong?
Problems:
This is not how exceptions work -- you need to call the appropriate super constructor with the appropriate String if you want it to show a String, and
You're not calling your own exception's constructor properly. You've written it to accept a Double, and you're not passing in a Double (you're passing in nothing).
the toString method is unnecessary and confusing since it will never be called and the String will never be seen.
You state, "and it gives me an error,...", but don't show us any error message. I'm guessing that the compiler is complaining that you're not calling your class's constructor correctly, but please don't leave us guessing -- show the complete unabridged error message.
Your setMaxTemp uses the wrong boolean operator: if ( max >= -100 || max <= 100). This is always true. You want to use && instead.
Suggestions:
Yes, pass in a double the constructor
And then use that double to create an appropriate error/exception message that is passed into the super's constructor.
Get rid of your exception class's fields and toString() method.
Most important, I urge you to first read the Exception tutorial before trying anything else.
Also simplify as you're making things overly complex. Your Exception class could easily be nothing more than a constructor and that's it.
Make sure that the method that might throw the exception declares that it throws this exception.
For example:
public class TestSensibleLimits {
private Double maxTemp;
public void setMaxTemp(double max) throws OutOfSensibleLimits {
if (max >= -100 && max <= 100) { // use && not ||
maxTemp = max;
} else
throw new OutOfSensibleLimits(max);
}
public Double getMaxTemp() {
return maxTemp;
}
public static void main(String[] args) {
TestSensibleLimits test = new TestSensibleLimits();
try {
test.setMaxTemp(200);
} catch (OutOfSensibleLimits e) {
e.printStackTrace();
}
}
}
#SuppressWarnings("serial")
public class OutOfSensibleLimits extends Exception {
private static final String FORMAT = "The maximum Temperature you "
+ "entered: %.2f is out of sensible limits.";
public OutOfSensibleLimits(Double max) {
super(String.format(FORMAT, max));
}
}
I have been trying to solve this problem for ages and with no luck I didn't progress. Could someone please help me out. I have created an arrayList, made an getter class, have made a method. I can add stuff to the array list as well but when I print the arrayList out it prints out some random text.
below is the arrayList I created.
public static ArrayList<getArrayList> arrayList = new ArrayList<getArrayList>();
here is my method;
private static void addToArrayList(String a, double no1, int no2, int no3) {
try {
arrayList.add(new getArrayList(a, no1, no2, no3));
} catch (Exception e) {
e.printStackTrace();
}
}
here is my getter class
public class getArrayList {
private String name;
private double seconds;
private int speed1;
private int speed2;
public String getName() {
return name;
}
public double getSeconds() {
return seconds;
}
public int getSpeed1() {
return speed1;
}
public int getSpeed2() {
return Speed2;
}
public StoreCommands(String storeName, double storeSeconds, int storeSpeed1, int storeSpeed2) throws Exception{
name = storeName;
seconds = storeSeconds;
speed1 = storeSpeed1;
speed2 = storeSpeed2;
}
}
to add stuff on this list I use the method I created
addToArrayList(String a, double no1, int no2, int no3) filled in with my values
and to receive stuff from the arraylist I use this
for(getArrayList s : arrayList) {
System.out.println(arrayList + "\n")
;
and it prints out if i use System.out.println(arrayList), depending on how much I add to the arraylist.
[StoreCommands#49a21b63]
Besides that could someone tell me how I can set a size of the arrayList so if anything more that is being added it won't add and give an error.
Also I need to perform certain error checks once the items are in the arrayList
*1st If the an item is added to the list and the user tries to add the same one again straight after I want to display an error.. (the user can add the same stuff but not directly after the one they just added, they will need to add something else first)
*2nd if say user wants to add apples to the list, I want to limit that to only 2 time in the whole list, more than that will not be added and will display and error.
Could someone help me out please, I will really appreciate it.
Thanks.
Try this -
for(getArrayList s : arrayList)
System.out.println(s + "\n");//This print the tostring of getArrayList class
Again override the toString method of getArrayList class, to print actual field value of the object. Example -
public class getArrayList {
public String toString(){
return name +"||" +seconds+"||"+ speed1+"||"+speed2;
}
}
Note : Follow java nomenclature standard, first later of you class name would be capital And also give a relevent name to the Class.
Overriding toString method will help you to print actual data. Override it in your class getArrayList. One more thing is class name should start with capital letter.
public String toString()
{
return "Name : "+name+" Seconds : "+seconds+" Speed1 : "+speed1+" Speed2 : "+speed2;
}
and use it like
for(getArrayList s : arrayList)
System.out.println(s.toString);
You can limit the size by adding check to
private static void addToArrayList(String a, double no1, int no2, int no3) {
try
{
if(arrayList.size < 10) //any size you want
arrayList.add(new getArrayList(a, no1, no2, no3));
else
System.out.println("ArrayList is full");
} catch (Exception e) {
e.printStackTrace();
}
}
You don't have to loop in order to print an array, just do:
System.out.println(Arrays.toString(arrayList.toArray()));
ArrayList doesn't have a mechanism to limit the size, if you want to do it - you'll have to implement it.
Example:
import java.util.ArrayList;
/**
* User: alfasin
* Date: 2/5/14
*/
public class RestrictedSizeArrayList<E> extends ArrayList<E> {
private static final int limit = 6;//example
#Override
public boolean add(E e){
if(this.size() > 5){
throw new IndexOutOfBoundsException("Can't add more than 5 elements to the ArrayList");
}
boolean result = super.add(e);
return result;
}
}