java incrementing with for works only once - java

City[] array = new City[6];
String [] arr = {"Paris","London","Rome","Los Angeles","New York","San Francisco"};
int [] arr2 = {200000, 100000, 80000, 60000, 50000, 45000};
String [] arr3 = {"Breitzel", "Statute of Liberty", "Tramways"};
for (int i = 0; i < 6; i++){
if (i<3){
City V = new City (arr[i], "EU", tab2[i]);
array[i] = V;
}
else {
for (int j = 0; j < 3; j++){
Capitale C = new Capitale (arr[i], "USA", arr2[i], arr3[j]);
array[i] = C;
}
}
}
The first incrementing loop works well, the one that creates cities (System.out.printline shows that City[] get 6 elements, which are the 6 cities.
BUT : the 3 American cities should each be assigned an element of arr3. This doesn't work. j doesn't get incremented and all 3 American cities get "Tramways".
I don't see why...

On the contrary, j is being incremented.
But each iteration of the internal loop is overwriting the results of the prior iteration.
The last iteration has j = 2, and arr3[2] is "Tramways".
I think you'll get the result you're looking for with this.
for (int i = 0; i < 6; i++){
if (i<3){
City V = new City (arr[i], "EU", tab2[i]);
array[i] = V;
}
else {
Capitale C = new Capitale (arr[i], "USA", arr2[i], arr3[j - 3]);
array[i] = C;
}
}
That said, the code isn't all that clear. The magic value of 3 isn't clear.
You could address this with a named constant:
final int INDEX_OF_FIRST_CAPITALE = 3;
Or by having arr3 be parallel to the other two arrays
String [] arr3 = { null, null, null, "Breitzel", "Statute of Liberty", "Tramways"};
Or by using a map from capital name to attraction.
Map<String,String> = new HashMap<String,String>();

Related

Adding jagged arrays beginner

I'm a beginner at java at struggling with this:
I am trying to sum two jagged arrays ( n and m, both double [][]) of the same size (each is length 3 at the first level, then of length x-1,x and x-1 respectively at the second level).
The problem I'm having is to specify the length that each array within the jagged array should be, at the moment my code is producing an n x n array because I've specified the length as n[1] rather than as a parameter, but if I try and use sum[i].length=n[i].length I get the error, "cannot assign value to final variable". So I know this part is wrong but I don't know what is right...
Thanks for the help!
My code:
else if (isValidTridiagonal(m)== true && isValidTridiagonal (n) == true)
{
int size = n[1].length; /** specifying all lengths to be x where they shouldnt be*/
sum = new double[3][size];
for (int i = 0; i < n.length; i++)
{
for(int j = 0; j< n[i].length; j++)
{
sum [i][j]= n[i][j] + m [i][j];
}
}
return sum;
}
There is some missing information. As far as I can tell there are two things you need to fix. You seem to have "sum" as a final variable already defined in your code.
Secondly, you are declaring a new array that is 3xsize big. If you want a jagged array in that sence, you must leave one of the brackets empty and in the first loop insert a new array of the wanted size.
double[][] sum = new double[3][]; //Make sure this is unique within the scope
for(int i = 0; i < 3; i++) { //if you want dynamic scaling you'll need to replace 3 in the array as well.
int size = n[i].length; //size of the new row
sum[i] = new double[size]; // Inserting a new array of the wanted size
for(int j = 0; j< sum[i].length; j++)
{
sum[i][j]= n[i][j] + m[i][j];
}
}
return sum;
The problem is probably with this line:
sum = new double[3][size];
Here you create an incorrect, non-jagged array of size [3][2]
When you try to set sum[1][2] (2nd, 3rd index), you will not be able to.
Otherwise, the code looks correct and I got a sum to work using this:
public static void main(String[] args) {
int[][] n = new int[3][];
n[0] = new int[2];
n[0][0] = 1;
n[1] = new int[3];
n[2] = new int[2];
int[][] m = new int[3][];
m[0] = new int[2];
m[1] = new int[3];
m[1][2] = 1;
m[2] = new int[2];
int[][] sum = new int[3][];
sum[0] = new int[2];
sum[1] = new int[3];
sum[2] = new int[2];
for (int i = 0; i < n.length; i++) { // n.length will be 3
for (int j = 0; j < n[i].length; j++) { // n[i].length will be 2, 3 and 2
sum[i][j] = n[i][j] + m[i][j];
}
}
System.out.println("Sum: ");
for (int i = 0; i < sum.length; i++) {
for (int j = 0; j < sum[i].length; j++) {
System.out.print(sum[i][j] + "|");
}
System.out.println();
}
}
This will print off:
Sum:
1|0|
0|0|1|
0|0|

Looping to create a custom String

I am looping to write data to an array of Strings. But what I want is that I create another loop where I will loop through the data of values as much as amount, but I would like to have some guidance on how to do so.
String[] s = new String[20];
String[] values = { "A", "B", "C", "D" };
final int amount = 2;
for (int i = 0; i < s.length; i++) {
s[i] = String.format("%s%04d", values[0], i); //TODO create another loop?
}
System.out.println(Arrays.toString(s));
The preferred output should be:
A0000, A0001, B0002, B0003, C0004, ...
The actual output is:
A0000, A0001, A0002, A0003, A0004, ...
Problem : your looping is wrong.
try this:
public static void main(String[] args) {
int k=0;
String[] s = new String[20];
String[] values = { "A", "B", "C", "D" };
final int amount = 2;
for (int i = 0; i < values.length; i++){
for (int j = 0; j < amount; j++){ //data of values as much as amount
s[k++] = String.format("%s%04d", values[i], k);
}
}
System.out.println(Arrays.toString(Arrays.copyOf(s,k)));
}
output:
[A0001, A0002, B0003, B0004, C0005, C0006, D0007, D0008]
You need to have 2 loops one to loop through the actual values array then another one is the amount (number of times).
Try this
List<String> a = new ArrayList<String>();
String[] values = { "A", "B", "C", "D" };
final int amount = 2;
int incrementVariable = 0;
for (int i = 0; i < values.length; i++){
for(int j = 0; j< amount; j++){
a.add(String.format("%s%04d", values[i], incrementVariable));
incrementVariable +=1;
}
}
System.out.println(a);
}
Output:
[A0000, A0001, B0002, B0003, C0004, C0005, D0006, D0007]
I like while loops better :)
String[] s = new String[10];
String[] values = {"A", "B", "C", "D"};
final int amount = 2;
for (int i = 0; i < values.length; ++i) {
int buffer = 0;
while(buffer <= amount) {
int index = i * amount + buffer;
s[index] = values[i] + String.format("%04d", index);
buffer++;
}
}
System.out.println(Arrays.toString(s));
[A0000, A0001, B0002, B0003, C0004, C0005, D0006, D0007, D0008, null]

Converting arrays into a multi-dimensional array - Java

is there a way to convert three single dimensional arrays into a multi-dimensional one.
For example I have three arrays (text, retweets, geo) how can I merge them so it appears as:-
The arrays I want to merge are something along the lines of text = 'hello, 'hello'. retweets = '2,5' and geo = '19912, 929293'.
And should result in:-
combined =
[hello, 2, 19912
hello, 5, 929293]
and so one... All of the arrays are the same sizes. I know I should loop through while a for loop somehow but am not quite sure how to implement it.
Thanks to any response.
int count = ...;
String [] text = new String [count];
int [] retweets = new int [count];
int [] geo = new int [count];
// Fill arrays with data here
Object [] combined = new Object [count * 3];
for (int i = 0, j = 0; i < count; i++)
{
combined [j++] = text [i];
combined [j++] = retweets [i];
combined [j++] = geo [i];
}
public static void main(String[] args) {
String[] array1 = { "hello1", "A2", "X19912" };
String[] array2 = { "hello2", "B2", "Y19912" };
String[] array3 = { "hello3", "C2", "Z19912" };
String[] copyArrays = new String[array1.length + array2.length
+ array3.length];
System.arraycopy(array1, 0, copyArrays, 0, array1.length);
System.arraycopy(array2, 0, copyArrays, array1.length, array2.length);
System.arraycopy(array3, 0, copyArrays, array1.length + array2.length,
array3.length);
String[][] array = new String[3][3];
int index = 0;
for (int i = 0; i < array.length; i++)
for (int j = 0; j < array[i].length; j++) {
array[i][j] = copyArrays[index++];
}
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
}
Output:
hello1 A2 X19912
hello2 B2 Y19912
hello3 C2 Z19912
This code will first copy the given arrays into a new array. Then it will insert all elements of copyArrays into a 2d array using for loop .
String[] text =...;
int[] retweets =...;
int[] geo =...;
int len = text.length;
List<List<Object>> items = new ArrayList<>();
for (int i = 0; i < len; i++) {
List<Object> item = new ArrayList<>();
item.add(text[i]);
item.add(retweets[i]);
item.add(geo[i]);
items.add(item);
}
a clever way of "toTableFormTheArrays" is:
public static String[][] to2DArray(String[]... yourArrays){
return yourArrays;
}
then the code is:
String[] text = {"hello", "hello"};
String[] retweets = {2, 5};
String[] geo = {19912, 929293};
String[][] yourTableForm2DArray = to2DArray(text, retweets, geo);
note: can change types, multi calls of to2darray for other D, maybe.
String[] text = {"hello", "hello"};
int[] retweets = {2, 5};
int[] geo = {19912, 929293};
//create table of strings for each array
Object[][] combined = new Object[text.length][3];
//load information into table, converting all information into Strings
for(int row = 0; row<text.length; row++){
combined[row][0] = text[row];
combined[row][1] = retweets[row];
combined[row][2] = geo[row];
}
This creates a multidimensional array that should look like this:
[[hello, 2, 19912], [hello, 5, 929293 ]]

java : get computed values outside loop

I do some calculation inside for loop and when I println values inside the loop, I got the expected values,
now, I need also that these values will be available outside loop and not only get the latest value.
example :
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
int value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value ); //it print me only third value
I would like that the value 1,2,3 will be also available outside loop
If you want to have access to all three variables. you have to declare a data structure that holds all the values.
e.g.
String[][] matrix = { { "1", "2", "3" } };
List<Integer> list = new ArrayList();
String[] y= { "TEST" ,"BUG"};
int a = 0;
int value;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
list.add(value);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value );
Declare the variable value outside of your loop:
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
int value = 0;
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
value = Integer.parseInt(matrix[i][j - 1]);
System.out.println(value ); //this is OK it print me 3 values
}
}
System.out.println(value );
But if you need all three values available you should use array or some other containers like ArrayList:
String[][] matrix = { { "1", "2", "3" } };
String[] y= { "TEST" ,"BUG"};
int a = 0;
Arraylist<Integer> values = new Arraylist<Integer>();
for (int i = 0; i < y; i++)
{
for (int j = 1; j < 4; j++)
{
values.add(Integer.parseInt(matrix[i][j - 1]));
System.out.println(values); //this is OK it print me 3 values
}
}
System.out.println(values);
you have to declare your variable (that you want to use outside of the for-loop) on top of your code.
Example:
for (...) {
//only valid in this for loop
int i = 1;
}
//valid also after this for loop
int i = 1;
for (...) {
}

Arrays (toString) not output correctly

Actually this tread is continuing from the other one. There wasn't enough characters to continue there. Anyway. the problem is that the output is "1(10) 2(23) 3(29)". Even though I could return string for the array values (10,23,29) and used string reference as 1, 2 and 3. My question is it possible to return index values 1,2,3 and as well as array values. Am I making an sense. Here is what I have done...
// int[] groups = {10, 23, 29}; in the constructor
String tempA = "";
String tempB = " ";
int[] temp = new int[4];
int length = groups.length;
for (int j = 0; j < length; j++)
{
temp[j] = groups[j];
tempB = tempB + "("+goups+")";
}
groups = temp;
Arrays.sort(coingroups);
for(int i = 1; i < groups.length;i++)
{
tempA = tempA+" "+(i)+ "("+groups[i]+")";
}
return tempA;
With the below code you are creating a string that and this string represents the whole array. Yet it will be harder to work with then just using the array 'groups'
// int[] groups = {10, 23, 29}; in the constructor
String tempA = "";
for (int j = 0; j < groups.length; j++)
{
tempA = tempA + " " + j + " (" + groups[j] + ") ";
}
return tempA;
If you create a Map, and save your data in there, you can get any information you want. Like:
Map<Integer, String> stack = new HashMap<Integer, String>();
stack.put(1, "10");
stack.put(2, "23");
stack.put(3, "29");
After storing everything, you can get the values of the Map by its key or value. Example:
stack.get(1) will return "10"
stack.get("10") will return 1

Categories

Resources