I have a class called cardNames. Every new game I will create a new instance of cardNames which would correspond to the current cards being used. I would prefer to have them as static so I won't have to send a copy of the cardNames object around.
Is this legal?
public class cardNames
{
private static String[] characters;
private static String[] weapons;
private static String[] rooms;
private int totalCards;
public cardNames(String[] theCharacters, String[] theWeapons, String[] theRooms)
{
characters = Arrays.copyOf(theCharacters, theCharacters.length);
weapons = Arrays.copyOf(theWeapons, theWeapons.length);
rooms = Arrays.copyOf(theRooms, theRooms.length);
totalCards = characters.length + weapons.length + rooms.length;
}
public static String[] getCharacters()
{
return Arrays.copyOf(characters, characters.length);
}
Would I have a new set of characters, weapons, and rooms after I create a new cardName object?
Related
I have a class in which i declare many words as class variables. And there is a method to choose a random word from those class words. How can i implement getRandomWord properly?
public class Vocabulary
{
int numOfWords = 2;
final static word1 = "hello";
final static word2 = "stack";
...
public String getRandomWord()
{
int random = (int)(Math.random() * numOfWords + 1);
return word + random;
}
}
I tried to add those words to an ArrayList first and then return the index but i cant understand how to add those words that are already declared in the class to the ArrayList.
If you just want to have one list of words, you should definitely use a Singleton as a static member of your class.
This member should have a List and be created only once.
That's why the constructor should be private.
It should look like this
import java.util.Arrays;
import java.util.List;
public final class Vocabulary{
//The final in the class name is there so you can't heritate from this class
private static Vocabulary INSTANCE = null;
private List<String> words;
//Private so you can't create another instance of it, you need to use static method
private Vocabulary() {
this.words = Arrays.asList("hello", "stack", "heap");
}
//In case you want to implemente other public function
public static Vocabulary getInstance(){
if(INSTANCE == null){
INSTANCE = new Vocabulary();
}
return INSTANCE;
}
//If you want to choose a word by its number
public static String getWord(int i){
return Vocabulary.getVocabulary().get(i);
}
//Used in getVocabulary, getter of the List
private List<String> getWords(){
return this.words;
}
// Return the whole List of words
public static List<String> getVocabulary(){
return Vocabulary.getInstance().getWords();
}
// Here your go
public static String getRandomWord(){
return Vocabulary.getWord((int)(Math.random() * Vocabulary.getVocabulary().size()));
}
}
And then you can just use it properly :
public static void main(String[] args) {
System.out.println(Vocabulary.getRandomWord());
}
Singleton is a well known design pattern and this is a pretty clean way to do it, hope it helps !
Make array like this:
String[] strs = { "hello","stack"};
Then add then to List<String>.
List<String> list = Arrays.asList( strs );
Okay. Here's my first page with the accessors and mutators
public class TimeCard {
private int employeeNum;
private String[] clockInTimes = new String[14];
private String[] clockOutTimes = new String[14];
private float[] decimalClockIn = new float[14];
private float[] decimalClockOut = new float[14];
private float[] timeElapsed = new float[14];
public String[] getClockInTimes()
{
return clockInTimes;
}
public void setClockInTimes(String[] value)
{
clockInTimes = value;
}
}
My second class acessessing those set/get arrays.
How would I ask for user input for each array subscript 0-13?
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
TimeCard josue = new TimeCard();
System.out.println("Enter Monday Clock In Times:");
//not sure if this is right?
josue.setClockInTimes[0](reader.next());
}
}
By the way I need to do it like this because teacher wants it this way. I'm just not really sure how to get user input and put it into an array using an object class.
I'd probably start by changing your setter to take an index and a value, so something like this:
public void setClockInTime(int day, String clockInTime) {
this.clockInTimes[day] = clockInTime; // note you don't need to write "this," but it's clearer that this is a member field
}
And then in your main method:
for (int i=0;i<14;i++) {
String input = <get input>
josue.setCliockInTime(i, input);
}
Now you can set one value at a time, and that should let you populate all of your fields.
I am looking to populate an array in the constructor with string values whenever a new instance is created. I am getting the following error in my code when I try to create an instance.
Array initialiser not allowed here.
Main Class
public static void main(String[] args) {
.....
Activities coldDrink = new Activities("string", 1, 1, {"string", "stringOne", "stringTwo"});
....
}
Activities Class
public class Activities {
private String activityName;
private int numberEssentialSensors;
private int numberOptionalSensors;
private ArrayList sensorList = null;
Activities(String actName, int essSensors, int optSensors, ArrayList arrayValues) {
this.activityName = actName;
this.numberEssentialSensors = essSensors;
this.numberOptionalSensors = optSensors;
this.sensorList = arrayValues;
}
{"string", "stringOne", "stringTwo"} is an array initialization expression, not an ArrayList. You can use new ArrayList(Arrays.asList("string", "stringOne", "stringTwo")) instead.
It would be better to use ArrayList<String> instead of the raw type though.
Activities coldDrink = new Activities("string", 1, 1, new ArrayList<String>(Arrays.asList("string", "stringOne", "stringTwo"));
I have a problem where each element of my array seem to be reassigned.
class Car {
private static int nom = 0;
private static String whee = "";
public void setCar(int r, String s) {
this.nom = r;
this.whee = s;
}
}
class Rawr {
private Car[] jar = new Car[3];
public Mar() {
jar[0] = new Car();
jar[1] = new Car();
jar[2] = new Car();
jar[0].setCar(2, "yar");
jar[1].setCar(3, "tar");
jar[2].setCar(4, "sars");
}
}
If I printed it like jar[0].nom + jar[0].whee + jar[1].nom + jar[2].whee + jar[3].whee, the output would be
4 sars 4 sars sars
It's because your variables are static i.e. they belong to the class, rather than to an instance. Take a look at Java Tutorials | Understanding Instance and Class Members for more information about what this means.
You should remove the static keyword, so that they become instance variables.
Change
private static int nom = 0;
private static String whee = "";
to
private int nom = 0;
private String whee = "";
static means the variable is shared by all instances. (The fact you can use this to refer to static variables is a Java oddity.)
Your nom and whee fields are static. This means that they are tied to the class, and not to the object (instance) of the class.
Thus, when you assign a new value to this.nom, in reality, you assign a the value to Car.nom. The compiler allows referring to static variables through an object, but it's very bad practice. You should always refer to static fields by their class : Car.nom, Car.whee. This makes it clear that the nom and whee are static, and thus shared by all instances of the class. In this case, these fields should not be static : each Car instance has its own name and whee (whatever it might be).
A better way to structure your code is as follows.
class Car {
private final int nom;
private final String whee;
public Car(int nom, String whee) {
this.nom = nom;
this.whee = whee;
}
public String toString() { return num + " " + whee; }
}
class Rawr {
private final Car[] jar = {new Car(2, "yar"), new Car(3, "tar"), new Car(4, "sars")};
public String toString() {
return Arrays.toString(jar);
}
}
I'm trying to create a class with static variables, but I'm not sure how to set the variables before runtime. This is what I'm attempting to do...
public class Defaults {
public static String[] abc = new String[2];
public static void functionToExecuteBeforeRuntime{
abc[0] = "a";
abc[1] = "b";
abc[2] = "c";
}
}
It's supposed to set abc using functionToExecuteBeforeRuntime before runtime so other classes can access it with Defaults.abc,however it is never executed. How can I achieve this? Any help appreciated
-oh i'm not sure if this makes a difference but I don't think with andriod I can use the public static main() guy
For that example, you could just initialize it there, like:
public static String[] abc = new String[]{"a", "b", "c"};
For just a general way of doing complex initialization for your static fields, I'm not sure, but I believe Android has Static Initializer Blocks, which work like:
public class Test
{
public static String[] stuff = new String[2];
static
{
stuff[0] = "Hi";
stuff[1] = "Bye";
}
}
Or you could use static functions to do, basically, the same thing.
public class Test
{
public static String[] stuff = initializeStuff();
public static String[] initializeStuff()
{
String[] arr = new String[2];
arr[0] = "Hi";
arr[1] = "Bye";
return arr;
}
}
Put it into a static initialization block of code like so:
private static String[] stuff;
static {
stuff = new String[] {"1", "2"};
}