for-each loops ; String cannot be converted to int? - java

I need to acess 2D array and write some information there. I want to use for-each loop for this.
Here is my code. But when executing it says ;
q13.java:24: error: incompatible types: String[] cannot be converted to int
wi.write(St[a][b] + "\t");
^
q13.java:24: error: incompatible types: String[] cannot be converted to int
wi.write(St[a][b] + "\t");
What's wrong in my code?
import java.io.*;
class q13{
public static void main(String[] args)
{
String St[][]={ {"STUDENT NO", "STII", "SPD", "PS", "DCCNII", "SEI"},
{"DIT/10/C1/0001", "A", "A-", "B+", "A", "A"},
{"DIT/10/M2/0123", "C-" ,"C" ,"B" ,"B", "B+"},
{"DIT/10/M1/0054", "D" ,"C-" ,"C" ,"B-", "B"},
{"DIT/10/M1/0025", "A" ,"A" ,"A-", "A", "A"},
{"DIT/10/C2/1254", "C" ,"C-" ,"B" ,"B+", "B"} };
try{
BufferedWriter wi = new BufferedWriter(new FileWriter(".\\st_info.txt"));
for(String[] a:St)
{
for(String[] b:St)
{
wi.write(St[a][b] + "\t");
}
wi.write("\r\n");
wi.newLine();
}
wi.close();
}
catch(IOException ex)
{
System.out.print(ex);
}
}
}

It doesn't make sense to use a and b as indexes into an array - they are themselves String[] variables - check the declaration.
If you're trying to iterate over every element in the array, I suspect you want:
for(String[] a : St)
{
for(String b : a)
{
wi.write(b + "\t");
}
wi.write("\r\n");
wi.newLine();
}
(I'd also strongly advise you to follow normal Java naming conversions, and use more meaningful names than "st".)

You are accessing each string, when you call for(String[] a:St). This is the reason you are getting the error you have show. A quick method to solve this is to iterate each element manually in the loop and call the loop index like so:
import java.io.*;
class q13{
public static void main(String[] args)
{
String St[][]={ {"STUDENT NO", "STII", "SPD", "PS", "DCCNII", "SEI"},
{"DIT/10/C1/0001", "A", "A-", "B+", "A", "A"},
{"DIT/10/M2/0123", "C-" ,"C" ,"B" ,"B", "B+"},
{"DIT/10/M1/0054", "D" ,"C-" ,"C" ,"B-", "B"},
{"DIT/10/M1/0025", "A" ,"A" ,"A-", "A", "A"},
{"DIT/10/C2/1254", "C" ,"C-" ,"B" ,"B+", "B"} };
try{
BufferedWriter wi = new BufferedWriter(new FileWriter(".\\st_info.txt"));
int i = 0;
for(String[] a:St)
{
int j = 0;
for(String[] b:St)
{
wi.write(St[i][j] + "\t");
j++;
}
i++;
wi.write("\r\n");
wi.newLine();
}
wi.close();
}
catch(IOException ex)
{
System.out.print(ex);
}
}
}

Note that St (that should be name st to follow Java Naming Conventions) is an array of arrays of Strings.
Let's take a closer look to at your loop:
for(String[] a : St) { // a is an array
for(String[] b : St) { //b is an array (unrelated to a)
wi.write(St[a][b] + "\t"); //error, a and b are arrays
Your first loop should loop on the array of arrays, the inner loop will now loop on the array, which includes Strings:
for(String[] a : St) { // a is an array
for(String b : a) { //b is a String
wi.write(b + "\t");

It seems the answers here have already mentioned the error in your code. However, it only grazes on the cause of your casting error.
In short, you are attempting to call on an index of an array using a String[] and a String as the indices. For example, your code is equivalent to the following...
String[] array = {"My", "first", "array"};
String stringFromArray = array["first"];
You are attempting to call on the index of the array using a String (and String[] in your first for-each loop).
In order to obtain the item in an array you must call it using it's index position (starting with position 0 in java).
The following would be proper use of calling on the specific index...
// index [0] [1] [2]
String[] array = {"My", "first", "array"};
String positionZero = array[0];
String positionOne = array[1];
String positionTwo = array[2];
Your output would be , "My", "first", and "array" respectively.

Related

Joining two lists together separated by a comma in Java

I have two String lists (a and b) that I wanna join with a comma after each element. I want the elements of list a to be first. I'm also stuck on Java 7
I tried the following but it doesn't work:
StringUtils.join(a, ", ").join(b, ", ");
This works :
ArrayList<String> aAndB = new ArrayList<>();
aAndB.addAll(a);
aAndB.addAll(b);
StringUtils.join(aAndB, ", ");
Is there a shorter way of doing this?
You do not need StringUtils By default List toString() displays elements in comma separated format.
System.out.println (new StringBuilder (aAndB.toString())
.deleteCharAt (aAndB.toString().length ()-1)
.deleteCharAt (0).toString ());
The only thing you need to do is delete square brackets
You can use the guava library like so:
String [] a = {"a", "b", "c"};
String [] b = {"d", "e"};
//using Guava library
String [] joined = ObjectArrays.concat(a, b, String.class);
System.out.println("Joined array : " + Arrays.toString(joined));
// Output: "Joined array : [a, b, c, d, e]"
To get short code you could :
String res = String.join(",", a) + "," + String.join(",", b);
Since you are using Java 7, you could write a static method to perform the task.
List<String> a = Arrays.asList("a", "b", "c");
List<String> b = Arrays.asList("d", "e", "f");
String s = join(",", a, b);
System.out.println(s);
List<Integer> aa = Arrays.asList(101, 102, 103);
List<Integer> bb = Arrays.asList(104, 105, 106);
String ss = join(":", aa, bb);
System.out.println(ss);
}
public static <T> String join(String delimiter, List<T>... lists) {
StringBuilder sb = new StringBuilder();
for (List<T> list : lists) {
for (T item : list) {
sb.append(delimiter);
sb.append(item);
}
}
return sb.substring(delimiter.length()).toString();
}
}
This prints.
a,b,c,d,e,f
101:102:103:104:105:106

Mapping Two String Arrays in Java

I'm trying to find out if there is an easier way to map two string arrays in Java. I know in Python, it's pretty easy in two lines code. However, i'm not sure if Java provides an easier option than looping through both string arrays.
String [] words = {"cat","dog", "rat", "pet", "bat"};
String [] numbers = {"1","2", "3", "4", "5"};
My goal is the string "1" from numbers to be associated with the string "cat" from words, the string "2" associated with the string "dog" and so on.
Each string array will have the same number of elements.
If i have a random given string "rat" for example, i would like to return the number 3, which is the mapping integer from the corresponding string array.
Something like a dictionary or a list. Any thoughts would be appreciated.
What you need is a Map in java.
Sample Usage of Map :
Map<String,String> data = new HashMap<String,String>();
` for(int i=0;i<words.length;i++) {
data.put(words[i],numbers[i]);
}
For more details please refer to https://docs.oracle.com/javase/tutorial/collections/interfaces/map.html
Oracle Docs for HashMap
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
String[] words = {"cat","dog", "rat", "pet", "bat"};
String[] numbers = {"1","2", "3", "4", "5"};
Map<String,String> keyval = new HashMap<String,String>();
for(int i = 0 ; i < words.length ; i++ ){
keyval.put(words[i], numbers[i]);
}
String searchKey = "rat";
if(keyval.containsKey(searchKey)){
System.out.println(keyval.get(searchKey));
}
}
}

Assignment of an array

I saw this snippet when I was preparing for one of the certification exam on java. Can anybody please explain me how does this work?
public static void main(String args[]) {
String str[] = new String[][] {
{ null },
new String[] { "a", "b", "c" },
{ new String() }
}[0];
System.out.println(str[0]);
}
The o/p is null as expected but I am confused with the assignment of String array 's'.
Is it a single dimension array or two-dimensional?
What does [0] on the righthand side of the assignment mean?
How does new String[] { "a", "b", "c" } work?
Thanks in advance
GPAR
I've split the statement into multiple lines, improving the readability
// First, the array is created, then it is stored into a variable.
// At last, store the result of code below into a String[].
String str[] =
// Create a two-dimensional array
new String[][] {
// Add the first element to the two-dimensional array,
// which is in fact a String[] with one null element in it.
/* element #0 */ new String[] { null },
// Add the second element to the two-dimensional array:
// it's a String[] containing three strings
/* element #1 */ new String[] { "a", "b", "c" },
// Then add the third element to the two-dimensional array,
// which is an empty string.
/* element #2 */ new String[] { new String() }
}
// Then get the first element of our two-dimensional array,
// which returns a String[] with one null element in it.
[0];
So in fact, variable str now contains a String[] with index 0 being null.
At last, str[0] is printed on the screen, which was null.
To answer your questions:
Variable str is a one-dimensional array. The notation String str[] is very ugly and confusing; it should be String[] str. And then you can see more easily that our variable is one-dimensional.
[0] means get the first element of the array (arrays always start with index 0). A certain element of a two-dimensional array is always a one-dimensional array; with other words, a two-dimensional array is an array containing arrays.
So that's why String[] str = new String[][] { ... }[0] is perfectly valid.
new String[] { "a", "b", "c" } creates a string array containing three strings: "a", "b" and "c".
So new String[] { "a", "b", "c" }[2] would return "c".
EDIT
Let me explain it step by step.
Step 1 — This is how we declare a String[] (a String array):
String[] myArray = new String[numberOfElements];
Step 2 — We can also immediately initialize the array with values:
String[] myArray = new String[] {
"some value",
"another value",
"et cetera"
};
Step 2b — We do not need to mention the number of elements, because the compiler already sees that we initialize the array with three elements
String[] myArray = new String[3] {
// ^
"some value", // That number
"another value", // is unnecessary.
"et cetera"
};
Step 3 — Because we declare the array and immediately initialize it, we can omit the new statement:
String[] myArray = {
"some value",
"another value",
"et cetera"
};
Step 4 — Next, we have a two-dimensional array, which is nothing more than an array of arrays.
We can first initialize the one-dimensional arrays and then dump them together in a two-dimensional array, like this:
String[] firstThree = { "a", "b", "c" };
String[] lastThree = { "x", "y", "z" };
String[][] myArray = new String[] {
firstThree,
lastThree
};
Step 5 — But we can also do that at once:
String[][] myArray = new String[] {
new String[] { "a", "b", "c" },
new String[] { "x", "y", "z" }
};
Step 6 — Now we said that we can omit the new statements (see step 3), because the array is initialized immediately after initialization:
String[][] myArray = {
{ "a", "b", "c" },
{ "x", "y", "z" }
};
Step 7 — Right?
Step 8 — Now we have your code:
String str[] = new String[][] {
{ null },
new String[] { "a", "b", "c" },
{ new String() }
}[0];
System.out.println(str[0]);
And let us rewrite your code; effectively it's the same as your piece of code.
// Let us define a new two-dimensional string array, with space for three elements:
String[][] our2dArray = new String[3][];
// Then, let us fill the array with values.
// We will add a String array with exactly one element (that element is `null` by chance)
our2dArray[0] = new String[] { null };
// We define the contents for index 1 of our2dArray
our2dArray[1] = new String[] { "a", "b", "c" };
// At last, the last element:
our2dArray[2] = new String[] { new String() };
// Which is effectively the same as
// new String[] { "" };
We have initialized the array so far.
Step 9 — But then, do you see this snippet?:
}[0];
Step 10 — That means we just grab the first element of our newly created array and store that element to our famous variable named str!
String[] str = our2dArray[0]; // Variable str now contains a
// String array (String[]) with exactly one null-element in it.
// With other words:
// str = String[] {
// 0 => null
// }
Step 11 — Then if we print index 0 of our str array, we get null.
System.out.println(str[0]); // Prints null
Step 12 — You see?
1> str is a one-dimensional array
2> the [0] returns the first element of the array (which in this case is another array)
3> new String[]{"a","b","c"} creates and initialises the string array, so that it contains the 3 specified strings - answers to this question might help you with the various syntax rules for this
This is very ugly code.
this String str[]=new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0]; create and initialize a jagged 2d array of String with some initialization and [0] is there to select the 0th String[] to be assigned to the new str variable (the value will be {null}).
the second line prints some value s[0] which is declared somewhere else.

Expanding an array to pass into varargs

Given this function signature:
public static void test(final String... args) {}
I would like to fit a string and an array of strings into the args:
test("a", new String[]{"b", "c"});
But it is not possible because the second argument is not expanded.
So is it possible to expand an array to fit into varargs?
If that is not possible, what is the shortest way to construct a concatenated string array given one string and a string array? E.g:
String a = "a";
String[] b = new String[]{"b", "c"};
String[] c = // To get: "a", "b", "c"
Thank you.
You can use Guava's ObjectArrays.concat(T, T[]) method:
String a = "a";
String[] b = new String[]{"b", "c"};
String[] c = ObjectArrays.concat(a, b);
Notice the order of arguments. Invoking with (b, a) will also work, but that will append the element to the array rather than prepend (which is what you seem to want). This internally uses System.arraycopy() method.
I don't know any other shorter ways but this is pretty clean to me. With plain java (without ant libraries)
String a = "a";
String[] b = new String[] { "b", "c" };
String[] c = new String[b.length + 1];
c[0]=a;
System.arraycopy(b, 0, c, 1, b.length);
That will work no matter what is the size of b
You could just create a separate array, and put the String "a" first into that array, and then copy the array b[] into the array using System.arraycopy(), and then pass the new array to the method.
You can use StringBuilder:
StringBuilder sb = new StringBuilder();
sb.append(a);
for(String s : b) {
sb.append(s);
}
And then you can convert it back to ArrayList or array of Strings...
Shortest way which comes to my mind (BUT not clean code):
test((a + "," + Arrays.toString(b)).replaceAll("[\\[\\] ]", "").split(","));
Test:
public static void main(String[] args) {
String a = "a";
String[] b = new String[] {"b", "c"};
System.out.println(Arrays.toString(
(a + "," + Arrays.toString(b)).replaceAll("[\\[\\] ]", "").split(",")));
}
Output:
[a, b, c]

Using string in java array

I need to put several strings into a java array for example.
"Dog","Cat","Lion","Giraffe"
"Car","Truck","Boat","RV"
each of the above would be 1 key in the array
array[0] = "Dog","Cat","Lion","Giraffe"
array[1] = "Car","Truck","Boat","RV"
Not sure how to do this,or should I be using something other than an array,and how to get each individual element i.e array[0]"Lion"
Thanks
Declare the array like this:
String [][]array = {
{ "Dog","Cat","Lion","Giraffe"},
{"Car","Truck","Boat","RV"}
};
and use the items like this:
array[0][0]; // this would be "Dog"
array[1][0]; // this would be "Car"
You can use a multidimensional array:
String[][] something =
{
{ "hello", "kitties" },
{ "i", "am", "a", "pony" }
};
Well you can do it by declaring a map like so Map<String, MySweetObject> or create a List<String> and put each list into the array.
You need a jagged array, which is an array of arrays:
String [][]array = { {"Dog","Cat","Lion","Giraffe"}, {"Car","Truck","Boat","RV"}};
You can then access the content as this:
array[0] // will be the String array {"Dog","Cat","Lion","Giraffe"}
array[1] // will be the String array {"Car","Truck","Boat","RV"}
array[0][2] // Lion
array[1][0] // Car

Categories