Returning arrays and looping - java

I am new to Java and am assigned to design a program that grabs input from a file and inserts it to certain parts of an array, then exports that data. I have the code to read the file into a string array.
Two questions:
1.) How can I create a loop to create a numbered list with blank data following it? (see my code snippet below) I am trying to create a list that looks like the following:
1 0000 0000 00000 ...
2 0000 0000 00000 ...
Do you see any issues with my loop below?
for (int x = 0; x < array.length; x++) {
array[x] = Integer.toString(y);
y++;
while (x < 16) {
x++;
array[x] = "00000";
}
}
2.) Can I use a single method to return two array values? I would like two arrays filled, then their values returned for use in other methods. I found a method I could use, but I'm not sure how to go about properly implementing it.
I have a code snippet below:
public static Object[] rtrStr() {
//...blah blah
return new Object[]{array1, array2};}

2) You can return an array (or List) of arrays, if you wish:
public static String[][] rtrStr() {
// ...blah blah
String[][] arr = new String[][2]; // syntax might not be exactly correct
arr[0] = array1;
arr[1] = array2;
}
Note: I'm unsure about the exact syntax on the noted line, but the idea is sound. Personally, I would prefer using a List instead.
With that said, you should consider the meaning of the data in each array. It might make sense to create a custom class which wraps the array and clarifies the semantics. This also makes it easier to return an array or List from any method since the elements will be objects of your new custom class.

Do you see any issues with my loop below?
Yes, multiple: Your code is what I would call bad code. Even if it does what you want (and I'm not sure of that), it's extremely difficult to understand for such a simple task.
You're using x and y as counter-variable names. Don't do that when more than one counter is involved! It's hard to understand exactly what counter is counting what.
Your inner loop is messing with the counter-variable of your outer loop. If that was by design, don't ever do this. It makes the code very difficult to understand.
Also, if the array should hold something like a table (rows and columns) like in your example output, you'll need a two-dimensional array.
Can I use a single method to return two array values?
Yes, why not? You're actually returning one array with two values. You can however not return two arrays from a single method.

Related

User defined Array dimensional and size

I have unsolvable task, I have task, where i have insert random number to array. The user can choose if array is 1D, 2D, 3D,size of array is optional . I tried everything but withot success. I can not use ArrayList.
Thank you for help.
double[] array= new double[size];
for ( int i;i<dimensional;i++)
{
double[] array= new double[size];
}
Edit:
I mind if is effective way to create array with 1D and then add to this array one or more dimension.
Multi-dimensional arrays in java are essentially just arrays of arrays. The user provides the number of dimensions and sizes at runtime so you need to dynamically build this array at this point. It's a strange problem, and not one that you would try to solve with arrays in production code, but nevertheless it should be possible. Try the accepted answer for this question, it seems like a pretty good attempt.
So, an "unsolvable" task ... well, as long as you work with primitive types and the dimension can be theoretically any number (only limited by memory available), you may be right.
You can however use some kind of object (Java is an object-oriented language) and solve the task rather easily. Basically, you might want a tree structure with nodes. You can even write a constructor that sets fixed sizes for every level and give no direct accessors to the array as a whole. Start with:
class Node {
double payload;
Node[] children;
}
I don't really understand what do you want to do with that, but it pretty much fits the idea of N-dimensional array.
Another solution: Make the array one-dimensional, but using the sizes of the individual dimensions, you can calculate the correct index. Of course, it will require you to handle the logic.
E.g. in a 2D array of 3x3 size, you can use a 1D array of 9 size and use first three indexes for first row, next three for second row, last three for third row. You can then use a cycle like this:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//arr[i * 3 + j] = ...
}
}

Does java cache array length calculation in loops [duplicate]

This question already has answers here:
What is the Cost of Calling array.length
(8 answers)
Closed 7 years ago.
Lets say that i have an array which i would like to iterate over:
int[] someArray = {1,2,3,4}
for (int i = 0; i < someArray.length; i++) {
// do stuff
}
Will this length of aray be caclulated with each iteration or it will be optimized to calculate it only once ?
Should i iterate arrays by calculating the length in advance and pass that to a loop ?
for (int i = 0, length = someArray.length; i < length ; i++) {
// do stuff
}
From JLS 7
10.7 Array Members
The members of an array type are all of the following:
• The public final field length, which contains the number of components of
the array. length may be positive or zero.
Coming back to your question,java doesn't recount the number of elements in array on array.length. It returns the value of public final int length, calculated during array creation.
As always for performance: write the simplest code you can, and test it to see whether it performs well enough.
If you only need the element (and not the index) I would encourage you to use the enhanced-for loop:
for (int value : array) {
...
}
As per JLS 14.14.2 that's basically equivalent to your first piece of code, but the code only talks about what you're actually interested in.
But if you do need the index, and assuming you don't change array anywhere, I believe the JIT compiler will optimize the native code to only fetch the length once. Obtaining the length is an O(1) operation, as it's basically just a field within the array, but obviously it does involve hitting memory, so it's better for the eventual code to only do this once... but that doesn't mean that your code has to do this. Note that I wouldn't expect the Java compiler (javac) to perform this optimization - I'd expect the JIT to.
In fact, I believe a good JIT will actually see code such as:
for (int i = 0; i < array.length; i++) {
int value = array[i];
...
}
and be able to optimize away the array bounds checks - it can recognize that if it accesses the same array object all the time, that can't possibly fail with an array bounds error, so it can avoid the check. It may be able to do the same thing for more "clever" code that fetches the length beforehand, but JIT optimizations often deliberately target very common code patterns (in order to get the biggest "bang for buck") and the above way of iterating over an array is very common.
As length is the member of Array So it is already been set when you create an Array , On Each iteration you are only accessing that property nothing else .
So either you access it like
int myArrayLength=arr.length;
for(int i=0;i<myArrayLength;i++)
or like :
for(int i=0;i<arr.length;i++)
There will be no measurable performance change .

I'm not that experienced with ArrayLists, I need some basic functions for it

I have a 2D ArrayList
List<List<String>> transitionTable = new ArrayList<List<String>>()
If I'm correct, adding "rows" to this would be (correct me if I'm wrong)
transitionTable.add(new ArrayList<String>())
How would I go about adding the equivalent of a column? Use a for loop something like this?:
for (int i = 0; i < transitionTable.get(0).size(); i++)
{
transitionTable.get(i).add("something");
}
edit: Now having trouble figuring out why it stops adding after a certain point, it's always at index
i = anything (depending on how many times I've iterated the loop"
j = 1 (always)
I forgot to mention I'm aiming for a nxn 2d arraylist (a square basically)
This is my code so far:
transitionTable.add(new ArrayList<String>()); //Adds a new row
if (transitionTable.size() == 1)
{
transitionTable.get(0).add("NULL"); //Adds a new column.
}
else
{
for (int i = 0; i < transitionTable.get(0).size(); i++)
{
transitionTable.get(i).add("NULL"); //Adds a new column (needs to iterate for each row to create something like a column)
}
}
At the moment, each iteration will add a value in the first column because they are empty;
After adding three arraylists;
transitionTable
- ArrayList[0] - []
- ArrayList[1] - []
- ArrayList[2] - []
After using your loop;
transitionTable
- ArrayList[0] - [something]
- ArrayList[1] - [something]
- ArrayList[2] - [something]
But when you add more items to each list, you then need to edit the position in the arraylist specifically! As David Wallace said, you are close, I hope the above bit of information helps!
A Java List (and ArrayList is just one implementation) is a way to represent a list of things, such as:
Strings: 〖 "This" "That" "Another string" "Wow" 〗
Integers: 〖 15 208 -632 17 999 5 〗
Other objects, anything you can describe with a class, like Animal or Contact.
Just think of them as lists you have on paper. They have order (but they are not necessarily sorted), new items can be added, items can be removed, and you can access them by index or iterate on them in order.
So what exactly does a List of Lists look like? Basically, something like this:
〖 〖 "This", "That" 〗 〖 "Something" 〗 〖 〗 〖 "A" "Bunch" "Of" "Several" 〗〗
This is a list of four items. Each item is a list of strings. Note something important about it, though: the lists inside it are still lists, and they are independent of one another just like the numbers in the list of Integers. For this reason, each of the lists inside can have a different number of items.
This is important to remember if you want to use a list of lists to represent a table. Tables are objects that have the same number of items in each row. And you have the concept of a column. In Excel, you can copy a column together as one, to somewhere else.
Using a List of Lists doesn't give you the concept of equal-length-rows and separable columns. At least, not directly. If you use it to represent a table, you should probably wrap it in a class that makes sure that every time you extend one row, all the others are extended as well, and allows you to do things like return whole columns or delete whole columns.
It would do so by looping over the rows and performing the operations on each sub-list separately.
You can use a List of Lists as a table even without wrapping it as said, if you don't actually need all those operations and you just need a rudimentary implementation of a table as part of something else. You will still have to take care to fill and retrieve "columns" by looping over the rows and accessing the required column on each of them.
I would suggest using a temporary "reference" ArrayList, like this:
List<List<String>> templist = new ArrayList<List<String>>();
for(List<String> list1 : transitionTable) {
list1.add("String whatever");
templist.add(list1);
}
transitionTable = templist;
Edit: Accidentally posted prematurely.

Adding int to an array

First off don't call this a duplicate unless you actually find a thread that works for exactly what I'm trying to do, as I've gone through about 50 threads that aren't helping.
~Problem: I don't know how to correctly add an integer to an array like "private int test[] ={}"
~My code:
private int generatedList[] = {};
private int lastInt = 1;
private void startList() {
if (generatedList.length == 30000) {
System.out.println(generatedList);
} else {
generatedList[lastInt+1] = generatedList[lastInt];
lastInt++;
System.out.println(generatedList);
startList();
}
}
~What I'm trying to accomplish: if the length of the list is less than 30,000 add the last int to the array then lastInt++, so after looping say 5 times the list will print like this: 1,2,3,4,5
How do I add the "lastInt" to the generatedList[]?
Arrays in Java are of a fixed size. The one you declared is of size 0, in fact. You won't be able to append to the end of it. Check out the ArrayList class, it will help you.
private ArrayList<Integer> generatedList;
...
generatedList.add(1234);
However, there is a bigger problem with your code. Your recursive implementation is going to be extremely slow, and it doesn't have an initialization for the first value in the array. It would be much better to use a primitive array of fixed size 30,000, and simply loop from 0..30k and fill in the values by index. I leave that as an exercise for you since this is probably related to some homework assignment :)
Arrays are not extendible. This is by design.
I suggest using an ArrayList. It's like an array (can index any property, works almost as fast in terms of runtime complexity) but has the additional properties that you can add and remove items.
The easy way to do this is to change generatedList into ArrayList<Integer>. If you want to preserve an array, you can always create a new array and copy over the contents. (ArrayLists are easier, though.)
Your trying to add new elements to an array of size zero size. Use an arraylist or specify array size first.

How can I add up values of an array object?

I have an array that created 5 objects. Each object has two strings and a int. Lets call the int "number". How can i add up the "number's" of each object into a final number, assume that the numbers change so i cannot simply just put 5 + 3 etc.. For example
Question question[] = new Question[5];
public Constructor()
{
String1 = "null";
Sting2 = "null";
number = 0;
}
SO i have five objects that look like this, they all have a different value. Number refers to a score, So if the user does something right, the number will be added to a variable, i need to know how to add up the 5 variables when i execute the 5 objects in something like.
for (i=0; i < Question.length; i++)
{
object.dostuff
}
Many things have to happen first:
Initialize the array: seems you got that one covered.
Initialize objects within the array: Make sure every cell of your array actually contains a question instance (or to be more precise: a reference to a Question instance).
Iterate over the array: here your loop seems to go over the class (Question, with capital Q) but you need to iterate over the array (question with a small q). Piece of advice, since the variable question here represents an array of question it would make more sense if you make your name plural (questions) to help illustrate that this is an array. Basic rule is to make the name as explicit as possible, so questionArray would be an even better name. Past a certain point it's a question of taste. Rule of thumb is that if you have to look at the declaration of the variable then it's probably not named correctly.
access methods, properties etc of the objects: when iterating over the array you need to access the right index (questions[i]) then access the members of this object (questions[i].doStuff). If you aim for OOP (which I assume is the point here) then you may want to make the obvious operations as functions of your Question class. Then simply call this function with the proper parameter (questions[i].setNumber(i)). It all depends on what you need it to do.
Hope this helps (if this is a homework related question you should tag it as such, that would maximize your chance to get help here).
Don't use Question.length, use question.length
Add an accessor method and a method to increment the scores.
use map to extract the numbers from the list of tuples then use reduce to accumulatively sum the numbers.
list=[("1 this is sentence 1","1 this is sentence 2",1),("2 this is sentence 1","2
this is sentence 2",2),("3 this is sentence 1","3 this is sentence 2",3)]
numbers=map(lambda x: x[2],list)
result=reduce(lambda x,y: x+y,numbers)
print(result)
output:
6

Categories

Resources