I have a question regarding a situation I am experiencing. I wrote a really basic program to help show you an example of what my issue is. I wondering how (if even possible) to do something a certain way. It involves a variable from one class, a method from another class. And using them together to get a result in the Main.
Main:
// The main, which creates an object of Testing and Yupp, then Tries to run the method to add +3 and display it, repeatidly.
import javax.swing.JOptionPane;
public class Runit
{
public static void main(String[] args)
{
Testing testing = new Testing();
Yupp yupp = new Yupp();
JOptionPane.showMessageDialog(null, testing.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, testing.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, testing.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, testing.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, testing.number);
}
}
Yupp Class:
//Just extending all the information from Testing class( which holds the "number" variable so I have access to it ) Then making the simple personal method to add 3 to it.
public class Yupp extends Testing
{
public void doMath()
{
number = number + 3;
}
}
Testing Class:
// Just holding the number variable in this class.
public class Testing
{
int number = 3;
}
So essentially what I want to happen, regardless of if its proper coding, which I'm sure it isn't. What should(I want to) happen is the "number" variable, should just increase by 3 on each separate JOptionPane window. Like I said, its just a basic code example I wrote to explain my problem. I think it makes a lot of sense this way. Thank you if you can help me figure out what to do to make this possible.
Currently the number always comes back as 3. Instead of 3 + 3, 6 + 3, 9 + 3, etc.
problem:
testing.number
You are getting the same number from that instance of Testing which is not incremented thus giving you 3 all the time
solution:
use your Yupp object to get the incremented value from the method call doMath
sample:
JOptionPane.showMessageDialog(null, yupp.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, yupp.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, yupp.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, yupp.number);
yupp.doMath();
JOptionPane.showMessageDialog(null, yupp.number);
In short:
You are creating two different objects:
Testing testing = new Testing();
Yupp yupp = new Yupp();
then, you are calling the operation (doMath) in one (yupp), but printing the attribute number of the other (testing). The last one, doesn't change in the whole program.
Related
this is my first question on here and I did a search before forming it, so I hope everything is as required.
I am working on a school assignment in Java. I am able to produce the required output but there are a lot of null instances created first. I don't understand why. Information about the library the professor created for the course and the code are below
Library included with this course: i2c.jar. It can be found here.
included in this Library are the classes Country and CountryDB. The API for the Country class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/Country.html
The API for the CountryDB class can be found at http://130.63.94.24/~roumani/book/doc/i2c/ca/roumani/i2c/CountryDB.html
I am asked to create a class called Game, using the Country and CountryDB APIs.
The only attribute is db, which is an instance of CountryDB.
The constructor only sets the attribute (db) for this instance to a new CountryDB object.
The class is also meant to include a method (called qa) that follows this pseudocode:
get a reference to the database's capital city list
determine the size of this list. Cal it n.
generate a random number in [0,n) called index.
invoke get(index) on the list to get a random capital city. Call it c
get a reference to the database's data map
invoke get(c) on the map to get a reference to a country. Call it ref.
The method is then supposed to return one of two Strings (which will be clear in the code). Everything works as it should, except I get a lot of "nulls" before the desired output. When made into a List, db has size 241 so I suspect I am creating 241 null instances and 1 proper instance. I have no idea why though. I have tested every line of code in my method and the constructor was dictated by the textbook.
CODE
package ca.yorku.eecs.caps;
import java.util.List;
import java.util.Map;
import ca.roumani.i2c.Country;
import ca.roumani.i2c.CountryDB;
public class Game
{
private CountryDB db;
public Game()
{
this.db = new CountryDB();
}
public String qa()
{
List<String> capitals = db.getCapitals();
System.out.println(capitals.toString());
int n = capitals.size();
System.out.println(n);
int index = ((int) (n * Math.random()));
System.out.println(index);
String c = capitals.get(index);
System.out.println(c);
Map<String, Country> data = db.getData();
Country ref = data.get(c);
if (Math.random() > 0.5)
{
return "What is the capital of " + ref.getName() + "? \n" + ref.getCapital();
}
else
{
return ref.getCapital() + " is the capital of? \n" + ref.getName();
}
}
public static void main(String[] args)
{
Game g = new Game();
System.out.println(g.qa());
}
}
the System.out.println() statements are only there to test when the nulls occur. It clearly happens immediately because my psvm output is 241 nulls (on separate lines) followed by my desired output. Can somebody please tell me what I am doing wrong?
And, more generally (to help more people) how do you implement classes, the constructor of which instantiates another class and sets it as an attribute value?
I appreciate any help. Also, please note, I am not trying to get others to do my work for me. I've spent hours on this and my lab TA also wasn't sure why it happens either. He would have helped me correct it had he known how.
Thank you.
So I'm currently trying make a simple rpg game, it's my first time so I'm learning haha, but my question is that, I am trying to reference a variable in another class I have for the player's choice of their class. P.S. I couldn't figure out what to look up so I'm sorry if this is a repeat question.
this is the main
public static void main(String[] args) {
Scanner inputRace = new Scanner(System.in);
player player1 = new player(race.valueOf(inputRace), profession.ranger);
}
and here is the race class I'm trying to reference
public enum race {
orc, elf, human, dwarf
}
So all I'm trying to do is be able to take the user's input and do like race.("whatever their choice is"), but I haven't been able to figure it out. Thanks for any help and sorry if it's confusing.
In other to access input data you must use scanner methods like next, nextInt, nextDouble etc.
In your case you are looking for string so it should look like this:
try {
Race race = Race.valueOf( inputRace.next() ); // next returns string
Player player1 = new Player(race, profession.ranger);
} catch ( IllegalArgumentException ex ) {
System.err.println( "That race doesn't exsist" );
}
Note that I used upper case for Race and Player, this is standard way of naming your classes.
Also you should put your code in some kind of loop until he doesn't write correct race.
If I understand correctly, you need to get race.orc if the user enters orc, and henceforth.
You're on the right track, you just need to input the String from the user, like
String s = inputRace.next();
player player1 = new player(race.valueOf(s), profession.ranger);
I have 3 jframes. After user answer questions on each frame, if they succeed i need to increase the marks. The user can go to the next frame whether they succeed or fail.
I did this by having a class called calculatemark and a setmark method in it.
int total =0;
public void setMark() {
total++;
System.out.println("Total :- " + total);
}
which will increase the mark. so on each frame i call this method to increase the mark. The problem is as i to create an instance of the class calculatemark on each frame the counter is not increasing as the variables get initialized as well. Can anyone please help me to let me know how to implement this? Any other ways i should do this to increase the counter? Do i really need to have a database connection and update this? I read something about singleton? is this helpful here? Please help i am a novice.
public class CalculateMark {
int mark=0;
public static CalculateMark calc = new CalculateMark();
private CalculateMark() {
}
public static CalculateMark getInstance(){
return calc;
}
public void addMark(boolean x){
// x is true if answer is right
if(x){
mark+=50;
}
System.out.println(mark);
}
}
Then say you have 3 frames Frame1, Frame2, Frame3.
on answering , just call another frame
CalculateMark().getInstance().addMark(true);
new Frame2().setVisible(true);
this.dispose();
I am new in Stackoverflow , please correct me if my way of answering is not correct..
Instantiate an CalculateMark instance as an instance variable in the class which opens up the JFrames.
Then, in your JFrame subclasses, make a constructor like this:
public MyJFrame(CalculatMark counter){
}
Whenever you create a new JFrame, pass in the reference to the same CalculatMark object.
Basically, just pass around a reference to this single CalculateMark object, and you should be good.
I don't have your code, so I'm not sure exactly how you'd do that, but it shouldn't be too difficult.
I am making exactly the same Java program that is in this link:
Run-time Polymorphism in Java without "abstract"?
But I am having problems in the Main Application.
In my problem I have to ask the user to enter which types does he want(Bicycle,MountainBike,RoadBike).
And then I add what type he chose to an array of 5 indexes.
How can I do that?
Please give me some help.
Thanks in advance.
I don't know how you look for answers from your users, but if it's buttons you do it with, you can just add the requested type of object, when a user press specific buttons.
But what you have to do, is make an ArrayList<Bicycle> and then just add the objects that extends Bicycle.
You should create a factory method that returns an instance of a Bicycle:
For example:
public Bicycle createBicycle(String type) {
if (type.equals("Bicycle")) {
return new Bicycle(20, 10, 1);
} else if (type.equals("MountainBike")) {
return new MountainBike(20, 10, 5, "Dual");
}
//and so on..
}
And use it like this for example:
Bicycle[] bicycles = new Bicycle[5];
bicycle[0] = createBicycle("Bicycle");
I'm in a beginner's java class. This Lab is for me to make a class "Wallet" that manipulates an array that represents a Wallet. Wallet contains the "contents[]" array to store integers represing paper currency. The variable "count" holds the number of banknotes in a wallet. After writing methods (that match provided method calls in a serpate Driver class) to initialize the Wallet and add currency/update "count", I need to transfer the array of one instantiated Wallet to another. I don't know how that would work because the one Wallet class has only been messing with a wallet called "myWallet" and now I need to take a new Wallet called "yourWallet" and fill it with "myWallet"'s array values.
//I should note that using the Java API library is not allowed in for this course
My Wallet class looks like this so far:
public class Wallet
{
// max possible # of banknotes in a wallet
private static final int MAX = 10;
private int contents[];
private int count; // count # of banknotes stored in contents[]
public Wallet()
{
contents = new int[MAX];
count = 0;
}
/** Adds a banknote to the end of a wallet. */
public void addBanknote(int banknoteType)
{
contents[count] = banknoteType;
count = count + 1;
}
/**
* Transfers the contents of one wallet to the end of another. Empties the donor wallet.
*/
public void transfer(Wallet donor)
{
//my code belongs here
}
...
The Driver code looks like this:
public class Driver
{
public static void main(String args[])
{
Wallet myWallet = new Wallet();
myWallet.addBanknote(5);
myWallet.addBanknote(50);
myWallet.addBanknote(10);
myWallet.addBanknote(5);
System.out.println("myWallet contains: " + myWallet.toString());
// transfer all the banknotes from myWallet to yourWallet
Wallet yourWallet = new Wallet();
yourWallet.addBanknote(1);
yourWallet.transfer(myWallet);
System.out.println("\nnow myWallet contains: "
+ myWallet.toString());
System.out.println("yourWallet contains: "
+ yourWallet.toString());
I want to use addBanknote() to help with this, but I don't know how to tell the transfer() method to transfer all of myWallet into yourWallet.
I had the idea to do somethign like this in transfer():
yourWallet.addBanknote(myWallet.contents[i]);
with a traversal to increase i for myWallet contents. It seems horribly wrong, but I'm at a complete loss as to write this method.
If my problem is so unclear that nobody can help, I would be more than happy to receive advice on how to ask a better question or on how to search with correct terms.
Thanks for any help you can provide.
I don't want to spoil your homework as you seem to be going the right way, but I do have some comments which you may either take or not :)
First, I would probably put the bank note types in some enumeration. But as that sounds a bit to advanced, consider
public class Wallet {
public static final int ONE_DOLLAR_BILL = 1;
public static final int FIVE_DOLLAR_BILL = 5;
...
// looks a bit more readable to me
myWallet.addBanknote(ONE_DOLLAR_BILL);
Transferring all the banknotes from the donor to yourself should not be so much of a problem
(a for loop would do) but I think you're in a world of hurt if you are trying to implement a
removeBanknote(int banknoteType);
as you are using count not only as a length but also as an index variable. By this I mean that you assume contents[0] ... contents[count-1] hold valid banknotes. And how do you remove one without too much work?
Warning: a bit more advanced
In your case I would probably opt to have a banknoteType of 0 indicating an empty banknote slot in your wallet, and implement _addBanknote(int banknoteType) as:
public void addBanknote(int banknoteType) {
for (int i=0; i < contents.length; i++) {
if (contents[i] == 0) {
contents[i] = banknoteType;
count++;
return; // OK inserted banknote at the first empty slot
}
}
throw new RuntimeException("Wallet is full");
}
This may be a bit overwhelming at this point. But it would allow you to implement:
public void removeBanknote(int banknoteType) {
for (int i=0; i < contents.length; i++) {
if (contents[i] == banknoteType) {
contents[i] = 0; // better: NO_BANKNOTE = 0
count--;
return;
}
}
throw new RuntimeException("This wallet does not contain a banknote of type " + banknoteType);
}
Please note that in both methods I return when I successfully removed or added the banknote. Only when I could not find a free slot, or the requested banknote, I finish the for loop and end up throwing an exception and thereby stopping the program.
I think the question is fine and I think you're on the right path. The way you're calling Wallet#addBanknote(int) is correct. What you have said is the right thing:
public void transfer(Wallet donor)
{
// Traverse the donor's wallet
// Add the bank note from the donor to this wallet
// What do you think also needs to happen to make sure
// the donor is actually giving their bank note?
}
Just another thing, what would happen in your Wallet#addBanknote(int) method if you have more contents than the MAX?
You can create either a constructor that takes another wallet, or a function (as already mentioned) and use System.arraycopy to copy the array in one fell swoop. System.arraycopy is fast, and its definitely overkill for something small like this, but its good tool to have in your toolkit.
The other alternative mentioned, copy the elements from one array to the other element by element in a loop will work fine too.
The myWallet inside the transfer method is named 'donor', and with that, it doesn't look horribly wrong:
addBanknote (donor.contents [i]);
You just need a loop around it, and to remove the yourWallet. which is the name of an instance of that class. That instance is inside the Class/method this, but needn't be specified, because there is no other addBanknote-Method in scope, which could be meant. (Thanks to mangoDrunk).