How to use method in the name of variable? - java

I have to create a few variables like: "n23, n4, n18...".
So, they consist of two parts: letter "n" and a number witch I want to get from my method for generating random numbers(rand()).
Something like this:
for(int i = 0; i < 6; i++) {
int n*here_must_be_random_number_got_from_my_method*;
}
Is it possible to do something similar?

Java is no script language.
All identifiers, which means all package names, type names, method names, field names and variables, must be specified at compile time. So there is no way to concatenate your variable names based on values calculated at runtime.
BUT!
You do not even need to. Just use a java.util.Map. Instead of doing
int n*here_must_be_random_number_got_from_my_method* = *whatever_it_is_you_want_to_put_here*;
you can instead do
Map<Integer, Integer> myMap = new HashMap<>();
once, then put values inside the map like so:
myMap.put(*here_must_be_random_number_got_from_my_method*, *whatever_it_is_you_want_to_put_here*);
and get it back like so:
myMap.get(*here_must_be_random_number_got_from_my_method*);

You can't, but presumably you want to refer to these later, and if you were intending to refer to n123, then you can hopefully refer to them as n[123] instead. If that's the case, then you can use a java array, perhaps like this:
private int[] n = new int[999];
void populate() {
for(int i = 0; i < 6; i++) {
n[here_must_be_random_number_got_from_my_method] = something;
}
}
Note that java doesn't do sparse arrays, so the size of your array needs to be as large as the largest random number. If this us large, consider using a map as per Jan's answer.

Related

Sorting an object array into another array based on a variable

I have a problem with a program I'm writing for a school assignment.
Essentially, before this piece of code, I already recieve and work with a bunch of information that I store into an array of objects. Now I have to sort this array (after it's sorted, I will have to calculate some things in the order of the PRIORITY variable).
presume I already have a MyClass[] array called input, that stores a finite amount of MyClass objects.
MyClass[] priorityArray = new MyClass[input.length];
for (int i=0; i<priorityArray.length; i++) {
int maxIndex = 0;
int maxPrivilege = input[i].returnPrivilege();
for (int j=1; j<input.legnth; j++) {
int currentPrivilege = input[j].returnPrivilege();
if (currentPrivilege > maxPrivilege) {
maxPrivilege = currentPrivilege;
maxIndex = j;
}
}
priorityArray[i] = input[maxIndex];
input[maxIndex].setPrivilege(-900000000);
}
the MyClass class if nothing fancy, but of course, contains a proper constructor, getter and setter methods and an integer variable "privilege".
I'm getting an error in my final tests of the program and, seeing as the program returns privileges as "-900000000", it has to have something to do with this part of the code.
It's also not even writing certain MyClass instances from the input array into the priorityArray array.
How can I clead this up? Help.
I'll rewrite my answer totally.
In this line
priorityArray[i] = input[maxIndex];
You are assigning object from one array to another array by reference. It means that there is only one object and you set value to -9000000 in the next line to it. Of course element in priorityArray will have the same changes. To fix it you need to clone your object here.

Tool for transforming variables of different types in Java

Suppose I want to perform some non-trivial(not just though type casting) transformations for a variable v, e.g., from type T1(String) to T2(List):
String v = "123";
List<Integer> list = new ArrayList<Integer>();
One solution will be like this:
for(int i = 0; i < v.length(); i++) {
char c = v.charAt(i);
int intVal = Character.getNumericValue(c);
list.add(intVal);
}
However, if the transformations are performed among various types, manually permuting solutions for all the patterns will be both tedious and inefficient.
The question is, is there any tool to do this kind of transformation automatically?
Thanks,
The thing you are asking for, (im assuming a sort of catch-all typecasting tool that could work for almost anything) doesn't exist. It wouldn't really make sense for something like that to be built in because there are so many different ways people would want some object to be represented in other formats.
If you wanted to have a tool to transform a string into an array of ints, then you can easily make that tool yourself, something like
ArrayList<Integer> stringToArray(String v)
{
List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < v.length(); i++) {
char c = v.charAt(i);
int intVal = Character.getNumericValue(c);
list.add(intVal);
}
return list;
}
Making your own functions to change from one object type to another is the best way to go about this.

Using class variables in methods

In java how to use class variables in methods?
this is the code that I have
public class ExamQ3a {
String[] descriptionArr = new String[50];
static int[] codeArr = new int[50];
public static void displayItems(int count, int[] codeArr,
String[] descriptionArr) {
count = this.codeArr.length;
for (int i = codeArr.length; i < codeArr.length; i--) {
}
}
}
The line that is being highlighted here is the count = this.codeArr.length; the error that I am getting is that the non-static variables cannot be referenced from a static context. But I already made the variable static. So what gives?
So as per request only! not that I want to ask the whole question, just to know why I want to use static, this is a practice question
You are to develop a simple application system to manage the inventory
in a company. The system should be able to maintain a list of up to 50
items. Each item has a unique integer code and a description.
(a) Write Java statements that declare and create two arrays to store the
code and the description of the items.
(b) Write Java method with the following method signature:
public static void displayItems(int count, int[] codeArr, String[] descriptionArr)
This method displays the code and description of all items in the company
in tabular form with appropriate column heading.
Parameters: codeArr: the array that stores the codes of the items
descriptionArr: the array that stores the descriptions of the items
count: the number of items in the system
There is no this in the static world. Get rid of it. To explain, this refers to the current instance, and when you're dealing with static methods or variables, you're dealing with items associated with the class, not with any one particular instance. So change the code to:
count = codeArr.length;
Edit 1
As an aside, you don't want to bunch up your closing braces like } } } which makes your code very difficult to read and follow. White space is free, so might as well use it judiciously to improve code readability.
Edit 2
You state:
so how would I reference the array codeArr to the class variable codeArr?
You're inside of the class, and there's no need to use the class variable name here since it is assumed to be used. Just use the static variable or method name and you should be golden.
Edit 3
Your use of static for this type of variable gives the code a bad smell. I'm thinking that your entire program would be much better off if this were an instance variable and not a static variable. For more discussion on this, you may tell us why you decided to make the variable static.
Is you're going to reference a static variable having the same name as a method parameter you prefix the static variable with the name of the class. In this case it would be ExamQ3a.codeArr.
The other way to handle this is to pick different names for your method parameters, or start using a common prefix for instance/static variables.
Another point to note is that, in the following piece of code statement1 will never be executed:
for (int i = codeArr.length; i < codeArr.length; i--) { statement1; }
it should be either
int length = codeArr.length;
for (int i = 0; i < length; i++) { ... }
or
int length = codeArr.length;
for (int i = (length-1); i > -1 ; i--) { ... }

in java, is it possble to name an array from a string?

I am a beginner with java, and I was wondering is if is possible to name and create an array from the value of a string.
Here is what I have:
public static void array(){
createArray(array1, 100, 100);
}
public static void createArray(String name, int r, int c) {
int[][] name = new int[r][c];
}
I hope that explains itself. Thanks
EDIT: The code above does not work. I just want to know if it is possible to do what is above
EDIT2: As a beginner with java, I am just watching tutorials, and creating programs with what I learned to make sure I understand what is being taught. I first created a program which creates s multidimensional arrays. It then calls a method which assigned values to the array, (row+1)*(column+1). This makes a table much like a multiplication table. Then it displays the table to the screen.
After I created that program, I wanted to be able to create arrays much like I assigned the values to it. So i asked this question...
Here is my code:
public static void array(){
int[][] array1 = new int[100][100];
int[][] array2 = new int[20][20];
setArrayValue(array1);
setArrayValue(array2);
drawArray(array1);
System.out.println();
drawArray(array2);
}
public static void setArrayValue(int x[][]){
for(int row = 0; row<x.length; row++){
for(int column=0; column<x[row].length; column++){
x[row][column]= (column+1)*(row+1);
}
}
}
public static void drawArray(int x[][]){
for(int row=0; row<x.length; row++) {
for(int column=0; column<x[row].length;column++){
System.out.print(x[row][column] + "\t");
}
System.out.println();
}
}
Your concept doesn't make sense.
You might want to use a Map<String, int[][]>, which will map names to arrays.
What you are trying to do is not possible in Java. In the createArray method, name is of type String and cannot be redeclared as an int array.
Perhaps you are interested in a Map that uses String objects as keys? The values could be int arrays (or any other object).
No, you can't do that.
Variable names are not variable in Java.
Furthermore, local variables even lose their names when the code is compiled. Variable names are just a help for the programmer to distinguish between variables.
Nop can't be done. Variable names need to be known before hand.
No, it is not possible. You might be able to accomplish your task with a TreeMap or another Map implementation instead.
Instead of saying
name = something;
You would say
map.put(name, something);
Instead of
name[0] + 7
You'd say
map.get(name)[0] + 7
As stated by others - this cannot be done. That is because Java compiler needs to know exact name of a variable at the compile time. This is mandatory, since otherwise Java compiler wouldn't know which variable you are addressing, so it couldn't perform, for instance, type-safety checks.
However, if you just wish to stamp your variable with some unique ID, I guess the solution is closest to what has been stated by SLaks. Simply use Map, and You should be good. Example below.
Map<String, int[][]> myMap = new HashMap<String, int[][]>();
myMap.put("someUniqueName", new int[][] {{0,0}, {1,1}});
and later on:
int[][] array = myMap.get("someUniqueName");
Hope that helps achieve what You want.
Strictly: almost ;-) You can add a dynamic field in a class, which could be an array, using AOP. But...
It's difficult.
This solution is too complicated in most cases. You could probably solve your real problem in a much easier way.
Some advice: start with the beginning... and try using List (interface) / ArrayList as much as possible unless you have some pretty good reason to use an array.

How do I copy a two dimensional array of strings?

I'm working with a program that uses two-dimensional arrays of Strings (probably not that smart to begin with, but eh), and I'd like to write a function that takes one of these arrays (let's say array1), makes an independent copy, and returns it (let's say array2). However, when I then change a value in array2, it seems to be reflected in array1.
My function currently looks something like this:
public static String[][] copy(String[][] matrix, int n) {
String[][] out = new String[n+1][n+1];
for (int i = 0; i < n+1; i++)
for (int j = 0; j < n+1; j++) {
if(matrix[i][j] != null) {
String cp = new String(matrix[i][j]);
out[i][j] = cp;
}
}
return out;
}
I declare a new array of Strings, and then iterate through it, copying each value individually. When that didn't work, I even tried explicitly declaring a new string from each old string and putting that in the array instead.
Can anyone tell me where I'm going wrong?
I'm not sure what the n parameter is for, but if I needed such a function, I'd use something like this:
public static String[][] copy(String[][] matrix) {
String[][] copy = new String[matrix.length];
for (int idx = 0; idx < matrix.length; ++idx)
copy[idx] = matrix[idx].clone();
return copy;
}
You don't need to create a copy of the String, because they are immutable. As pointed out by Michael in the comments, the String(String) constructor might be useful if the original string was created as a substring of some very large string. Another use is when you are using String objects as locks (not recommended), and want a private instance to avoid deadlocks.
Also, your check to see whether an element is null before assigning is unnecessary; if you have your loops setup correctly, the element is guaranteed to be null. (And if it's not, what's the harm in overwriting it?)
Your method looks like it should work, though passing in n as a parameter makes it brittle, using the input array's length field would be better, and you could even handle jagged arrays that way.
Making a copy of the contents is not necessary, since Strings cannot be changed - which leads to the main question: What kind of changes are you making that seem to be reflected in the copy? Show us the code that does this.
Have a look at System.arraycopy. That way you can get rid of the inner loop.
Maybe Arrays.copyOf would be of some use?
I tried with your code : got exception
java.lang.ArrayIndexOutOfBoundsException
It's working for me, please try like this :
public static String[][] copy(String[][] matrix, int n)
{
String[][] out = new String[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if(matrix[i][j] != null) {
String cp = new String(matrix[i][j]);
out[i][j] = cp;
}
}
return out;
}
Take a look at this question Is Java pass by reference? It can be a little confusing how Java passes objects, but this would explain why making a change to one array also makes the change to your other array.
Your use of the 'n' parameter, as noted above is redundant, but also flawed by your code with n+1?? Your code would produce an ArrayIndexoutOfBoundsException if run something like:
String [][] m1 = { {"A", "B"}, {"C", "D" } };
String [][] m2 = copy(m1, 2);
Which presumably is how you intend it to be invoked?
It also limits your function to square 'matrices' of Strings.
But as for the problem you cited, I see no reason why the program should behave that way... I even ran it using the above call (but with n=1???) then changed
m2[0][1] = "X";
and m1 was unaffected as expected.
Even replacing the innermost code line to:
out[i][j] = matrix[i][j];
does not change this, as the compiler rewrites it to what you originally had. In fact a lot of the String sytax is simply syntactic sugar for StringBuffers (such as concatenation and assignment). eg the compiler will rewrite
String s = "Hello ";
s += "World"; // Makes it appear that String is builtin type!
to
String s = new String("Hello ");
s = new StringBuffer(s).append("World").toString();
Which is why is you have lots of string concatenation inside loops they can perform very poorly.
I do not understand why you are having the problem you cited either.
And as you are not modifying the parameter 'matrix', 'Pass By Reference' has nothing to do with it.

Categories