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"};
}
Related
I just saw this tutorial creating multiple objects using the same instance by applying the DAO pattern and tried it in a simple console, but I always get this message java.lang.NullPointerException I'm now confused, as far as I know, a constructor can be used once only, and the object will be immutable. Kindly look at this:
Fighter.java
public class Fighter {
private String style;
public Fighter() {}
public String getStyle() {
return style;
}
public void setStyle(String style) {
this.style = style;
}
}
FightersDAO.java
public class FightersDAO {
public List<Fighter> getFighters(){
List <Fighter> fighter = new ArrayList<>();
String [] styles= { "Karate", "Sumo", "Pro-Wrestling" };
for(int i=0; i < styles.length; i++) {
Fighter temp = new Fighter();;
temp.setStyle(styles[i]);
fighter.add(temp);
}
return fighter;
}
}
Demo.java
public class Demo {
private static FightersDAO fighterDAO;
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle()); //this should output the objects, but nothing shows
}
}
}
Why is it null? What part did went wrong
The variable fighterDAO is never initialized. Therefore you get a NPE here:
List <Fighter> fighters = fighterDAO.getFighters();
To fix that use:
private static FightersDAO fighterDAO = new FightersDAO();
private static FightersDAO fighterDAO;
I think there is a problem because it is not initialized.
Change it:
private static FightersDAO fighterDAO = new FightersDAO();
In your code
private static FightersDAO fighterDAO;// here is not initialized. its just a declaration so fighterDAO = null;
while executing below code will throw exeption
List fighters = fighterDAO.getFighters();// means null.getFighters();
Below is the correct code
package aks;
import java.util.List;
public class Demo {
private static FightersDAO fighterDAO= new FightersDAO();
public static void main (String [] args) {
List <Fighter> fighters = fighterDAO.getFighters();
for(Fighter e: fighters) {
System.out.println(e.getStyle());
}
}
}
You can analyse this by just debuggin on eclise or any IDE
If you want same instance use below code
private static FightersDAO fighterDAO = new FightersDAO();
I am calling a library method on a fluent API that takes a var args of Strings. when I call it I always pass at least three strings and then a few more depending on circumstance.
Can have a final static array or something to capture the three Strings that are always passed?
Perhaps something like this:
public class Overloaded {
private static final String[] CONST_ARR = {"1", "2", "3"};
public static void main(String[] args) {
Overloaded o = new Overloaded();
o.withConstantStrings();
String[] a = {"1", "2"};
o.withAdditionalStrings(a);
}
public void withConstantStrings() {
libraryVarArgsCode(CONST_ARR);
}
public void withAdditionalStrings(String... additional) {
String[] join = new String[additional.length + CONST_ARR.length];
System.arraycopy(CONST_ARR, 0, join, 0, CONST_ARR.length);
System.arraycopy(additional, 0, join, CONST_ARR.length, additional.length);
libraryVarArgsCode(join);
}
public void libraryVarArgsCode(String... args) {
// librabry code here
}
}
Here is an idea:
static final String[] RESERVED = {"A", "B", "C"};
...
libMethod(Stream.concat(Arrays.stream(RESERVED), Stream.of("D")).toArray(String[]::new));
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?
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 );
Im building a lexical/syntex analyzer for class. The problem I am having is when I try to access my static variable "lexems" or "tokens" from a method besides main they are NULL. When I use them in main (such as the lex.printList method) they are fine and filled with data.
Whats going on???
import java.io.IOException;
import java.util.ArrayList;
public class SyntaxAnalyzer {
public static int pos = 0;
public static ArrayList<String> lexems = new ArrayList<String>();
public static ArrayList<String> tokens = new ArrayList<String>();
public static String nextToken;
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
static void lex(){
//String lexem = lexems.get(pos);
//System.out.println(lexem);
nextToken = tokens.get(pos);
pos++;
}
}
You are overriding the lexems object with the local one so it is not static variable you are modifying inside main function.
To operate on the static one you should do
/*NOTHING HERE!!*/ lexems = lex.getLexems();
lex.printList(lexems);
...
The same issue with tokens occurs
/*NOTHING HERE!!*/ tokens = lex.getTokens();
lex.printList(tokens);
...
The problems are here:
ArrayList<String> lexems = lex.getLexems();
lex.printList(lexems);
ArrayList<String> tokens = lex.getTokens();
In you main function you do not modify the static variables but local ones (local in the main function).
Just change it to that:
lexems = lex.getLexems();
tokens = lex.getTokens();
You are creating another pair of variables in your main method, which happen to have same names as your static variables, and "overshadow" them within the scope of main method.
To fix it, you should not declare new variables, but initialise the existing ones:
public static void main(String[] args) throws IOException {
LexicalAnalysis lex = new LexicalAnalysis();
lex.getFile();
lex.parseText();
lexems = lex.getLexems();
lex.printList(lexems);
tokens = lex.getTokens();
lex.printList(tokens);
//expr();
lex();
}
This should help make the difference between the scopes used in your code :
public class MyClass{
private static int myInt;
public static void main(String[] args){
int myInt = 6;
printMyInt();
}
static void printMyInt(){ System.out.println(myInt); } // Prints 0 because uses the class field
}