I am studying Java and using BlueJ so my question relates to part of an assignment I have been asked to do. Some of it works but I am having problems with other parts. I will include everything that I have done in the class so far but first here are the requirements:
Prompt user to select an appropriate file // done and working
Use BufferedReader and Scanner objects to read a file line by line // done and assume working!
As each line containing the name and age of a runner is read, a new Runner object should be created and its instance variable set as follows: // Class Runner already created
// Class MathatonAdmin - current class.
3a) name - can be set directly using the value from the file.
// tested with System.out.println and all values (in display panel) are shown (*).
3b) ageGroup - can be worked out from the given age: runners under 18 should be categorised as junior, 55 and older as senior, all else as standard.
// tested with System.out.println and all values (in display panel) are shown (*).
3c) The instance of Runner should be added to the list referenced by the instance variable runners.
Essentially when I run the test code provided:
MarathonAdmin ma = new MarathonAdmin();
ma.readInRunners();
I am supposed t o see a list of runners when I inspect ma; currently one the name and age of a single person is listed.
So I need help with 3a - 3c. How do I create a new instance of Runner with said variables, then add the instance Runner to the list in runners?
I have tried a for loop in while loop but since I am guessing the for loop I do not get the required list in the variable ma.
I am using System.out.println for testing that I at lest have the correct file.
Any help or advice will be appreciated.
The class MarathonAdmin:
import java.util.*;
import java.io.*;
import ou.*;
/**
* MatharthonAdmin Class
*
* #author Stephen Berry
* #version 28/03/14
*/
public class MarathonAdmin
{
// instance variables
private String runners;
private String age;
/**
* Constructor for objects of class MarathonAdmin
*/
public void MarathonAdmin()
{
List<String> runners = new ArrayList<>();
}
public void readInRunners()
{
String pathName = OUFileChooser.getFilename();
File aFile = new File(pathName);
BufferedReader bufferedFileReader = null;
try
{
String currentLine;
Scanner lineScanner;
bufferedFileReader = new BufferedReader(new FileReader(aFile));
currentLine = bufferedFileReader.readLine();
while (currentLine != null)
{
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
runners = lineScanner.next();
age = lineScanner.next();
for (String aList: runners)
{
Runner runners = new Runner();
if (Integer.parseInt(age) < 18)
{
System.out.println(currentLine + " : Junior");
}
if (Integer.parseInt(age) > 55)
{
System.out.println(currentLine + " : Senior");
}
if (Integer.parseInt(age) > 18 && Integer.parseInt(age) < 55)
{
System.out.println(currentLine + " : Standard");
}
currentLine = bufferedFileReader.readLine();
}
}
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
finally
{
try
{
bufferedFileReader.close();
}
catch (Exception anException)
{
System.out.println("Error: " + anException);
}
}
}
}
There are some points in your class that lead to this missbehaviour of your program.
The Exercise says that you shall create a list of runner objects as instance variable right? Look at your instance variable runners of your marathon class and look at the type of it. ;)
Your while loop is a good approach. Now inside the while loop you interate for each line of the textfile which is equivalent to one runner right? So why you need the for loop? You can use the lineScanner to get each part of the line there is no need for a second loop i try to give you a structure with pseudocode
String runnerName;
Int runnerAge;
while (currentLine != null)
{
lineScanner = new Scanner(currentLine);
lineScanner.useDelimiter(",");
runnerName = lineScanner.next();
runnerAge = lineScanner.next();
runners = lineScanner.next();
age = lineScanner.next();
create new Runner Object
set age and name of object according to the data you ve just read
runners.add(Runnerobject) // <-- this line adds the object you ve just created to the list which is your instancevariable. Make sure that this variable really is a list :)
currentLine = bufferedFileReader.readLine();
}
}
Hope this helps you a little bit.
You create a Runner instance, but you don't set the instance variables name and age/ageGroup for class Runner. You could create a constructor in the Runner class to do that. Also you should rename your variable, since runners is already used.
Further you declared runners as an instance variable of type String. But you would need to have a List. After you created the Runner instance you can add that instance to the list.
Your instance variables are incorrect. You need a list of objects not a String runners.
Also you need a method instance for age not a class instance.
private List<Runner> runners; // instance variables for a list of runner objects
runners = new ArrayList<Runner>(); // in the constructor
I would also agree with MeiSign, you do not need a for loop within the while loop
Related
I was given a file that I have to find the duplicates and put them into a new text file. That is the gist of what I am trying to accomplish. Here are the directions I was given:
Your client owns a bookstore, and you will find attached; a text file called Samsbooks.txt with
titles of all the books in the store. Write and Print all the duplicate titles to a file called
SamsDuplicate.txt.
EXAMPLE OUTPUT:
Duplicate Books
Sam’s Bookstore 2021
Jack and Jill
Peter Pan
My Little Pony
Here is my code:
enter code here
//In this program, I will write and print all the duplicate book titles to a new file called
SamsDuplicate.txt.
import java.io.*;
public class bookstore {
public static void main(String[] args) throws IOException {
//Printwriter object for the output file that is called SamsDuplicate.txt.
PrintWriter duplicates = new PrintWriter("SamsDuplicate.txt");
//Bufferreader object for the input file that is called SamsBookstore.txt.
BufferedReader original = new BufferedReader(new
FileReader("C:\\Users\\patti\\Desktop\\Patricks dcom101class\\CSIT
210\\SamsBookstore.txt.docx"));
String begin = original.readLine();
//This while loop will read each line of the SamsBookstore.txt file.
while(begin != null) {
boolean in_stock = false;
//This Bufferreader object is for the output file SamsDuplicate.txt.
BufferedReader output = new BufferedReader(new FileReader("SamsDuplicate.txt"));
String mid = output.readLine();
//This while loop will read each line of the SamsDuplicate.txt file.
while(mid != null) {
if(begin.equals(mid)) {
in_stock = true;
break;
}
mid = output.readLine();
}
//This if statement is if the boolean is false and will also write line from SamsBookstore
file to SamsDuplicate file.
if(!in_stock) {
duplicates.println(begin);
}
begin = original.readLine();
}
//Closing both files.
original.close();
duplicates.close();
System.out.println("Duplicate Books");
System.out.println("Sam's Bookstore 2021");
System.out.println();
System.out.println();
}
}
I cannot use HashMaps or anything of that nature since I have not learned about it yet. I have tried putting in the last System.out.println line: my printerwriter (duplicates), my bufferreader(output), even the name of the new file I created called SamsDuplicate.txt none of them will display the duplicates. Am I missing something here? Any help would be appreciated thanks!
Can you use Set?
Based on your code, it seems that the Samsbooks.txt has a book name per line, right?
Set has a method add, declared boolean add(E e). It returns true if the element was added and false if it was not because it already exists in the collection.
If you cannot use Set, you can implement similar functionality by storing each book name in an array. You'll need to first check if the current book name is already in the array. If it is not, then resize the array +1 and add the new book name to the end.
I'm setting a java application that has 3 separately saved classes WordApp, WordProcessor, and WordType. WordApp reads the file and is suppose to pass the data to the other classes. I can read the file but I can't the data to pass to the other classes. How to pass the information via a string?
I've searched this and every example I find has all the classes saved to the same file. I'm using textpad and I tried passing the string to the WordProcessor class which has constructs an ArrayList of WordType objects. This method is not working for me.
This is the first part of the WordApp class for reading the file.
import java.io.*; // Import IO package
import java.util.Scanner; // Import Scanner utility
import java.util.ArrayList; // Import ArrayList utility
public class WordApp // Declared WordApp Class
{
public static void main (String[] args) // Main
{
// Declared Variables
String again;
String initial = "";
String inputFileName;
String outputFileName;
// Declared Objects
Scanner input = new Scanner(System.in);
do
{
try
{
System.out.println(" Welcome to the Word Processor App! ");
System.out.println("**********************************************************************\n");
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Read: ");
inputFileName = input.nextLine().trim();
File mcFile = new File(inputFileName);
Scanner scan = new Scanner(mcFile);
System.out.println("Enter file names with .txt extension.");
System.out.print("Please Enter File Name to Save: ");
outputFileName = input.nextLine().trim();
File deFile = new File(outputFileName);
PrintWriter out = new PrintWriter(deFile);
System.out.println("Reading file...\n");
while(scan.hasNext())
{
initial = scan.next();
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial);
I'm trying to pass the words in the file here:
import java.util.ArrayList;
import java.util.Collections;
public class WordProcessor
{
private ArrayList<WordType> words;
private int totSentences;
private int totUnique;
public WordProcessor()
{
words = new ArrayList<WordType>();
totSentences = 0;
totUnique = 0;
}
and here:
public class WordType implements Comparable
{
// instance data
private String word;
private int count;
private int syllables;
// Constructors
public WordType(String newWord)
{
word = newWord;
count = 1;
syllables = countSyllables();
}
I'm expecting that that words pass to the other classes but when I save the file it is blank. Sorry if I didn't post the code correctly
You're reading the file and getting the items it holds but discarding all but the last.
while(scan.hasNext()) {
initial = scan.next();
// You do **nothing** with the String read in
}
scan.close();
System.out.println("Scanning Paragraph.....\n");
WordProcessor x = new WordProcessor();
x.addWord(initial); // until here where you add the last one
Instead create the WordProcessor object before the while loop, and add words within the while loop
WordProcessor x = new WordProcessor();
while(scan.hasNext()) {
initial = scan.next();
x.addWord(initial);
}
scan.close();
There may be other errors, especially problems in your code not shown (addWord(...) comes to mind), but this error was immediately obvious.
Also what type of looping are you doing and why? You appear to have a do-while loop -- why? Again if this does not solve your problem, then you still will need to create and post a valid mcve so we don't have to guess what the problem truly is. Please understand that I am not asking for all your code but rather for something completely different -- please read the link and understand it fully if your problem has not been solved and you still need help.
import java.util.*;
import java.io.*;
public class comparing{
static ArrayList <compare> events = new ArrayList<compare>();
public static void main(String[]args){
try{
Scanner in = new Scanner(new File("events.txt"));
File output = new File("chines.txt");
Scanner sc = new Scanner(output);
PrintWriter printer = new PrintWriter(output);
while(in.hasNext()){
int temp = in.nextInt();
String temptwo = in.nextLine();
//String s = ;
events.add(new compare(temp,temptwo));
//System.out.println("Next word is: " + temp);
Collections.sort(events);
for(int i = 0;i<events.size();i++){
printer.write(events.get(i));
System.out.println(events.get(i));
}
}
}
catch(Exception e){
System.out.println("Invalid file name");
}
}
My code above reads from a file it sorts the data then prints it out. What I would like to do is write this sorted data to another file but I keep getting the following error:
comparing.java:27: error: no suitable method found for write(compare)
printer.write(events.get(i));
You're declaring events to be an ArrayList, meaning that it contains java.lang.Object elements, thus printer.write(java.lang.Object) is what's being searched for by the compiler.
You're adding an object of your undisclosed class compare, so even declaring ArrayList<compare> wouldn't help. Hopefully your compare class has a meaningful toString, so that you can use ArrayList<compare> events, combined with printer.write(event.toString());
See the docs.
There is no write(Object) method. You can change it to write(events.get(i).toString()) to convert it to a String first.
Alternatively, use print instead of write for more input options. See write() vs print().
It can take a object as argument and calls the String.valueOf(obj) method for you:
printer.print(events.get(i));
Add this code instead of your loop
for (int i = 0; i < events.size(); i++)
{
printer.write(String.valueOf(events.get(i)));
out.write(" ");
}
I'm working on a class that will take user input to assign values to an object created in a source class. Those objects will then be added to an array, which then prints the values on it. However, the "list" under print : list is telling me that I need to initialize the variable. Why is it not recognizing that this is an array even though it seems to work fine in my do loop?
import java.util.Scanner;
import name.Names;
public class NameTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
String entry;
Scanner firstscan = new Scanner(System.in);
Scanner lastscan = new Scanner(System.in);
Scanner codescan = new Scanner(System.in);
Scanner entryscan = new Scanner(System.in);
String first;
String last;
int code;
System.out
.println("This program will prompt you to input first name, +"
+ "last name, and zip code for an individual. Hit \"x\" when finished\n");
do {
System.out.println("Enter first name:");
first = firstscan.nextLine();
System.out.println("Enter last name:");
last = lastscan.nextLine();
System.out.println("Enter zip code:");
code = codescan.nextInt();
Names nm = new Names(first, last, code);
Names[] list = new Names[25];
int count = 0;
list[count] = nm;
count++;
System.out
.println("To quit hit \"X\" or any other key followed by enter to continue:");
entry = entryscan.nextLine();
} while (!(entry.equalsIgnoreCase("x")));
for (Names print : list)
System.out.println(print + "");
}
}
For one, you are instantiating your array inside your loop, that means every time your loop runs through, it creates a new array instead of updating the old one. Then, once you leave your loop, you leave its "scope". That means everything you declare inside the loop is not available outside. The solution is to declare your array outside the loop.
Every block in java has its own scope (defined through brackets). While you can access variables that have been declared outside your block while inside it, it does not work the other way around; as you can see. Just google java scope, and you will understand more. Hope that helps ;)
You will need a method in the class Name that return the first, last name and the zip code because if you just use:
System.out.println(print + "")
You are printing the object Name and no the String that represents the attributes saved in the object.
For example you can have the method in the class Name:
String getFirst()
{
return this.first;
}
And the last line in your class Nametester can be
System.out.println(print.getFirst() + "");
I have a main class which has an ArrayList. This ArrayList has a set of values stored via iteration. I need to use this ArrayList (fileList & directoryList) value in another class. How can I achieve this?
I do not want to move the ArrayList into another class.
package com.filehandler;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class FileFinder {
public static void main(String[] args) {
// TODO Auto-generated method stub
int directoryCount = 0;
/* Declare Lists for Files & Directories */
List<String> fileList = new ArrayList<String>();
List<String> directoryList = new ArrayList<String>();
// enter code here
/* Set file location */
File myFolder = new File("O:\\The Ultimate Book Shelf\\Technical");
File[] myFileList = myFolder.listFiles();
/* Iterate the folder to get the details of Files & Folders */
for (int count = 0; count < myFileList.length; count++) {
if (myFileList[count].isFile()) {
// System.out.println("File " + myFileList[count].getName());
fileList.add(myFileList[count].getName());
} else if (myFileList[count].isDirectory()) {
directoryCount++;
// System.out.println("Directory " +
// myFileList[count].getName());
directoryList.add(myFileList[count].getName());
} else {
System.out
.println("There are no files or directories in the mentioned path. Please verify the folder location.");
}
}
System.out.println("Total Files : "
+ (myFileList.length - directoryCount));
System.out.println("Total Directories :" + directoryCount);
System.out.println(fileList);
System.out.println(directoryList);
}
}
Your other class can either accept two ArrayLists in its own constructor or as parameters for a specific method, depending on what you are trying to do. By passing them as parameters you will actually pass a reference to the ArrayLists you created in you main function, therefore the other class will be able to read the values inside.
It depends how would the array be used in the second class. You have the following options.
To use the array in a method in the second class.
To use the array as a member in the second class.
To use the array as a static member in the second class.
For 1, you can simply pass the array to the method.
For 2, you can pass the array to a constructor and initialize the member variables in the class.
For 3, you can set like SecondClass.fileList = myFileList;