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);
}
....
Related
public static FAQ_Alisa_QnA[] oipReadQuestion(){
String questionA1,thisUser;
int indexQuestion;
String [] entryDetails;
FAQ_Alisa_QnA [] entries = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File file = new File ("ReadOIP.txt");
int count = 0;
try{
Scanner sc = new Scanner(file);
//do this while there is a next line in file.
while(sc.hasNextLine()){
String line = sc.nextLine();
entryDetails = line.split(";");
// index = entryDetails[0];
indexQuestion = Integer.parseInt(entryDetails[0]);
thisUser = entryDetails[1];
questionA1 = entryDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexQuestion = indexQuestion;
a.thisUsername = thisUser;
a.questionA1 = questionA1;
entries [count] = a;
count++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA [] allQuestions = new FAQ_Alisa_QnA [count];
for(int i = 0; i < count; i++){
allQuestions[i] = entries[i];
}
return allQuestions;
}
public static FAQ_Alisa_QnA[] oipReadAnswers(){
String indexAnswer, answer11, thisUser;
String [] answerDetails;
FAQ_Alisa_QnA [] answers = new FAQ_Alisa_QnA[100];
//Read file = "activities.txt".
File thisFile = new File ("AnsReadOIP.txt");
int count1 = 0;
try{
Scanner sc1 = new Scanner(thisFile);
//do this while there is a next line in file.
while(sc1.hasNextLine()){
String line = sc1.nextLine();
answerDetails = line.split(";");
// index = entryDetails[0];
indexAnswer = answerDetails[0];
thisUser = answerDetails[1];
answer11 = answerDetails[2];
//Object to store values of entry.
FAQ_Alisa_QnA a = new FAQ_Alisa_QnA();
// a.index = Integer.parseInt(index);
a.indexAnswer = Integer.parseInt(indexAnswer);
a.thisUsername = thisUser;
a.answer11 = answer11;
answers [count1] = a;
count1++;
}
}catch(FileNotFoundException fnfe){
System.out.println(fnfe.getMessage());
}
FAQ_Alisa_QnA[] allAnswers = new FAQ_Alisa_QnA[count1];
for(int i = 0; i < count1; i++){
allAnswers[i] = answers[i];
}
return allAnswers;
}
public static void oipPrintQnA(){
FAQ_Alisa_QnA [] allQuestions = oipReadQuestion();
FAQ_Alisa_QnA [] allAnswers = oipReadAnswers();
System.out.println("Organization in project work");
System.out.println("=============================");
for(int i = 0; i < allQuestions.length; i++){
System.out.println( allQuestions[i].indexQuestion + "-" + "Question" + ":");
System.out.println(allQuestions[i].thisUsername + ":" +allQuestions[i].questionA1);
System.out.println(" ");
for(int j = 0; j < allAnswers.length; j++){
if(allQuestions[i].indexQuestion == allAnswers[j].indexAnswer){
System.out.println("Answer for question "+ + allAnswers[j].indexAnswer+ ":" );
System.out.println(allAnswers[j].thisUsername+ ":" +allAnswers[j].answer11);
System.out.println(" ");
}
}
}
}
//So I have read answers and questions and I saved my qns and answers in 2 different text files. This is because I have add functions to it but i never put it here cuz my qn is not related to that. I just wanna know how to print out the qn and answer in 2 lines so that if the qn is so long then it can print out in two lines//
So these are how my text files look like:
ReadOIP.txt
1;Shafiq;How to organize your time well when you're juggling with so many project work and assignments on the same day? Best answer:The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment.
2;Rohannah;Does having a timetable works to finish your project on time?
3;lymeoww;Is task allocation really important to be organized in project work?
AnsReadOIP.txt
1;Andy23;The best solution to this is to early planning or schedule your time wisely. Write in a calendar beforehand the work you are going to do for an assignment .2; Does having a timetable to do your project works? //For example this line, it will print out very long on the console//
2;Betty23;of course it does!
1;Ying Qian;just organize lorh
3;lymeoww;Yes, it is important!
//Refer to this picture//
i have file txt in desktop :
1 5 23
2 5 25
3 30 36
i want sum column by column 1 + 2 + 3 =... and 5 + 5...n and 23,...n
Scanner sc = new Scanner (file("patch");
while (sc.hasNextLine)
{
//each sum by column
}
help me please thanks
I would use a try-with-resources to clean up my Scanner using the File. Also, you could construct a Scanner around the line of input to get your int columns (that doesn't need to be closed because String(s) aren't closable anyway). Something like,
try (Scanner sc = new Scanner(new File("patch"))) {
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
long sum = 0;
int count = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (count == 0) {
System.out.print(val);
} else {
System.out.printf(" + %d", val);
}
sum += val;
count++;
}
System.out.println(" = " + sum);
}
} catch (IOException e) {
e.printStackTrace();
}
As the Scanner(String) Constructor Javadoc documents
Constructs a new Scanner that produces values scanned from the specified string.
Edit To sum the columns is a little trickier, but you could read everything into a multidimensional List<List<Integer>> like
try (Scanner sc = new Scanner(new File("patch"))) {
List<List<Integer>> rows = new ArrayList<>();
int colCount = 0;
while (sc.hasNextLine()) {
List<Integer> al = new ArrayList<>();
String line = sc.nextLine();
Scanner row = new Scanner(line);
colCount = 0;
while (row.hasNextInt()) {
colCount++;
int val = row.nextInt();
al.add(val);
}
rows.add(al);
}
for (int i = 0; i < colCount; i++) {
long sum = 0;
for (List<Integer> row : rows) {
sum += row.get(i);
}
if (i != 0) {
System.out.print("\t");
}
System.out.print(sum);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Edit 2 For efficiencies sake, you might prefer to use a Map like
try (Scanner sc = new Scanner(new File("patch"))) {
Map<Integer, Integer> cols = new HashMap<>();
while (sc.hasNextLine()) {
String line = sc.nextLine();
Scanner row = new Scanner(line);
int colCount = 0;
while (row.hasNextInt()) {
int val = row.nextInt();
if (cols.containsKey(colCount)) {
val += cols.get(colCount);
}
cols.put(colCount, val);
colCount++;
}
}
for (int i : cols.values()) {
System.out.printf("%d\t", i);
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
Please find the code. Please go through the comments.
This is one way of doing for your reference. I want you to try other ways to improve your knowledge rather just using this code.
int sums[] = null;
while (sc.hasNextLine())
{
String row = sc.next();// get first row
String[] values = row.split(" ");// split by space
if(null == sums)
{
sums = new int[values.length];// create sum array with first row size
}
int index = 0;
for (String value : values)
{
sums[index] = sums[index]+Integer.parseInt(value);//adding current row value to current sum
index++;
}
}
if(null != sums)
{
int index=0;
for (int sum : sums)
{
System.out.println("Sum of column "+index+" : "+sum);// Printing each column sum
index++;
}
}
If your file is CSV formatted, then split line by comma(",") and find number of columns based on split array length.
Like below:
String line = sc.next();
String[] lineArr = line.split(",");
int len = lineArr.length;
create array of arraylists of size len and store each column field in the respective arraylist.
finally, at the end apply sum on each arraylist to calculate sum of each column values.
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);
}
Hi I have a problem with reading a text-file:
I load into Java a file called huizen.txt, which is the following: (I put it in workspace, C:\, src, bin, in Files in the project itself and on the desktop, still dont know where to put it correctly)
3
Emmalaan 23
3051JC Rotterdam
7 kamers
prijs 300000
Javastraat 88
4078KB Eindhoven
3 kamers
prijs 50000
Javastraat 93
4078KB Eindhoven
4 kamers
prijs 55000
Now I want (in the end......) to say loop for 3 times through a read-method for appartments since 3 is the number of appartments. But when I try: int NumberOfAppartmentsInList = scanner.nextInt(); , this does not work! I get false even for scanner.hasNextInt(), even when I try NumberOfAppartmentsInList = Integer.parseInt(list.get(0)) when I create an arraylist for the string lines..
Can anyone help me out?
Tnx in advance!
Grtz (code below)
public static Portefeuille read(String infile) throws Exception
{
Portefeuille protonX = new Portefeuille();
ArrayList<String> huizen = new ArrayList<String>();
Scanner sc = new Scanner("huizen.txt");
while (sc.hasNext())
{
huizen.add(sc.nextLine());
}
String infil3 = huizen.toString();
Scanner scan = new Scanner(infil3);
if (scan.hasNextInt())
{
int aantal = scan.nextInt();
System.out.println(aantal);
}
else{
System.out.println("ERROR");
}
ArrayList<Woning> list = new ArrayList<Woning>();
for (int i = 0; i < 4; i++)
{
list.add(Woning.read(scan));
}
scan.close();
sc.close();
return protonX;
}
You did not read the data in the right order, I guess. Plus huizen.toString() will not give you the sum of all strings.
So the one way to fix it might be like this:
public static Portefeuille read(String infile) throws Exception
{
Portefeuille protonX = new Portefeuille();
ArrayList<String> huizen = new ArrayList<String>();
Scanner sc = new Scanner("huizen.txt");
while (sc.hasNext())
{
huizen.add(sc.nextLine());
}
String infil3 = "";
for (String h : huizen)
{
infil3 += h + "\n";
}
Scanner scan = new Scanner(infil3);
if (scan.hasNextInt())
{
int aantal = scan.nextInt();
System.out.println(aantal);
}
else{
System.out.println("ERROR");
}
ArrayList<Woning> list = new ArrayList<Woning>();
for (int i = 0; i < aantal; i++)
{
list.add(Woning.read(scan));
}
scan.close();
sc.close();
return protonX;
}
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");
}
}