Using static array - java

I am novice programming. I am using java. I have declared an array like this:
static String horario[];
later, in one method I want to use this array like this:
if(datos.get(z+3).contains("CET")) {
horario[]= (datos.get(z+3).split("CET"));
mipartido.setHorario(horario[0]);
}
but it says that horario cannot be resolved to a type.
How can I use this variable?

You shouldn't use [] unless you're assigning an element to a specific index of the array, for example: horario[0] = "abc";
So, since you're assigning the array, you should change:
horario[]= (datos.get(z+3).split("CET"));
to:
horario = (datos.get(z+3).split("CET"));

Related

Calling get (array static method) from an array instance

New to Java, and OOP in general.
I'm doing an online Lynda course, and in the course there's an example of using Array.get to extract the 2nd item from an array:
String[] myFavoriteCandyBars = {"Twix", "Hershey's", "Crunch"};
System.out.println(Array.get(myFavoriteCandyBars, 2));
And the instructor explained that get is a static method from the "Array" class.
But when I tried defining:
`Array[] testarray = new Array[10];`
And using:
`testarray.get(testarray[10]);`
I get an error:
cannot resolve method 'get(java.lang.reflect.Array)'
But I don't understand why - the testarray is an object of class Array, and class Array has a method "get", so although it's bad practice, why can't I do it?
The Array class is an internal Java class containing only public static methods, and its intended use is to not be be directly instantiated. The following code:
testarray.get(testarray[10]);
fails because testarray is of type Array[], not Array, and therefore does not have the static method get() available. Hypothetically speaking, if you could call Array#get on an instance, it should work, but as mentioned above, Array cannot be instantiated.
A more typical way to use Array would be something like:
String[] testarray = new String[10];
testarray[1] = "Snickers";
System.out.println(Array.get(testarray, 1));
That is, create an array of the desired type, and then use Array#get to access whichever element you want.
get() is not a method in the array class, (as in a byte[] object). get() is in the Array class. Doing Array.get(testarray, 0) is what you want. Despite that, don't do this, do testarray[0] instead.
Whenever you use a static method, you shouldn't call it from an object, you should use the class instance, so instead of doing
Object o = new Object();
o.staticMethod();
Do:
Object.staticMethod();

create variables dynamically, Data Types of java Variables

As we know variables are of different data types, but which data type are their names of?
As it seems they are String, but if they are String then this should be allowed:
int i=6;
String [] arr+i;
...as we can add an int to a String.
So if these are not String then what are they?
And if we want to create variable names dynamically how can we create it?
By dynamically I mean whenever the user clicks on a specific JComponent, a new variable is created, like:
int i=0;
//on first click
String str+i; ///str0
i++;
///on 2nd click
String str+i; ////str1
///i++;
How can I do it?
You can not create dynamic variables in Java because Java isn't a scripting language. YOu need to create variables in source code. But Java provides other ways to do this.
You can use arrays or Map<String, String> etc for this purpose.
Map<String, String> map= new HashMap<>();
int i=0;
while(true) {
// you can use whatever condition you need
details.put("key" + i, "val: "+i);
i++
// some condition to break the loop
}
Java identifiers are not of any type and definitely not String. You can't do this in java, instead, you use a data structure to use these values like ArrayList<String>and store the nth String in the nth index of the data structure like so:
ArrayList<String> strings= new ArrayList<String>(); // Create a new empty List
strings.add(index, string); //add string at index position of the List; can be replaced with strings.add(string) if the strings are being sequentially added
CONSIDER THIS:
public class Test {
public Test() {
}
public static void main(String[] args) {
// GenericType<Integer> intObj;//creates a generic type for integers
//String type
GenericType<String> strObj=new GenericType<String>("My data");
System.out.println("Value is " +strObj.getValue());
}
}
class GenericType<GT>{
GT obT;
GenericType(GT o){
obT=o;
}
GT getValue(){
return obT;
}
void showType(){
System.out.println("Type of GT is " +obT.getClass().getName());
}
}
GT is the name of a type parameter. This name is used as a placeholder for the actual type that will be passed to GenericType when an object is created. Thus, GT is used within GenericType whenever the type parameter is needed. Notice that GT is contained within
< >. This syntax can be generalized. Whenever a type parameter is being declared, it is specified within angle brackets. Because Gen uses a type parameter, Gen is a generic class, which is also called a parameterized type.
as mentioned above JAVA provide you with advanced generic classes such as ArrayList, Vectors, Hashmaps to cater for such scenarios .
previous thread similar: How to create new variable in java dynamically
Variable names do not have data types. They are merely references. They are not a String, they are not an int, they are just names. You can't dynamically declare a variable with a name derived from the name of another variable, Java does not work this way.
Java does not work this way. Other languages do but Java isn't one of them. You can't dynamically manipulate the names of variables because they are fixed at compile time. However, in some interpreted scripting languages such a thing is possible.
To be more accurate if they are fixed to be anything at all they are fixed at compile time. If java is not compiled in debug mode the names of the variables cease to be at all. They just become addresses of memory locations.
See this for details: Can I get information about the local variables using Java reflection?
Firstly variables can be categorized into two. primitives (standard ) types such as int, float,double, char,boolean, byte... and non-primitives(user defined)types such as String, Integer, Float, Double. String type fall under non primitive , its a class provided by java.lang Api such that when you create a string variable you are indeed creating an object EX String str; str is an object it can as well be declared as String str=new String();
hence the string class consist of helper methods that may help to achieve your objective, you can as well use concatenation/joining of strings as follows:
class Demo{
String str;
static int i;
JButton but=new JButton("click me!");
.....
public static void actionPeaformed(ActionEvent e){
Object source=e.getSource();
str="msg";
if(source==but){
String newStr;
newStr=str+i;
System.out.println(newStr);
}
}
}
where str may contain some message/text eg from label/elsewhere for every click

How to access a struct via an ArrayList in Java

I have following lines of code:
private ArrayList<wordClass>[] words;
and
public class wordClass {
public String wordValue = null;
public int val = 0;
public boolean used = false;
}
Is there anyway I can access wordValue, val, and used via words? Like words[5].val? I know I can do that if they are just in an array of wordClass, but I want a dynamic array to make it easier to add and subtract from the array.
And yes, I know the values should be private. Just don't want to write getters and setters yet.
Thanks.
Do you really want an Array of an ArrayList?
It doesn't seem correct.
In Arrays, you use [] to access (words[0]).
In ArrayLists, you should use words.get(0).
The way you have coded, you should use: words[0].get(0).val to get the very first value.
But I recommend you to review your words definition.
ArrayList Documentation: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Regards,
Bruno
Your code is a bit off for a dynamic array (Java has immutable arrays), so you need an ArrayList. Also, Java uses Capital Letters for class names (please follow the convention) -
// like this, changing wordClass to WordClass. Also, using the diamond operator
private ArrayList<WordClass> words = new ArrayList<>();
To access your WordClass fields you can use something like -
for (WordClass wc : words) {
if (wc.used) {
System.out.println(wc.wordValue + " = " + wc.val);
}
}
Note, you still need to create WordClass instances and place them into the words List.
Write wrapper classes for each value. e.g. What you call "getters".
Then call:
words[1].getWordValue() ==> None
Voila

Put String[] in a String[][]?

Ok, soo what I'm trying to do, I have an oject with a attribut which looks like String[][], and I want to fill this one by calling a function and fill this String[][], one by one.
So here is what I tried but I get an error telling me :
"The type of the expression must be an array type but it resolved to String"
When I try to do
Produit[NbrProduit][0] = Produit[0];
My code :
public String[][] Produit = new String[MAX_Produit][2];
public void GetInfo1(String Client, String[] Produit,int NbrProduit){
Produit[NbrProduit][0] = Produit[0];
Produit[NbrProduit][1] = Produit[1];
Produit[NbrProduit][2] = Produit[2];
I don't understand why I get this because I'm filling a String field with an another String, right ? no ?
Sorry for my english.
Your parameter name (a 1D array) is the same as your instance variable name (a 2D array), so you're actually referring to your parameter only. Either use a different name (recommended), or use this.Produit when referring to your 2D array.
i.e.
public void GetInfo1(String Client, String[] produitParam,int NbrProduit){
Produit[NbrProduit][0] = produitParam[0];
Produit[NbrProduit][1] = produitParam[1];
Produit[NbrProduit][2] = produitParam[2];
Produit is a two dimensional String array, which means each of its element will be a string array. So you need to assign the element with the array of String and not just one String. Try this if it makes sense for your logic:
this.Produit[NbrProduit][0] = Produi;

Simple way to re-assign values in an array

I'm having trouble reassigning values in an array.
public static void main(String[] {
int[] arrayOfIntegers = new int[4];
arrayOfIntegers[0] = 11;
arrayOfIntegers[1] = 12;
arrayOfIntegers[2] = 13;
arrayOfIntegers[3] = 14;
arrayOfIntegers = {11,12,15,17};
}
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?
Because Java doesn't have destructuring assignment like some other languages do.
Your choices are:
Assign a new array to the array variable as shown by Rohit and Kayaman, but that's not what you asked. You said you wanted to assign to the elements. If you assign a new array to ArrayOfIntegers, anything else that has a reference to the old array in a different variable or member will still refer to the old array.
Use System.arraycopy, but it involves creating a temporary array:
System.arraycopy(new int[]{11,12,15,17},
0,
ArrayOfIntegers,
0,
ArrayOfIntegers.length);
System.arraycopy will copy the elements into the existing array.
You need to provide the type of array. Use this:
arrayOfIntegers = new int[] {11,12,15,17};
From JLS Section 10.6:
An array initializer may be specified in a declaration (§8.3, §9.3, §14.4), or as part of an array creation expression (§15.10), to create an array and provide some initial values.
If you are trying to re-assign array elements in some range, you can't do that with direct assignment. Either you need to assign values at indices individually, or use the way as given by #TJCrowder in his answer.
The correct syntax is:
arrayOfIntegers = new int[]{11,12,15,17};

Categories