Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Hi! I have write from the file problem. Java question I have a file call 1.txt c

ID: 3801885 • 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

// code ArrayRead.java

import java.io.File;
import java.util.Scanner;

public class ArrayRead {
public static void main(String[] args) {
try {
File f = new File("1.txt");
Scanner s = new Scanner(f);
String[] array;
// Read file line by line
while (s.hasNextLine())
{
String line = s.nextLine();
  
// Place a unique identifier for splitting arrays
line = line.replaceAll("\},\{", " ");
array = line.split(" ");
  
// Now for each array given in a line split on "," and print first element
for (String l : array)
{
l = l.replaceAll("\{", "");
l = l.replaceAll("\}", "");
System.out.print(l.split(",")[0] + ",");
}
}
System.out.println();
// Close the input stream
s.close();
}
catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}

// 1.txt

{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}

// Sample run

$ java ArrayRead
0,11,1,2,4,5,8,4,5,8,6,

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote