I have a homework problem that I have been working on for quit a while now. I am creating objects which are shapes then putting them in an arrayList then putting a collection of those shapes in another array list. Then drawing the shape as a picture all at one time. I need to name them so I can use the name of the collection Picture to draw the text file. I got the program working (it draws the shapes correctly) but when set the name of the picture then get it, it returns null. I believe that it is because my method I am not properly passing the name. Of Course help would be Greatly appreciated.
//read in text from file
start picture A // I want to name the picture A
circle 100 100 20
rectangle 100 100 20 30
draw A // I want to draw picture A
import java.awt.Graphics;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
public class Driver {
private static String fileName;
private static String line;
private static Graphics g;
private static char[] name1;
public static void main(String[] args) {
ArrayList<Picture> collection = new ArrayList<Picture>();
try {
readLines(collection);
} catch (Exception e) {
e.printStackTrace();
}
}
static void readLines(ArrayList<Picture> collection) throws Exception {
Picture<Shape> pictures = new Picture<Shape>();
Scanner input = new Scanner(System.in);
System.out.print("Please enter the file name ---> ");
fileName = input.next();
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
// loop through lines
while ((line = inFile.readLine()) != null) {
System.out.println(line);
txtAnalysis(line, collection,pictures);
}
// close file
inFile.close();
}
public static void txtAnalysis(String name, ArrayList<Picture> collection, Picture<Shape> pictures ) {
if (line.startsWith("start picture")) {
String picName = line.split(" ")[2];
pictures = new Picture<Shape>();
//set the name here
pictures.setName(picName);
//here it works
System.out.print(pictures.getName());
}
else if (line.startsWith("circle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object circle
Circle c1 = new Circle("circ", x, y, z);
//add object
System.out.println("calling add " + c1);
pictures.addShape(c1);
}
else if (line.startsWith("rectangle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object rectangle
Rectangle r1 = new Rectangle("rect", x, y, z); // small and upper
//add object
pictures.addShape(r1);
}
else if (line.startsWith("draw")) {
collection.add(pictures);
//problem here
pictures.draw(pictures.getName());
//returns null!!!!!
System.out.print(pictures.getName());
line = null;
}
else {
System.out.println("end of loop");
}
}
}
Picture class
import java.awt.Graphics;
import java.util.*;
public class Picture <E extends Shape> {
private ArrayList<Shape> shapes;
private String name;
public Picture() {
shapes = new ArrayList<Shape>();
}
public String getName() {
//System.out.println("getting the name");
return name;
}
public String setName(String name) {
// System.out.println("setting the name " + name);
this.name = name;
return name;
}
public boolean addShape(E newA) {
// System.out.println("add shape" + newA);
boolean b = shapes.add(newA);
return b;
}
public void draw(String name) {
DrawingPanel panel = new DrawingPanel(600, 600);
Graphics g = panel.getGraphics();
for (Shape shape : shapes) {
System.out.print("this is cool");
shape.draw(g, 0, 0);
}
}
public String toString(String name) {
String s = "Picture " + name + " hosts these shapes:\n";
for (int i = 0; i < shapes.size(); i++) {
s += " " + shapes.get(i).toString() + "\n";
}
return s;
}
}
The problem is that pictures = new Picture<Shape>(); doesn't affect the global value of pictures; it only affects the local value of pictures in txtAnalysis(). A simple code shift should get you the result you're looking for, by setting the value of pictures in a place where it will actually stick:
static void readLines(ArrayList<Picture> collection) throws Exception {
Picture<Shape> pictures = null; //Just do null here
Scanner input = new Scanner(System.in);
System.out.print("Please enter the file name ---> ");
fileName = input.next();
FileReader fr = new FileReader(fileName);
BufferedReader inFile = new BufferedReader(fr);
// loop through lines
while ((line = inFile.readLine()) != null) {
System.out.println(line);
if (line.startsWith("start picture")) {
String picName = line.split(" ")[2];
pictures = new Picture<Shape>();
//set the name here
pictures.setName(picName);
//here it works
System.out.print(pictures.getName());
}
else {
txtAnalysis(line, collection,pictures);
}
}
// close file
inFile.close();
}
public static void txtAnalysis(String name, ArrayList<Picture> collection, Picture<Shape> pictures ) {
if (line.startsWith("circle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object circle
Circle c1 = new Circle("circ", x, y, z);
//add object
System.out.println("calling add " + c1);
pictures.addShape(c1);
}
else if (line.startsWith("rectangle")) {
String[] parts = line.split(" ");
int x = Integer.parseInt(parts[1]);
int y = Integer.parseInt(parts[2]);
int z = Integer.parseInt(parts[3]);
//new object rectangle
Rectangle r1 = new Rectangle("rect", x, y, z); // small and upper
//add object
pictures.addShape(r1);
}
else if (line.startsWith("draw")) {
collection.add(pictures);
//problem here
pictures.draw(pictures.getName());
//returns null!!!!!
System.out.print(pictures.getName());
line = null;
}
else {
System.out.println("end of loop");
}
}
Related
I have a method to read a text file of five stocks using Scanner and delimiter. I also have a method which should take a double multiplier and an array of stock objects and change the price with that multiplier. The method which reads the stock file functions correctly, however, when I attempt to change the stock objects that have been assigned values with the filereading method, it does not change the price. After I use method updateStocks(), I test stock[1] to see if the value has changed and it has not.
After I run this:
public class Main {
public static void main (String args[]) {
// stock object with which to call methods
Stock theStock = new Stock("", "", 0);
// this array holds the stocks to be read
Stock[] stocks = new Stock[100];
// here is the multiplier I am attempting to use
double multiplier = 1/3;
// first I read in the stocks file
theStock.readStocksWithScanner(stocks);
// then I call the updateStockPrices method
theStock.updateStockPrices(multiplier,stocks);
// lastly, I test to see if the method has functioned correctly
System.out.println(stocks[1]);
}
}
This is my output:
Apple AAPLE 152.70
Alphabet GOOGLE 873.96
IBM IBM 194.37
Microsoft MSFT 65.67
Oracle ORCLE 62.82
Company name: Apple Stock symbol: AAPLE Stock Price: 152.7
Press any key to continue . . .
Here is the method updateStockPrices:
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
and here is stocks.java:
import java.util.Scanner ;
import java.util.InputMismatchException ;
import java.io.FileInputStream ;
import java.io.IOException ;
import java.io.FileNotFoundException ;
import java.io.PrintWriter ;
public class Stock {
private static final double MULTIPLIER = (1/3);
public static final String FILE_NAME = "stocks1.txt";
public String newFile = "stocks2.txt";
public static final String FORMAT = "%-10s%6s\t%.2f%n";
private PrintWriter writer = null;
private String name = "";
private String symbol = "";
private double price = 0;
protected Stock stocks[] = new Stock[100];
FileInputStream inputStream = null;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
public Stock(String aName, String aSymbol, double aPrice)
{
this.name = aName;
this.symbol = aSymbol;
this.price = aPrice;
}
// the fileReading method reads the stocks in
public void readStocksWithScanner(Stock[] stocks)
{
this.stocks = stocks;
String workingDirectory = System.getProperty("user.dir");
String absolutePath = workingDirectory + "\\" + FILE_NAME;
FileInputStream inputStream = null;
try{
inputStream = new FileInputStream(absolutePath);
}
catch (FileNotFoundException e)
{
System.out.println("File not found: " + FILE_NAME);
System.out.println("Exiting program.");
System.exit(0) ;
}
Scanner inputFile = new Scanner(inputStream);
int lineNumber = 1;
try{
while(inputFile.hasNextLine())
{
inputFile.useDelimiter(",");
String name = inputFile.next();
inputFile.useDelimiter(",");
String symbol = inputFile.next();
inputFile.useDelimiter("[,\\s]") ;
Double thePrice = inputFile.nextDouble();
inputFile.nextLine();
// here the stocks are given the values found in the text file and initialized above
stocks[lineNumber] = new Stock(name, symbol, thePrice);
// I print them out using a format constant, in order to ensure the method has functioned correcly
System.out.printf(FORMAT, name, symbol, thePrice);
// then I increment the lineNumber
lineNumber++;
}
// I close the stream and should be left with a partially filled array of stock items
inputStream.close();
}catch (IOException e) {
System.out.println("Error reading line " + lineNumber + " from file " + FILE_NAME) ;
System.exit(0) ;
}
catch(InputMismatchException e) {
System.out.println("Couldn't convert price to a number on line " + lineNumber) ;
System.exit(0) ;}
}
public void setName(String name)
{
this.name = name;
}
public void setSymbol(String symbol)
{
this.symbol = symbol;
}
public void setPrice(double aPrice)
{
this.price = aPrice;
}
public String getName()
{
return name;
}
public String getSymbol()
{
return symbol;
}
public double getPrice()
{
return price;
}
public boolean equals(Object other)
{
if(other.getClass() != getClass() || other == null )
{
return false;
}
Stock stock = (Stock) other;
{
if(stock.getName() == getName() && stock.getSymbol() == getSymbol() && stock.getPrice() == getPrice())
{
return true;
}
return false;
}
}
public String toString()
{
return "Company name: " + getName() + " Stock symbol: " + getSymbol() + " Stock Price: " + getPrice();
}
// this is the method which does not seem to function as intended
public void updateStockPrices(double multiplier, Stock[] objects)
{
// I loop to the length of the array in the parameter
for(int i = 1; i < objects.length; i++)
{
// try to manipulate the stock
try{
double subtractThis = stocks[i].getPrice() * multiplier;
objects[i].setPrice(stocks[i].getPrice() - subtractThis);
}// and catch any null objects
catch(NullPointerException e){
// if null I then increment the counter
i++;}
// Is code missing in order for this to function as intended? or have I made a mistake?
}
}
public void createStocks(int stockAmount)
{
Stock[] stocks = new Stock[stockAmount];
}
public void writeStocks(String fileName, Stock[] objects)
{
try{
writer = new PrintWriter(fileName);
}
catch(FileNotFoundException e){
System.out.println("Couldn't create file " + fileName);
System.exit(0);
}
for(Stock s: objects)
{
writer.printf(FORMAT, getName(), getSymbol(), getPrice());
if(objects == null)
writer.close() ;
}
}
public Stock[] getStocks()
{
return stocks;
}
}
simple test
double multiplier = 1/3;
System.out.println(multiplier);
compared to
double multiplier = 1/3f;
System.out.println(multiplier);
import java.io.*;
public class Point {
private double x;
private double y;
public Point(double x_coord, double y_coord) {
x = x_coord;
y = y_coord;
}
}
public class PointArray {
private Point points[];
public PointArray(FileInputStream fileIn) throws IOException {
try {
BufferedReader inputStream = new BufferedReader(new InputStreamReader(fileIn));
int numberOfPoints = Integer.parseInt(inputStream.readLine())...points = new Point[numberOfPoints];
int i = 0;
String line;
while ((line = inputStream.readLine()) != null) {
System.out.print(line);
double x = Double.parseDouble(line.split(" ")[0]);
double y = Double.parseDouble(line.split(" ")[1]);
points[i] = new Point(x, y);
i++;
}
inputStream.close();
} catch (IOException e) {
System.out.println("Error");
System.exit(0);
}
}
}
public String toString() {
String format = "{";
for (int i = 0; i < points.length; i++) {
if (i < points.length - 1) format = format + points[i] + ", ";
else format = format + points[i];
}
format = format + "}";
return format;
}
public static void main(String[] args) {
FileInputStream five = new FileInputStream(new File("fivePoints.txt"));
PointArray fivePoints = new PointArray(five);
System.out.println(fivePoints.toString());
}
The txt file fivePoints is as shown below:
5
2 7
3 5
11 17
23 19
150 1
The first number in the first line means the number of points in the text file.
There is an error when I read the file. The output I want to get is {(2.0, 7.0), (3.0, 5.0), (11.0,17.0), (23.0, 19.0), (150.0, 1.0)}. How can I fix it?
Add a toString method to your Point which formats the Point as x, y
public class Point {
//...
#Override
public String toString() {
return x + ", " + y;
}
}
Move your toString method so it's defined in PointArray, you might also consider making use of StringJoiner to make your life simpler
public class PointArray {
//...
#Override
public String toString() {
StringJoiner sj = new StringJoiner(", ", "{", "}");
for (int i = 0; i < points.length; i++) {
sj.add("(" + points[i].toString() + ")");
}
return sj.toString();
}
}
I'm doing a Phone Directory project and we have to read from a directory file telnos.txt
I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.
I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.
Console
run:
telnos.txt
null
loadData tested successfully
Please enter a name to look up: John
-1
Not found
BUILD SUCCESSFUL (total time: 6 seconds)
ArrayPhoneDirectory.java
import java.util.*;
import java.io.*;
public class ArrayPhoneDirectory implements PhoneDirectory {
private static final int INIT_CAPACITY = 100;
private int capacity = INIT_CAPACITY;
// holds telno of directory entries
private int size = 0;
// Array to contain directory entries
private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];
// Holds name of data file
private final String sourceName = "telnos.txt";
File telnos = new File(sourceName);
// Flag to indicate whether directory was modified since it was last loaded or saved
private boolean modified = false;
// add method stubs as specified in interface to compile
public void loadData(String sourceName) {
Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else
telno = read.nextLine();
add(name, telno);
i++;
}
}
public String lookUpEntry(String name) {
int i = find(name);
String a = null;
if (i >= 0) {
a = name + (" is at position " + i + " in the directory");
} else {
a = ("Not found");
}
return a;
}
public String addChangeEntry(String name, String telno) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setNumber(telno);
} else {
add(name, telno);
}
}
return null;
}
public String removeEntry(String name) {
for (DirectoryEntry i : theDirectory) {
if (i.getName().equals(name)) {
i.setName(null);
i.setNumber(null);
}
}
return null;
}
public void save() {
PrintWriter writer = null;
// writer = new PrintWriter(FileWriter(sourceName));
}
public String format() {
String a;
a = null;
for (DirectoryEntry i : theDirectory) {
String b;
b = i.getName() + "/n";
String c;
c = i.getNumber() + "/n";
a = a + b + c;
}
return a;
}
// add private methods
// Adds a new entry with the given name and telno to the array of
// directory entries
private void add(String name, String telno) {
System.out.println(name);
System.out.println(telno);
theDirectory[size] = new DirectoryEntry(name, telno);
size = size + 1;
}
// Searches the array of directory entries for a specific name
private int find(String name) {
int result = -1;
for (int count = 0; count < size; count++) {
if (theDirectory[count].getName().equals(name)) {
result = count;
}
System.out.println(result);
}
return result;
}
// Creates a new array of directory entries with twice the capacity
// of the previous one
private void reallocate() {
capacity = capacity * 2;
DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
System.arraycopy(theDirectory, 0, newDirectory,
0, theDirectory.length);
theDirectory = newDirectory;
}
}
ArrayPhoneDirectoryTester.java
import java.util.Scanner;
public class ArrayPhoneDirectoryTester {
public static void main(String[] args) {
//create a new ArrayPhoneDirectory
PhoneDirectory newTest = new ArrayPhoneDirectory();
newTest.loadData("telnos.txt");
System.out.println("loadData tested successfully");
System.out.print("Please enter a name to look up: ");
Scanner in = new Scanner(System.in);
String name = in.next();
String entryNo = newTest.lookUpEntry(name);
System.out.println(entryNo);
}
}
telnos.txt
John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231
In your code:
Scanner read = new Scanner("telnos.txt");
Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt".
To make the Scanner understand that it has to scan a file you have to either:
Scanner read = new Scanner(new File("telnos.txt"));
or create a File object and pass its path to the Scanner constructor.
In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:
String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);
You need to also catch the FileNotFoundException in the function as follows:
public void loadData(String sourceName) {
try {
Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
int i = 1;
String name = null;
String telno = null;
while (read.hasNextLine()) {
if (i % 2 != 0)
name = read.nextLine();
else {
telno = read.nextLine();
add(name, telno);
}
i++;
}
}catch(FileNotFoundException ex) {
System.out.println("File not found:"+ex.getMessage);
}
}
You are actually parsing the filename not the actual file contents.
Instead of:
new Scanner("telnos.txt")
you need
new Scanner( new File( "telnos.txt" ) )
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
So I have a file that has names along with 11 popularity ranks which looks like this. <--- (this is a link) I am a bit confused on what I am suppose to do with this next part that I have for my assignment. Generally I have a name app that looks like this:
public class Name{
private String givenName;
private int[] ranks = new int[11];
public Name(String name, int[] popularityRanks){
givenName = name;
for (int i = 0; i < 11; i++){
ranks[i] = popularityRanks[i];
}
}
public String getName(){
return givenName;
}
public int getPop(int decade){
if (decade >= 1 && decade <= 11){
return ranks[decade];
}
else{
return -1;
}
}
public String getHistoLine(int decade){
String histoLine = ranks[decade] + ": ";
return histoLine;
}
public String getHistogram(){
String histogram = "";
for (int i = 0; i < 11; i++){
histogram += ranks[i] + ": " + this.getHistoLine(i)
+ "\n";
}
return histogram;
}
}
It is not finished for the getHistoLine but that doesn't have anything to do with what I am trying to do. Generally I want to take these names in from the file and create an array of list.
How he describes it:
Create the array in main, pass it to the readNamesFile method and let that method fill it with Name objects
Test this, by printing out various names and their popularity rankings
For example, if main named the array, list, then upon return from the readNamesFile method do something like:
System.out.println( list[0].getName() + list[0].getPop(1) );
This is what my main looks like:
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class NameApp{
public static void main(String[] args){
Name list[] = new Name()
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
}
}
}
I am just a bit confused how I can take the name have it send to the Name object list[] and then take the popularity ranks and send it to the Name object list[]. So when I call
list[0].getName()
it will just call the name for one of the lines... Sorry I am a bit new to the java language. Thanks in advance
You need to create a Name list correctly. I would use a List since you don't know how many names there will be;
public static void main(String[] args){
List<Name> list = new ArrayList<Name>();
loadFile();
System.out.println(list.get(0).getPop());
}
private static void loadFile(){
Scanner inputStream = null;
String fileName = "names.txt";
try {
inputStream = new Scanner (new File(fileName));
}
catch (FileNotFoundException e){
System.out.println("Error opening file named: " + fileName);
System.out.println("Exiting...");
}
while (inputStream.hasNext()){
// givenName = something
// ranks = something;
list.add(new Name(givenName, ranks);
}
}
Assuming each line is something like this (from your deleted comment)
A 1 234 22 43 543 32 344 32 43
Your while loop can be something like this
while (inputStream.hasNextLIne()){
String line = inputStream.nextLine();
String tokens = line.split("\\s+");
String givenName = tokens[0];
int[] numList = new int[tokens.lenth - 1];
for (int i = 1; i < tokens.length; i++){
numList[i - 1] = Integer.parseInt(tokens[i].trim());
}
list.add(new Name(givenName, numList);
}
I have two arrays the store the values of two lines that are read in from a file. After some processing in my GUI class it should show to rectangles side by side in the middle of the frame. However only one ever shows up. I have tried every way I know how to get the other one to show up but no dice. Here is my code:
public class PortraitFileReader
public static ArrayList<Drawable> readFile(File a) {
File myFile;
ArrayList<Integer> values = new ArrayList<Integer>();
ArrayList<Drawable> couple = new ArrayList<Drawable>();
Man aMan;
Woman aWoman;
Point aPoint;
String input;
String [] array = null;
String [] array2 = null;
try {
myFile = a;
Scanner inFile = new Scanner(myFile);
input = inFile.nextLine();
array = input.split(", ");
while(inFile.hasNext()) {
input = inFile.nextLine();
array2 = input.split(", ");
System.out.println(Arrays.toString(array2));
}
if(array[0].equals("man")) {
for(int i=1; i<array.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aMan = new Man(aPoint, values.get(2), values.get(3), array[5]);
couple.add(aMan);
values.clear();
}
if(array[0].equals("woman")) {
for(int i=1; i<array.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aWoman = new Woman(aPoint, values.get(2), values.get(3), array[5]);
couple.add(aWoman);
values.clear();
}
if(array2[0].equals("man")) {
for(int i=1; i<array2.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aMan = new Man(aPoint, values.get(2), values.get(3), array2[5]);
couple.add(aMan);
values.clear();
}
if(array2[0].equals("woman")) {
for(int i=1; i<array2.length-1; i++) {
int current = Integer.parseInt(array[i]);
values.add(current);
System.out.println(values);
}
aPoint = new Point(values.get(0), values.get(1));
aWoman = new Woman(aPoint, values.get(2), values.get(3), array2[5]);
couple.add(aWoman);
values.clear();
}
}
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
return couple;
}
}
This is the data that I'm reading in from the file:
man, 260, 100, 40, 80, Tom
woman, 300, 100, 40, 80, Sally
Any help would be greatly appreciated.
NOTE: the system.out.println's are just there to test if each array had the right values in it.
When you are going through array2 checking if it is a woman, you are actually going through the variable array.
for(int i=1; i<***array2***.length-1; i++) {
int current = Integer.parseInt(****array***[i]);
The same goes for when you are checking if array2 is a man
The effect of this is that you are processing the contents of the first line twice.
Um, I can barely read it, so I rewrote it:
public class PortraitFileReader {
public static ArrayList<Drawable> readFile(File file) {
ArrayList<Drawable> couple = new ArrayList<Drawable>();
try {
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
couple.add(parseLine(scanner.nextLine()));
}
}
catch (FileNotFoundException e) {
System.out.println("The file was not found.");
}
return couple;
}
public static Drawable parseLine(String line) {
String [] array = line.split(", ");
String gender = array[0];
int pointX = Integer.parseInt(array[1]);
int pointY = Integer.parseInt(array[2]);
int width = Integer.parseInt(array[3]);
int height = Integer.parseInt(array[4]);
String name = array[5];
if(gender.equals("man")) {
return new Man(new Point(pointX, pointY), width, height, name);
} else {
return new Woman(new Point(pointX, pointY), width, height, name);
}
}
}
Anyway, it looks like either you're not drawing your drawable right, or the input in the file isn't exactly formatted as you expect. The parsing itself seems to make sense....
except that you're always parsing array, and not switching it to parseInt(array2[i]) in the 3rd and 4th block. Which just demonstrates why collapsing these cut and pasted blocks into one method is the sensible way to go.
Inlining everything would look like the above with these edits:
....
Scanner scanner = new Scanner(file);
while(scanner.hasNext()) {
String line = scanner.nextLine();
Drawable person = null;
// everything from parseLine, change return to assignment to person
couple.add(person);
}
....