Create a file, call it data.txt that contains 6 integers. They could be on separate lines or just separated by spaces. For instance,
1 2 4 4 4 1
In the main method, use the Java Scanner class to open and read the 6 integers in your data file and put them into an array. You may assume that the file does, in fact, contain 6 integers (it may contain more, the program should not care). You can use Scanner to read the integers in your file by adapting the following code:
import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class ScanFile { public static void main(String[] args) { try { Scanner s = new Scanner(new File("data.txt")); int x = s.nextInt(); } catch (FileNotFoundException fof) { System.out.println("problem " + fof); } } }Here, we open a Scanner, telling it to read from a file by giving it a file object "new File("data.txt")". We then use the nextInt method on the scanner to read the first integer from the file data.txt.
Java often requires you to do things to handle problems. The way Java does this is with try..catch. We discussed try..catch in class (before break). Keep in mind that any place where a problem could occur must be between "try" and "catch". In this case, with the line "Scanner s = ..." an problem could occur if the file "data.txt" did not exist. On the next line, a problem could occur if scanner encountered a non-integer.
public static int[] readFile(String fileName)As a result of moving the reading code into a method, your main method should look like:
public static void main(String[] args) { int[] points = readPoints("data.txt)"; }Having done that, in the main method, add loop to print the contents of the array that your readPoints method just returned. (Do not use Arrays.toString; use a loop.)
1 2 4 4 4 1Once you have that working, move everything about printing the points into a new method called printPoints with the following signature:
public static void printPoints(int[] p)At the end of this step, your main function should look similar to
public static void main(String[] args) { int[] points = readPoints("data.txt)"; printPoints(points); }
distance = sqrt((x1-x2)^2 + (y1-y2)^2)So, in my data above, the distance between the first two points (the length of one side of the triangle) is
sqrt((1-4)^2 + (2-4)^2) or sqrt(3^2 + 2^2) or sqrt(9+4) or sqrt(13) or 3.605551275463989Write a method to calculate this distance. The "signature" of the distance function should be
public static double distance(int p1x, int p1y, int p2x, int p2y)Then use this function to print out the length of each side. At the end of this step, the output for you program should be:
1 2 4 4 4 1 3.605551275463989 3.0 3.1622776601683795
public static double area(int[] points)The calculated area for my triangle is 4.5 (which Java actually shows as 4.500000000000003). Finally, add to your main function a statement to print the area of the triangle.