This question already has answers here:
Assigning variables with dynamic names in Java
(7 answers)
Closed 5 years ago.
Okay so for what I am doing i need to increment my variables name, so for example
int Taco1 = 23432.....
int Taco2 = 234235656.....
int Taco3 = 11111.......
But instead i need it to be a variable like
int X = 0;
some method with loop or recursion()
int Taco(X) = bla bla bla
x++
Trying to get my variable names to auto name themselves incremented by 1 every time, so they don't overwrite themselves. If this is impossible then my apologies.
You can't do this in Java and more importantly, you don't want to do this as this isn't how Java works. In fact variable names aren't nearly as important as you think and hardly even exist in compiled code. What is much more important is that you are able to get a reference to your objects in as easy and reliable a way as possible. This can involve an array, an ArrayList (likely what you want here), a LinkedList, a Map such as a HashMap, a Set, and other types of collections.
For example:
List<Taco> tacoList = new ArrayList<Taco>();
for (int i = 0; i < MAX_TACOS; i++) {
tacoList.add(new Taco(i));
}
Indeed it is impossible to generate identifier names based on a variable. Perhaps what you want is an array:
int[] Taco = new int[ 15 /*some appropiate upper limit*/ ];
Taco[X] = bla bla bla;
Search the web for basic information on what arrays are and how they work.
Use an int[] or a List<Integer>:
int[] tacos = new int[numberOfTacos];
// in some loop or whatever
tacos[x] = someValue;
use array of int. say int taco[50]; and you can reference each location as taco[0],taco[1] etc
I TacoX is going to be an integer, I would create an array of X ints. If the max number is 10, we have:
int[] taco = new int[10];
Then to modify/read tacoX, you just look at taco[X]
Related
When declaring and assigning primitives before loop everything works fine and could be different from each other later on
//example
double sum1, sum2, sum3, sum4;
sum1 = sum2 = sum3 = sum4 = 0;
//later each gets own value correctly
Is it possible to make oneliner for an array?
//example
double[][] compare, updated; // works as intended
compare = updated = new double[SIZE][]; // makes compare=updated
Problem with second line is that it ignores all following calculations for updated and takes values from compare.
If by "one-liner" you mean a single statement and writing new double[] once, yes you can do this:
double[] arr1, arr2;
arr1 = (arr2 = new double[10]).clone(); // this is the line
arr1[0] = 10;
System.out.println(arr2[0]); // 0.0
But it's not very readable. It gets even worse when you do this with more arrays:
arr1 = (arr2 = (arr3 = new double[10]).clone()).clone();
I suggest you still use multiple lines to do this.
As an alternative to #Sweeper's answer, consider using the Arrays.copyOf() method, as suggested in this answer. Note that the copyOf() method is type-safe whereas the clone() method isn't.
double[] a, b, c;
c = Arrays.copyOf((b = Arrays.copyOf((a = new double[10]), a.length)), b.length);
But again, I'll reiterate as #Sweeper does, that this code really smells and you should consider doing it in multiple lines. As Steve McConnell says in Code Complete 2nd Ed., the Primary Technical Imperative of software is to manage complexity (i.e. make your code simple). This doesn't necessarily mean reducing the lines of code, but more to do with enabling people who read your code to understand what it does at a glance.
Let's say I want to generate 20 random numbers on a 8 by 6 grid.(8 columns, 6 rows) . Based on the answer from here:Creating random numbers with no duplicates, I wrote my code like this:
Random randomNumGenerator = new Random();
Set<Integer[][]> generated = new LinkedHashSet<Integer[][]>();
while (generated.size() < 20) {
int randomRows = randomNumGenerator.nextInt(6);
int randomColumns = randomNumGenerator.nextInt(8);
generated.add(new Integer[][]{{randomRows,randomColumns}});
}
In reality what happens is the Set see Integer[][]{{5,5}}; and Integer[][]{{5,5}};as NOT duplicate.Why? Even tho my purpose is to get 20 non-duplicate pair of numbers, this does not work. How do I fix this?
The Set checks for duplicates using the equals method (and also the hashCode method) of its inner type, but the Integer[][]'s equals method compares the memory addresses and not the contents.
Why do you use a Set of Integer[][] if you just want to store pairs?
Unfortunately, in Java there is no Pair class, but if you do not want to create your own, you can use the Map.Entry for that.
Random randomNumGenerator = new Random();
Set<Map.Entry<Integer, Integer>> generated = new LinkedHashSet<>();
while (generated.size() < 20) {
int randomRows = randomNumGenerator.nextInt(6);
int randomColumns = randomNumGenerator.nextInt(8);
generated.add(new AbstractMap.SimpleEntry<>(randomRows,randomColumns));
}
System.out.println(generated);
Array equals is == in Java, so an array is only equal to itself. Normaly you use Arrays.equals(array1, array2) to compare them by content, but in this case, arrays are simply the wrong choice. You can either create a bean, as rafalopez79 suggested of use an array of Collections (List in your case), as a List will compare the content on equals, see the documentation. Choice is pretty much yours, a bean would probably be a bit cleaner.
How about this code. I ran it through the debugger, it works nicely and yes, the contains() method checks the value of the Integer, not the reference. You can change the range of the random number as needed, I used 5 to facilitate testing. Yes I know it's not very robust, as written this will be an endless loop (because of the limited range of 5) but it's a simple example to make the point.
UPDATE: Actually this has a bug in that it won't check for uniqueness across all the rows, but that's easily fixed as well. I just re-read the original question and looking at the original code I'm not sure I know what you want exactly. If you just want a grid with 48 unique Intergers arranged 8 by 6 this will do it, but there are several ways to do this.
final int rows = 6;
final int cols = 8;
Random randomGenerator = new Random();
ArrayList[] grid = new ArrayList[rows];
for(int i=0; i<rows; i++)
{
grid[i] = new ArrayList<Integer>();
for(int j=0; j<cols; j++)
{
for(;;)
{
Integer newInt = new Integer(randomGenerator.nextInt(5));
if(!grid[i].contains(newInt))
{
grid[i].add(newInt);
break;
}
}
}
}
I'm trying to get a program so that it loops and adds up the sum of an array. My code appears to be working, with the exception that it states that the text[j] in adding = adding + text[j] is an incompatible type (I'm assuming data type). Earlier in the code, I have int adding = 0;. This is the erroneous code:
for (int j=0;j<=total;j++){
adding = adding + text[j];
System.out.println(text[j]);
}
where total is the limiting factor. If I put:
for (int j=0;j<= total;j++){
adding = adding + j;
System.out.println(text[j]);
}
the program compiles but gives 45, which is incorrect.
Why is this happening? Thanks!
The answer actually turned out to be outside the code given. I had set my array to be a String, not an int as it should have been.
If your text[] is String[] or char[] as the name suggests then I believe you are trying to update text[] elements with suffix j or adding, which you can write as:
If it is char[] then write
text[j] = (char)(adding + (int)text[j]);
If it is String[] then write
text[j]= text[j]+adding;
as required. It all depends on what is the data type of text[] and what are you trying to achieve?
Also as suggested in one of the answers, if total is length of the array, then change the comparison to < to avoind ArrayIndexOutOfBoundsException
Your second example, adds j into adding but prints text[j] value, which is nothing to do with the addition of adding and j.
So, I have to make a random number generator to get numbers ranging from 0 to 400. I'm putting these into an array and then sorting them later on. I just am not sure how to go about doing this. I was given something along the lines of;
public int nextInt(400) //gives me errors
{
random.setSeed(12345L);
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
}
I've already called the random class, since the directions indicated that. I just don't know why this is not working. It's giving me errors especially with the first part; class, interface, or enum expected. Could somebody steer me in the right direction please?
Functions in Java (all programming languages) have "variables" in their definition.
You've got:
public int nextInt(400)
Over here, you want your 400 to be a value that is passed to the function.
Think of this as math. I'm sure you've dealt with something like f(x) = 2 * x. Here, x is the variable, and you "evaluate" f(x) with a value for x. Similarly, in programming, we'd have something like :
public int nextInt(int x)
As you see, our function defines x to be of type int. This is necessary in a language like Java because you're telling the compiler that this function will only accept integers for x.
Now that you've done that, you can use x as a variable in the body of your function.
Note that whenever you use a variable, it first has to be defined. A line such as:
int variable;
defines variable as an int.
Your program is missing these for random, val, arr, and a. Note here that arr and a are arrays (and somehow I get the feeling that they should not be two separate variables).
You should really brush up on variables definitions, arrays, and functions before attempting this question. Your best resource would be your textbook, because it'll explain everything in an organized, step-by-step manner. You can also try the many tutorials that are available online. If you have specific questions, you can always come back to StackOverflow and I'm sure you'll find help here.
Good luck!
You need to define this function within a class definition
even you have specified :
public int nextInt(400)
in this line function returns int and in your whole body u didn't have any return statement.
and yes as Kshitij Mehata suggested dont use 400 directly as value use variable over there.
this should be your function:
public int[] nextInt(int x) //gives me errors
{
random.setSeed(12345L);
int[] a=new int[arr.size];
for (int i = 0; i < arr.size; i++)
{
val = random.nextInt(400);
a[i] = val;
}
return a;
}
even there is some issue with arr from where this arr come?
Is there a way to do the following at the same time?
static final int UN = 0; // uninitialized nodes
int[] arr;
// ... code ...
arr = new int[size];
for (int i = 0; i < 5; i++) {
arr[i] = UN;
}
Basically, I want to declare arr once I know what its size will be and initialize it to UN without having to loop. So something like this:
int[] arr = new int[size] = UN;
Is this possible?
Thanks.
Arrays.fill(arr, UN);
You don't need to initialize them with 0. An int defaults to 0 already.
Just
int[] array = new int[size];
is enough. It gives you an array of zeroes of the given length. If it were an Integer[], it would have been an array of nulls.
Well, in the case of objects (or primitives with autoboxing) you can do the following:
int count = 20;
final int UN = 0;
Integer[] values = Collections.nCopies(count, UN).toArray(new Integer[count]);
The downsides are that you have to use the object forms of the primitives (since the Collections must be of objects) and a separate List will be constructed and then thrown away. This would allow you to create the array as one statement however.
No, not with the standard libraries. If you write your own functions, though, you can easily do so in a single statement (not instruction; those are different). Mine looks like String[][] strings = Arrayu.fill(new String[x][y], "");
Here's a link. There's some junk in there too, though; I just posted a copy of the current source directly without cleaning it up.
No.
Next question?
int arr[] = { 0, 0, 0, 0, 0 };
Oops, read your question better:
You can init an array like so
int[] arr = new int[] {UN, UN, UN, UN, UN};
But ofcourse, if you don't know the size at compile time, then you have to do the for loop. The second technique is not possible.