This should be relatively straight forward however I'm being swamped in SQL information whenever I search for help with this.
Basically I have 3 classes and they each generate a number and I want to get the total number at the end. Is there a way to make a variable which all 3 classes can add to without generating a SQLite Database?
example
Page1.java creates 5 -> adds to Total
Page2.java creates 12 -> adds to Total
Page3.java creates 10 -> adds to Total
Page4.java opens total
Like I said, its likely a simple problem but SQLite is dominating my searches.
Hope you can help, Thanks.
You can use a static variable for that.
If you don't care about encapsulation you could even use one single public static variable for this purpose.
Example:
private static int mCounter = 0;
public static void addToCounter(int i)
{
mCounter += i;
}
public static int getCount()
{
return mCounter;
}
What you could do would be to have a private value, say, private int count in each of your class and its respective getter. You would then also have a method in each class, say, public void doSomething(){... count = ...}.
Once you have all these, in Page4 you could do something like:
public class Page4
{
Page1 pg1 = new Page1();
Page2 pg2 = new Page2();
Page3 pg3 = new Page3();
pg1.doSomething();
pg2.doSomething();
pg3.doSomething();
int total = pg1.getCount() + pg2.getCount() + pg3.getCount();
}
On the other hand, you could pass in an integer variable to the class which gets modified and passed on to the next class.
You could also pass in a reference to some class which contains the actual counter, and once that each class (Page1, Page2...) has finished doing what it needs it would simply reference that class and update the value itself.
It's not that clear how you call your classes.
However if you have just 3 simple classes and one place to call the classes you could pass your variable between the classes and add the values to it.
public class Page1 {
public void addToVariable(int var) {
var = var + 5;
}
}
public class Page2 {
public void addToVariable(int var) {
var = var + 12;
}
}
...
And then call the class methods with your variable:
int yourVariable = 0;
Page1 p1 = new Page1();
Page2 p2 = new Page2();
p1.addToVariable(yourVariable);
p2.addToVariable(yourVariable);
yourVariable will hold the total you're looking for.
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 have this class that serves as a container which I will use the instance variable for processing later
class Data{
static int counter= 0;
boolean boolean1;
String string1;
public Data() {
counter++;
}
}
And I have this method that sets the values of Data
public Data setData()
{
Data data = null;
for (int i = 0; i < somecoutnerhere; i++) {
Data = new Data();
Data.boolean1 = some boolean put here;
Data.string1 = "some string to be put here";
}
return ProcessData(Data);
}
I also have this class ProcessData that will make use of Data and will construct the response
private class ProcessData
{
private final Map<String, List<?>> map = new HashMap<String, List<?>>();
int counter;
public ProcessData(Data data)
{
map.put("boolean1", data.boolean1);
map.put("String1", data.string1);
counter = data.counter;
}
public String someMethodToGenerateReturnData(){
// some code here to make use of the Data collected. Will basically use map to construct the return String
}
}
My problem is that I couldn't figure out how can I return all the instance variables created on the for-loop for Data on setData(). Any thoughts?
My problem is that I couldn't figure out how can I return all the instance variables created on the for-loop for Data on setData(). Any thoughts?
According to this your problem is not "returning all instance one variables in one call", as your title states, but rather a question about how returning all Data-Objects created in your for-loop, which is easier.
Your code is erronous though, so I went ahead & corrected it (I hope I didn't mess up). I also renamed a few things.
The changes I made are:
renamed "boolean1" and "string1" to "trueOrFalse" and "string"
added a public, fully parameterized constructor to the Data-class
added a ProcessData-list to the setData()-method, which is filled in the for-loop
(+ a comment)
However, I'd strongly recommend you to check your architecture, and also to learn a bit about naming conventions, or coding conventions in general. Names should point out the purpose or content of the method/variable/class, and "boolean1" isn't really doing that.
Regarding the architecture: The Data-class seems to exist solely for the counter, and you could easily change that, making the Data-class obsolete (unless it's used somewhere else).
Data class:
class Data {
static int counter = 0;
boolean trueOrFalse;
String string;
public Data() {
counter++;
}
public Data(boolean someBoolean, String someString) {
this.trueOrFalse= someBoolean;
this.string = someString;
counter++;
}
}
setData()-Method:
public List<ProcessData> setData() {
List<ProcessData> processedDataList = new ArrayList<ProcessData>();
for (int i = 0; i < someCounterHere; i++) {
processedDataList.add(new ProcessData(new Data(true, "testString"));
// a new Data-object is created (parameters true and "testString")
// a new ProcessData-object is created (parameter is the newly created Data-Object)
// the newly created ProcessData-object is added to the list
}
return processedDataList;
}
ProcessData-class:
private class ProcessData {
private final Map<String, List<?>> map = new HashMap<String, List<?>>();
int counter;
public ProcessData(Data data) {
map.put("trueOrFalse", data.trueOrFalse);
map.put("string", data.string);
counter = data.counter;
}
public String someMethodToGenerateReturnData() {
// some code here to make use of the Data collected. Will basically use map to construct the return String
}
}
So lets say I have a class BaseballCard that creates a baseball card.
Now I need to make another class which would be my collection class.
For example I would call it BaseballCardCollection
and then I want to create methods like
size (which returns the numbers of cards in the collection)
addCard(adds a baseball object to the collection object)
removeCard (removes a baseball card)
and so on
What would be the best way to do this. I tried doing this
public CardCollectionList() {
BaseballCard[] baseballCardList = new BaseballCard[101];
}
So each object is insinuated with an array of type BaseballCard of size 100.
And then for example the size method I tried something like this
public int size(){
int size = 0;
for(int i = 1; i<this.baseballCardList.length; i++)
if (baseballCardList!= null)
size+=1;
}
But it doesn't work because "baseballCardList cannot be resolved to a variable"
You could try using ArrayLists - http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html:
ArrayList<baseballCard> baseballCardList = new ArrayList<baseballCard>(0);
public boolean addCard(baseballCard card){
return baseballCardList.add(card);
}
public boolean removeCard(int card){
return baseballCardList.remove(card);
}
public baseballCard getCard(int card){
return baseballCardList.get(card);
}
public int sizeBaseballCardList(){
return baseballCardList.size();
}
public ArrayList<baseballCard> getBaseballCardList(){
return baseballCardList;
}
Move the variable BaseballCard[] baseballCardList outside the constructor, make it a field in your class. Do similar with size.
This is how the class should look like:
public class CardCollectionList {
//fields
private BaseballCard[] baseballCardList;
private int size;
//constructor
public CardCollectionList() {
baseballCardList = new BaseballCard[101];
}
//method
public int getSize() {
return this.size;
}
}
You could try creating your own class implementing the Collection interface and define your own methods + implement Collection methods:
public class myContainer implements Collection <BaseballCard> {
}
You need to move the variable declaration from the constructor to the class, so you can access it in other methods, too.
class CardCollectionList {
BaseballCard[] baseballCardList;
public CardCollectionList() {
baseballCardList = new BaseballCard[101];
}
public int size(){
int size = 0;
for(int i = 1; i<this.baseballCardList.length; i++) {
if (baseballCardList[i] != null) {
size+=1;
}
}
return size;
}
}
The code is as close to your fragment as possible. There are several ways to improve this (keep track of the size when adding, automatic array reallocation etc.). But it is a start if you want to try this yourself.
Normally, you'd probably just use ArrayList<BaseballCard>.
Now I need to make another class which would be my collection class.
... What would be the best way to do this.
I don't have enough reputation to comment on your question, so I am going to assume that you just want to store BaseballCard objects in a Java Collection. The Java SDK offers a lot of options. Since you are asking about the "best" way to go then I would use one of those unless you need to add additional functionality .
if you don't find what you need from the Java SDK or just want to create your own Collection then follow the advice given by #michał-szydłowski above
I'm attempting to have an array (fishWeights) be set to the values that are found using a method. Except that when I try to compile this:
public class GoFishEdited {
public static void main(String[] args) {
System.out.println("\nProject 1, Stage 3\n");
Habitat h1 = new Habitat();
Habitat h2 = new Habitat();
int[] fishWeights = stockUp();
System.out.println("Start with some weights:");
for (int i : fishWeights) {
System.out.print(i + " ");
}
System.out.println("\n\nMake fish of those weights.\n");
Fish[] fishGroup = new Fish[fishWeights.length]; // array of Fish
for (int i=0; i < fishWeights.length; i++) {
fishGroup[i] = new Fish(fishWeights[i]); // make fish
}
}
}
It states that that the symbol stockUp() cannot be found. It is in this file:
public class Habitat {
ArrayList stringer = new ArrayList();
public int maxCount=25;
public int minCount=9;
public int maxWeight=10;
public int minWeight=1;
public int catchProbability=30; //0.3
public void stockUp(int[] fishArr){
int numofF = minCount + (int)(Math.random() * ((maxCount - minCount) + 1));
for(int i = 0; i<numofF; i++){
fishArr[i] = minWeight + (int)(Math.random() * ((maxWeight - minWeight) + 1));
}
}
public Habitat(){
}
public void addFish(Fish f) {
stringer.add(f);
}
public void removeFish(Fish f){
stringer.remove(f);
}
public void printFish(){
System.out.println(stringer);
}
}
So stockUp exists, I just can't seem to make getFishEdited to find it.
In java everything in an object.
So if you want to call method form a class should use
Habitat habitat = new Habitat();
habitat.stockUp();
stockUp() is an instance method of the Habitat class, so you need to create an instance of Habitat in your GoFishEdited class's main method in order to call it from GoFishEdited. You could call it on either instance of Habitat created, h1 or h2 Like this:
h1.stockUp();
Note that in the code you posted, you need to pass an array of integers as an argument to stockUp(), but it looks like in your code you are expecting stockUp() to return an int[]. If stockUp() is supposed to return an array of integers, then you need to change the method signature to look something like:
public int[] stockUp() {
//do whatever you want this method to do
return arrayOfInts;
}
You need to either create an instance of habitat using new Habitat to call the method in, or you need to make the method stockUp static and call it in the Habitat class using Habitat.stockUp.
Since you've created instances of Habitat in h1 and h2, call
h1.stockUp(fishArray)
Or
h2.stockUp(fishArray)
depending on what you mean to do. You declared the stockUp() method to accept an int[], so you'll need to pass it one--I called it fishArray, since you seem representing fish. Also, you've declare stockUp() as returning void, so don't expect it to return some value that you can assign to fishWeights. At some point you may find it's a good idea to introduce a Fish class to wrap that concept up better.
I have created a Compound class that holds the number of Carbon, Hydrogen, Oxygen, Nitrogen and it's bond count. I have a stack that holds these objects.
Initially the stack will start off at empty and I will pop that. Then I will apply addHydrogen function to it so it's Hydrogen will = 1, Oxygen=0, Nitrogen=0 and Carbon=0.
I then want to take the same object and apply the addCarbon function so that Hydogren will = 0, Oxygen=0, Nitrogren=0 and Carbon=1.
How can I write my program so I can use the same object but not with the changes I made from adding the Hydrogen? I know I could use some if cases initially but I don't think it will work because I will eventually start with a compound that has hydrogen=2, oxygen=2, Nitrogren=0, Carbon=1.
*I didn't include my constructors in the code, they just initialize everything to 0.
class compound {
int Hydrogen;
int Carbon;
int Nitrogen;
int Oxygen;
int bond;
public void addHydrogen(compound comp) {
Hydrogen++;
}
public void addCarbon(compound comp) {
Carbon++;
}
}
public static void main(String[] args) {
Compound a= new Compound();
a.addHydrogen(a);
a.addCarbon(a);
}
Your question isn't very clear, but one option you might wish to consider would be to make your object immutable - so you could never change the values within a single object, but you could instead make your addCarbon (etc) methods return a new object with appropriate new values in.
(Note that currently you're not using your parameters, which appear to have the wrong case anyway...)
Sample code:
public class Compound {
private final int hydrogen;
private final int carbon;
private final int nitrogen;
private final int oxygen;
public Compound(int hydrogen, int carbon, int nitrogen, int oxygen) {
this.hydrogen = hydrogen;
this.carbon = hydrogen;
this.nitrogen = nitrogen;
this.oxygen = oxygen;
}
public int getHydrogen() {
return hydrogen;
}
// ... etc for the other getters
public Compound plusHydrogen() {
return new Compound(hydrogen + 1, carbon, nitrogen, oxygen);
}
// etc for the other plus calls
}
Note that I've called the methods plusHydrogen etc to make it clear that they're not mutating the existing object, but returning a new one.
Then you can have:
Compound base = new Compound(0, 0, 0, 0);
Compound withHydrogen = base.plusHydrogen();
Compound withCarbon = base.plusCarbon();
// whatever