How can I make a linked list from a file? I have a file and each line is an object with its width height and length so the file is a 2d array. I am trying to make a linked list of objects but with just the variable next in the object class and no node class or linked list class also I can't use any arrays besides the split one. Since there are 7 objects a linked list of 7 nodes should be returned. I have done this so far which is similar to making array to linked list but I don't think it's correct
file:
2 18 9
1.2 6.32 9.2
2.0 2.0 2.0
5.0 1.4 7.0
121.0 107.0 12.0
4.2 4.2 4.2
8.0 1.0 11.0
//main
static Box LinkedList(String file){
file = "ll.txt";
Scanner scan = new Scanner(file);
while (scan.hasNextLine()){
String line = scan.nextLine();
String [] arr = line.split(" ");
Box b = new Box(Double.parseDouble(arr[0]),Double.parseDouble(arr[1]), Double.parseDouble(arr[2]));
Box head = arr[0];
Box temp = head;
for (int i = 0; i < row; i ){
Box s = arr[i];
temp.next = s;
temp = temp.next;
}
}
return head;
}
//class
class Box{
private double width, height, length;
public Box next;
Box(double w, double h, double l){
width=w;
height=h;
length=l;
}
}
CodePudding user response:
I've modified your code to make it output correct results. Does this solve your problem?
public class Main {
public static void main(String[] args) {
Box head;
try {
head = LinkedList("ll.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
return;
}
System.out.println(head);
}
// main
static Box LinkedList(String file) throws FileNotFoundException {
Scanner scan = new Scanner(new FileReader(file));
Box head = null;
Box lastBox = null;
while (scan.hasNextLine()){
String line = scan.nextLine();
String [] arr = line.split(" ");
Box b = new Box(Double.parseDouble(arr[0]), Double.parseDouble(arr[1]), Double.parseDouble(arr[2]));
if(lastBox != null) lastBox.next = b;
if(head == null) head = b;
lastBox = b;
}
return head;
}
}
//class
class Box{
private double width, height, length;
public Box next;
Box(double w, double h, double l){
width=w;
height=h;
length=l;
}
}