import java.awt.*; import java.util.*; import javax.swing.*; import java.io.*; /
ID: 654508 • Letter: I
Question
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.io.*;
//function
public class Exercise14_27 extends JFrame{
//constructor
public Exercise14_27() throws IOException{
System.out.print("Enter file name for the "+ "graph: ");
//input
Scanner input = new Scanner(System.in);
String filename = input.nextLine();
Scanner file = new Scanner(new File(filename));
int n= Integer.parseInt(file.nextLine());
int[][] position = new int[n][2];
ArrayList[] edge = new ArrayList[n];
//for loop
for(int i=0;i<n;i++){
String[] tokens=file.nextLine().split(" ");
//storing x,y position value into a variable
position[i][0]= Integer.parseInt(tokens[1]);
position[i][1]= Integer.parseInt(tokens[2]);
//Create a new array list
edge[i] = new ArrayList<String>();
//for loop statement
for(int k=3; k<tokens.length;k++){
edge[i].add(Integer.parseInt(tokens[k]) );
}//inner loop
}// end of for-loop
add(new GraphView(position, edge));
}//end of 14_27constructor
//main method
public static void main(String[] args) throws Exception{
Exercise14_27 frame = new Exercise14_27();
//panel size
frame.setSize(400,400);
//panel title
frame.setTitle("Exercise14_21");
//default close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame in the center of the screen
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}// end of main
}// exercise14_21
// class definition
class GraphView extends JPanel{
//declared variable
private int[][] position;
private ArrayList[] edge;
//constructor definition
public GraphView(int[][] position, ArrayList[] edge){
this.position = position;
this.edge = edge;
}// end of GraphView constructor
@Override
protected void paintComponent(Graphics g){
for(int i=0; i<position.length;i++){
//an oval on the panel
g.fillOval(position[i][0]-8, position[i][1]- 8,16,16);
g.drawString(i +"", position[i][0]-12, position[i][1]-12);
}// end of for loop
for(int i=0; i<edge.length;i++){
for(int j=0; j<edge[i].size();j++){
int v= (Integer)edge[i].get(j);
g.drawLine(position[i][0], position[i][1], position[v][0], position[v][1]);
}// end of inner one loope
}//end of outer for loop
}// end of paintComponent
}//end of GraphView
My question is, it is not reading my text file. What's wrong here???
Explanation / Answer
We cannot read a file using Scanner class.Try the following code instead.
String file_name="filename.txt";
try {
ReadFile file= new ReadFile(file_name);
String[] aryLines=file.OpenFile();
}
catch (IOException e)
{
System.out.println(e.getMessage() );
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.