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".)
See more on this question at Stackoverflow