Hi! I have write from the file problem. Java question I have a file call 1.txt c
ID: 3801896 • Letter: H
Question
Hi! I have write from the file problem. Java question
I have a file call 1.txt contain some sets of array:
{0,11,10},{11,12,13}
{1,2,3},{2,1,4}
{4,5,6},{5,6,8},{8,9,2}
{4,5,6},{5,6,8},{8,9,2},{6,3,1}
I want to write a code, when i print(array[0]). it should return 0,11,1,2,4,5,8,4,5,8,6. It just first element in the array.
Here is my code:
public static void main(String[] args) {
String folder = "data";
try{
File f = new File("1.txt");
Scanner s = new Scanner(f);
String[] array;
String line = s.nextLine();
array = line.split(",");
System.out.print(array[0]);
//Close the input stream
s.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Can you help finish my code? And explain!
Explanation / Answer
package QnA;
import java.io.File;
import java.util.Scanner;
public class PrintArrayByIndex {
public static void main(String[] args) {
try {
String folder = "folder_location";
File f = new File(folder+"1.txt");
Scanner s = new Scanner(f);
String[] array = new String[5];
//making result string empty (initially array is null
for(int i=0;i<array.length;i++)
array[i] = "";
while (s.hasNext()) {
//scanning each line
String line = s.nextLine();
//spliting by closing bracket
String arraysInLine[] = line.split("}");
for (String index : arraysInLine) {
//for each array removing brackets
index = index.replaceAll("[{}]", "");
//for counting index of particular array
int countIndex =0;
//for each array splitting each element by ,
String[] data = index.split(",");
for (int i = 0; i < data.length; i++) {
if(data[i] == null ||data[i].isEmpty())
continue;
//adding each element in array at index countIndex to resultant array as string
array[countIndex] += data[i] + ",";
countIndex++;
}
}
}
System.out.print(array[0]);
// Close the input stream
s.close();
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Got through the comments to understanding of code
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.