Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I posted about this yesterday, but I think I need to make it less involved. I have absolutely no Java experience, and I need to work on this "Dice" program. I've done it twice already, but clearly I still have no idea what I'm doing. I've also been pouring over examples on here and elsewhere online, but none of them exactly match what I'm doing, as they all say "Pair of Dice".
Mine says: "Create a class called Dice to represent a SINGLE cube". It should have a method called roll() that randomly selects a number from 1-6 for the value of the dice."
It has to use java.util.random, not math.java, and it has to have numberShowing:int, roll():int, and main() all in it.
The last part reads "Create a test main method for the Dice class that creates a dice and rolls it many times. Can you keep track of how many times a number comes up? Describe how or implement it in the program."
I have started at this computer for hours, and read as much info as I can. I can't tell you how high my anxiety level is right now, nor how much I despise this. Please help me get this code written.
First, don't panic. It's hard when things are new and don't be discouraged if you don't know where to start.
Here is the documentation for java.util.Random: http://docs.oracle.com/javase/7/docs/api/java/util/Random.html
Your first job is to work out how to read this and understand it. Try Googling "java understanding api documentation" or similar.
It describes how the class you've been told to use works.
You will also need to know how to define a class of your own, called Dice with an instance variable numberShowing and instance methods roll and main. You can research these things by Googling something like "java introduction tutorial create class" or similar for each of these.
Here's a quick rundown of what you need to know (but know the approaches above for future problems):
Declaring a class named Dice:
File: Dice.java (name must match class name below)
public class Dice {
}
Adding an instance variable numberShowing:
You need to know what type the variable needs to be. You have been told to use an int which represents an integer value (a whole number):
File: Dice.java
public class Dice {
int numberShowing;
}
Adding a method roll():
You need to know what type of value this method returns, and the types of any values it can be given to perform some calculation or action. In this case you have been told it doesn't take any values and returns a value of type int (this is what I assume is mean't by roll():int in your above description - that is, empty parenthesis for no values passed in and :int to indicate the method returns an int):
File: Dice.java
public class Dice {
int numberShowing;
public int roll() {
/* code to perform calculation goes here */
}
}
You need to place the code to perform a random roll and assign the result into numberShowing at the point where I have the comment above (the comment is denoted text enclosed in /* and */).
You will need to create an object of the java.util.Random class. To do this you will need to import this class. Then you need to create using its constructor, and call an appropriate method - be sure to check the API document to understand how the method works.
File: Dice.java
import java.util.Random;
public class Dice {
int numberShowing;
public int roll() {
Random random = new Random(); /* <-- this is a constructor */
numberShowing = random.nextInt(6) + 1; /* <-- look at the API doc for nextInt() to see why we give it 6 as and argument, and why we need to add 1 to the result */
}
}
Adding a static method main():
This is the standard entry point for running a class as a program. You should be able to find an example of this easily by googling any getting started or introduction to java tutorial. (Sorry, I ran out of time).
Related
i don't know if the title is right. I'm doing a project for a petrol station in java. There is a question that reads as:
write method:
addFuel() which passes in an amount of petrol to be added to the pump as an argument and updates the appropriate variables as necessary. No return data required.
i have a instance variable for the amount of petrol in the pump.
i'm still somewhat new to java and don't fully understand how to answer this question. i cant seem get java to click to me. This is probably a easy question but i need help.
Part of the method's signature is the parameters it receives. In your case, you need to pass an amount (for argument's sake, let's say it's a double) and add it to your data member:
public void addFuel(double amountToAdd) {
amount += amountToAdd;
}
The problem is as follows:
I have to write a program using static methods which according to what the arguments are like need to return a certain type of information.
if the arguments are 2 int-type numbers then it would return the sum of those 2
if one of the arguments is a double-type number then it would return that number squared
if the arguments are a string and an in-type number then it would print said string times the int-type number.
The problem is that I do not know how exactly this program should look like since there's just one "sample" problem about static methods and that one is nothing like the one I'm being asked to solve.
In addition I still haven't figured out why I even need to use this static method if instead
I could simply write an if sentence instead.
Feels kind of bad to not to be able to figure this out myself but I guess sometimes how have to ask for help.
Anyways thanks in advance!
Okay so unless I have misunderstood the question want you want to do is overload a method. As a single method in can only accept a fix set of parameters, the way around this would be to create multiple methods (static or otherwise) with the same name but different parameters.
E.g.
static int method(int a, int b) {
return a + b;
}
static double method(double b) {
return b*b;
}
And so on for each different set of parameters required. However I would recommend also looking up this concept thoroughly as its very fundamental.
To add further, an if statement most likely wouldn't evaluate the parameters inside the function correctly most likely be a lot more cumbersome to program than simply overloading your method to accept different types of parameters and act upon them accordingly
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I've just realised that when I am programming in Java I avoid local variables like the plague, if I really have to I prefix a member with a lower case "L" and have a method that resets that object (if the object is mine, I usually have a private method called init or something that the constructor calls)
I've just realised that this is really ugly in so many ways. Am I doing it right?
C++ programmers will know exactly what I mean, locals that don't leave the function's scope are automatically destroyed for us (if it does leave the function scope, use a pointer, blah blah blah)
Pattern for when this happens
I've found that whenever I fit an adapter to a function parameter and interact with it through this adapter is when I use this.
I also tend tohave the adapter maintain a pool of any objects it uses (up to a certain number)
It also occurs when I want to use data-types that require "new" to initialise but only within the method.
The code is a part of some main loop usually, otherwise it wouldn't matter, obviously (it's not a one off thing)
GC Collection amount:
Amount (Mb): | 30| 60| 90| 120| 150| 180| 210| 240| 270| 300| 330| 360|
--------------+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
With pattern |## (14)
without |################################################################### (350)
The program was pushed through its unit tests the mean GC amount is shown. The standard deviation was less than 5 for both.
This feels like it is somehow related to the flywheel pattern...
There is no code for this because:
It can manifest itself in so many ways! If you have a ComplexNumber class for example, if you just create them as needed you will generate vast amounts of garbage, if you have any sort of vector or matrix classes, same thing.
Another area is anything involving some sort of graph which is carefully traversed to generate another structure, like a scene graph, critical path, even a stack representing the current directory.
Basically if you have "new" to assign to a local variable in a method that gets called a lot you will find this.
Sample used above
It came from a program I wrote to teach people about finite state automata and other state-machines (Markov Chains, so forth), I noticed crippling ram usage and decided to investigate.
Comparison with other languages
Obviously C++ doesn't have this problem. But nor does Python you'll be glad to know. Python's reference counting means (provided you haven't got any cricles) that the moment the method ends things are deleted, infact there is a meta-method for it and you can use it reliably as a destructor (provided you are disciplined enough not to leak it from the method)
I can't be the first to have this problem, looking at similar questions suggests that there is no solution, but I can't believe that this hasn't been encountered before!
About me
I'm coming from C++ and Python (love them both!) to Java, I am "experienced" in Java in that I can read/write stuff that works, it follows a nice design philosophy and such, but I tend to be very mindful of performance and resources. I'm suffering withdrawal from const, I was a total const whore.
How this is not pooling
Suppose you have a GroupElement class - that represents a member of an algebraic group, we'll use additive notation.
Suppose that g.add(h) returns a new element, if you do this MANY many times you have a lot of elements. if instead you have:
GroupElement f = new GroupElement(0); //identity
g.add(f,h);
where:
add's first argument is the place to put the result, we generate no garbage.
The people who don't follow the above
You should know what a complex number is? Suppose a complex number has a method called add that takes a complex number and returns a new complex number. If you do a=b.add(c); A LOT of times, you get A LOT minus 1 garbage complex numbers floating around.
If you have inplaceAdd(ComplexNumber target, ComplexNumber value) say where:
target.real = value.real+real;
target.im = value.im+im;
you create no garbage if you do: b.inplaceAdd(a,c) - which does the same as the above a=b.add(c)
BTW add could do this: return new ComplexNumber(real+value.real,im+value.im) - see what I mean now?
Implementation of example (seriously guys, how do you not get this!)
public class ComplexNumber {
private double real;
private double im;
public ComplexNumber(double r, double i) {
real = r;
im = i;
}
public ComplexNumber add(ComplexNumber value) {
return new ComplexNumber(real + value.real, im + value.im);
}
public void inplaceAdd(ComplexNumber target, ComplexNumber value) {
target.real = real + value.real;
target.im = im + value.im;
}
}
If you have a ComplexNumber class for example, if you just create them as needed you will generate vast amounts of garbage, if you have any sort of vector or matrix classes, same thing.
Keep in mind that garbage is free; the cost of garbage collection is determined by the non-garbage that has to be traversed. (I mean, the VM spec doesn't actually specify exactly how GC must be implemented, but that's how the major ones all work.) And this is intentional: obviously there's no technical reason that a Java implementation can't use reference-counting; it's just that it's not considered very robust/efficient/reliable/etc. (In C++ and Perl and Python, the reference-counting gives you the advantage of predictable destructors. Java doesn't offer that; instead, it offers finally blocks and try-with-resources.)
As part of my AP curriculum I am learning java and while working on a project I wondered which of the following is best way to return a value?
public double getQuarters(){
return quarters;
}
or
public void getQuarters(){
System.out.println(quarters);
}
***Note: I now that the second option is not "technically" returning a value but its still showing my the value so why bother?
Your answer would be correct. The second method doesn't return any value at all, so while you might be able to see the output, your program can't. The second method could still be useful for testing or even for a command line application, but it should be named something like printQuarters instead.
public double getQuarters(){
return quarters;
}
Use this incorder to encapsulate quarters and hide it from being accessed by other programs. That means, you have to declare it as private quarters. Let see the second option:
public void getQuarters(){
System.out.println(quarters);
}
However, this seems wrong as getQuarters is not returning anything. Hence it would make more sense to refactor it as
public void printQuarters(){
System.out.println(quarters);
}
You answered your own question. For most definitions of the word "best", you should go with the first option.
Your question, however, does touch on the object-oriented programming topic of accessors and mutators. In your example, "getQuarters" is an accessor. It is usually best to use accessors to retrieve your values. This is one way to adhere to the Open/Closed Principle.
Also, the Java community has a coding convention for this and many tools and libraries depend on code following those conventions.
If all you need to do is display the value when this method is called, and you are ok with console output, then your System.out.println method will do the job. HOWEVER, a function that actually returns the variable is much more semantically correct and useful.
For example, while you may only need to print the variable for your current project, what if you came back later and decided that you were instead going to output your variable to a file? If you wrote your getQuarters function with a println statement, you would need to rewrite the whole thing. On the other hand, if you wrote the function as a return, you wouldn't need to change anything. All you'd have to do is add new code for the file output, and consume the function where needed.
A returning function is therefore much more versatile, although more so in larger code projects.
You return values to a specific point in your program, so that the program can use it to function.
You print values at a specific point in your program, so that you as an end user can see what value you got back for some function.
Depending on the function - for instance, yours - the result of quarters is no longer regarded in the program; all it did was print a value to the screen, and the application doesn't have a [clean|easy] way to get that back to use it.
If your program needs the value to function, then it must be a return. If you need to debug, then you can use System.out.println() where necessary.
However, more times than not, you will be using the return statement.
Option 1 is far superior.
It can be easily Unit Tested.
What if the spec changes and sometimes you want to print the result, other times put it into a database? Option 1 splits apart the logic of obtaining the value from what to do with it. Now, for a single method getQuarters no big deal, but eventually you may have getDimes, getEuros, etc...
What if there may be an error condition on quarters, like the value is illegal? In option 1, you could return a "special" value, like -1.0, or throw an Exception. The client then decides what to do.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
Because I'm tired of solving math problems, I decided to try something more engaging with my very rusty (and even without the rust, very basic) Java skills. I landed on a super-simple people simulator, and thus far have been having a grand time working through the various steps of getting it to function. Currently, it generates an array of people-class objects and runs a for loop to cycle through a set of actions that alter the relationships between them, which I have stored in a 2d integer array. When it ends, I go look at how much they all hate each other. Fun stuff.
Trouble has arisen, however, because I would like the program to clearly print what action is happening when it happens. I thought the best way to do this would be to add a string, description, to my "action" class (which stores variables for the actor, reactor, and the amount the relationship changes). This works to a degree, in that I can print a generic message ("A fight has occurred!") with no problem. However, ideally I would like it to be a little more specific ("Person A has thrown a rock at Person B's head!"). This latter goal is proving more difficult: attempting to construct an action with a description string that references actor and reactor gets me a big old error, "Cannot reference field before it is defined." Which makes perfect sense.
I believe I'm not quite in programmer mode, because the only other way I can think to do this is an unwieldy switch statement that negates the need for each action to have its own nicely-packaged description. And there must be a neater way. I am not looking for examples of code, only a push in the direction of the right concept to handle this.
Wow. Quite a large wall of text. Hence:
Breakdown
Your setup
Currently, it generates an array of people-class objects and runs a for loop to cycle through a set of actions that alter the relationships between them, which I have stored in a 2d integer array.
I would like the program to clearly print what action is happening when it happens.
I thought the best way to do this would be to add a string description to my "action" class (which stores variables for the actor, reactor, and the amount the relationship changes).
It sounds like your Action class so far looks something like this:
public class Action {
private String reactor;
private String actor;
private double hateMeasure;
/* Obligatory constructor method, getters, and setters go here */
}
Your trouble
I would like it to be a little more specific ("Person A has thrown a rock at Person B's head!").
... attempting to construct an action with a description string that references actor and reactor gets me ... "Cannot reference field before it is defined."
At this point I'm not quite sure how you're setting up your reference fields, and exactly how you're running into this error.
I know you weren't looking for code, but you must appreciate the difficulty of getting somebody into "programmer mode" without showing them some skeletal principle-illustrating code.
Perhaps create a method that takes two parameters of the actor and reactor, and then call that method after each action happens?
public void reportAction(String reactor, String actor) {
// do stuff
}
/* if you're confused by how "reactor" and "actor" have the same names as
the instance variables, look into the "this" keyword */
Alternatively (if your setup was different from what I inferred from your description, add in those instance variables and then) you can simply write a new method in your Action class that takes no parameters and simply references your instance variables:
public void reportAction() {
System.out.println(actor + " with " + reactor);
}
Now it occurs to me that you may wish to specify what happened between the reactor and actor instead of simply stating that something happened between two specific simulated people. In that case...
public void reportAction() {
System.out.print(actor);
// you're going to have to define the change in hateMeasure here
if( deltaHateMeasure > 0 ) {
System.out.print(" had a fight with " + reactor);
} else { /* print other stuff */ }
}
Another fun thing for you to look at would be ternary operators, if you'd like to code this succinctly.
Have fun!
EDIT:
Even better!
Add in a String descriptor; instance variable to your class!
Then it all comes down to...:
public void reportAction() {
System.out.println(actor + descriptor + reactor);
}
I am not exactly sure how you wrote your classes. Am I correct in assuming that at the time that you want to print your string, you do know the names of the actor and reactor?
If so, you should be able to do something along these lines:
System.out.printf(action.description, actor.name, reactor.name);
In which case action.description (or wherever you store your description string) looks something like:
"%s has thrown a rock at %s's head!";
I hope this helps!