I want to remove elements from an arraylist with the method:
public static String removeOldestItem(ArrayList<String> theList)
and to write the removed elements to a text file using this method:
public static void addItem(ArrayList<String> theList, String s)
So far I have:
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList <String> s = new ArrayList<> (4);
s.add("Knock knock.");
s.add("Who's there?");
s.add("*very long pause....*");
s.add("Java");
try {
FileWriter fos = new FileWriter("list_contents.txt");
PrintWriter out = new PrintWriter(fos);
for (int i = 0; i < s.size(); i++) {
out.write(String.valueOf(s.get(i) ) );
out.write("\r\n");
}
out.close();
} catch (Exception e) {
}
}
}
The second method should place the String “s” into the passed list “theList”. The first method should remove the item that has been in the list the longest and return that item to the caller.
I'm having trouble understanding how to implement the methods.
Any thoughts?
I'm not aware of a removeOldestItem method on ArrayList, however linked lists and linked hash maps have removeEldestEntry. It is generally overridden to produce a cache with some sort of smart pruning.
Is your goal to extend ArrayList and an OutputStream by adding a couple convenience methods?
Related
The goal is to fill an ArrayList with custom Country objects made up of information from a separate text file. The while loop gives me the "identifier expected" error, and I'm at my wit's end trying to fix it.
import java.util.Scanner;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
public class Driver {
public static void main(String[] args) {
//Instance variables
Scanner sc;
Country next = new Country();
String reader;
int size;
ArrayList<Country> ledger = new ArrayList<Country>();
//Suppressing this exception because I know it's there.
#SuppressWarnings("unreported exception FileNotFoundException; must be caught or declared to be thrown")
sc = new Scanner(new File("testLedger.txt"));
//"<identifier> expected" error
while (sc.hasNext()) {
next.setName(sc.nextLine());
next.setFaith(sc.nextLine());
next.setInfo(sc.nextLine());
next.setOrder(sc.nextInt());
ledger.add(next);
}
//Test accessor methods and filling of the ArrayList
for (int i = 0; i < ledger.size(); i++) {
System.out.println(ledger.get(i));
}
}
}
First, your code will not compile. You need to handle the exceptions. As in this case you are just running a test, you can use a Throw in the main method.
try {
sc = new Scanner(new File("testes.txt"));
while (sc.hasNext()) {
next.setName(sc.nextLine());
next.setFaith(sc.nextLine());
next.setInfo(sc.nextLine());
next.setOrder(sc.nextInt());
ledger.add(next);
}
} catch (FileNotFoundException e) {
System.out.println(e);
}
Second, look at the setters of your Country class and see if the method types are compatible with what you are using in the while.
For example:
sc.nextLine () // will return a String
sc.nextInt () // will return an int
your setters should be compatible with this
public void setOrder(int order){
this.order = order;
}
and Finally, as mentioned by #Dawood in comments, you need do see stackoverflow.com/q/13102045
I'm trying to create an ArrayList of type Item in my Store class and then test it in another class called StoreTester. I keep getting the error: The method get() is undefined for the type Store. So Java thinks my tester object of type Store is not an ArrayList even though I tried to make it so.
My Store class constructor:
import java.util.ArrayList;
public class Store
{
private ArrayList<Item> blockbuster;
public Store(){
blockbuster = new ArrayList<Item>();
}
public void addItem(Item i){
blockbuster.add(i);
}
}
This is my StoreTester class:
import java.util.ArrayList;
public class StoreTester{
public static void main(String[] args){
Store videostore = new Store();
System.out.print(videostore.toString());
System.out.print(videostore.get(0));
}
}
For some reason videostore.toString() works fine and prints out the list of objects I've added to it. Here is the method toString I wrote in my Store class:
public String toString(){
String item = "Items in store: " + "\n";
for(int j = 0; j < blockbuster.size(); j++){
item = item + blockbuster.get(j).getTitle() + "\n";
}
return item;
}
but as soon as I try to get() a specific object at an index or even use videostore.size(), i get the: method undefined error. Hopefully it is just a syntax error or something simple I've overlooked. Any help is appreciated.
Yes, Store does not have a method get
It can be implemented in Store as
public Item get (int index) {
// check for null, then
return blockbuster.get(index);
}
Store has-a ArrayList it is not Store is-a ArrayList
As #ElliottFrisch also mentions, you will need to implement a size method as well
public int size () {
// check for null, then
return blockbuster.size();
}
I'd like to populate an array list with lines from an input file, the input file looks like this:
7f00000000000000000000000000000000000000000000000000000000000000027f00000000000000000000000000000000000000000000000000000000000000027f00000000000000000000000000000000000000000000000000000000000000020101
7f00000000000000000000000000000000000000000000000000000000000000037f00000000000000000000000000000000000000000000000000000000000000037f00000000000000000000000000000000000000000000000000000000000000030101
7f00000000000000000000000000000000000000000000000000000000000000047f00000000000000000000000000000000000000000000000000000000000000047f00000000000000000000000000000000000000000000000000000000000000040101
7f00000000000000000000000000000000000000000000000000000000000000057f00000000000000000000000000000000000000000000000000000000000000057f00000000000000000000000000000000000000000000000000000000000000050101
7f00000000000000000000000000000000000000000000000000000000000000067f00000000000000000000000000000000000000000000000000000000000000067f00000000000000000000000000000000000000000000000000000000000000060101
The data object in Java that I'd like to create based on this would have each one of those lines as a new string, and they would live together in a list, so to speak*.
So, in my attempt to read in the lines of the file into different components of this array list, I can't figure out where I need to declare the array list in my main program. My plan is to populate it in a separate method:
import java.io.*;
import java.util.Scanner;
import java.util.List;
import java.util.Array;
import java.util.ArrayList;
class evmTest {
public static void main(String[] args) {
Array<String> inputLinesObject = new ArrayList<String>();
// populate from file
inputLinesObject = readFile("/Users/s.matthew.english/codes.txt", inputLinesObject);
System.out.println(Array.toString(inputLinesObject));
}
private static void readFile(String fileName, Array<String> inputLines) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
// System.out.println(scanner.nextLine());
inputLines.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return inputLines;
}
}
Maybe I can initially instantiate it as null, and then pass that null array list to the method to be populated?
* The terms in that last sentence are not totally precise- please forgive me- I'm re-adjusting to the vocabulary of Java, nevertheless I think it should be clear enough what I'm trying to do. If not please let me know and I'll be happy to clarify.
For your test, you simply have to instantiate the ArrayList just above the try
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class EvmTest {
public static void main(final String[] args) {
// populate from file
final List<String> inputLinesObject = EvmTest.readFile("/Users/s.matthew.english/codes.txt");
for (final String line : inputLinesObject) {
System.out.println(line);
}
}
private static List<String> readFile(final String fileName) {
final List<String> inputLinesObject = new ArrayList<>();
try {
final File file = new File(fileName);
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
// System.out.println(scanner.nextLine());
inputLinesObject.add(scanner.nextLine());
}
scanner.close();
} catch (final FileNotFoundException e) {
e.printStackTrace();
}
return inputLinesObject;
}
}
That has 2 advantages:
- You don't modify an input parameter of your readFile method
- You don't have to handle the case where the List is empty or null
You actually have three options:
Pass in a presumably empty list as a parameter into the method, and then add elements to the list:
static void readFile(String filename, List<String> inputLines) {
// For each line
inputLines.add(line);
}
You can then call is this way:
List<String> inputLines = new ArrayList<>();
readFile("someFilename", inputLines);
Let the readFile() method return a list:
static List<String> inputLines(String filename) {
List<String> lines = new ArrayList<>();
// For each line
lines.add(line);
// And then return the list with lines:
return lines;
}
And then call it this way:
List<String> lines = readFile("someFilename");
Don't reinvent the wheel and use functional programming to get the lines of the file:
List<String> lines = Files.lines(Paths.get("somefile"))
.collect(Collectors.toList());
The second one is way better than the first one, since it leaves the responsibility to create the list to the method itself. However, the latter is the best option.
A few more things:
Stick to the Java Naming Conventions: class names should start with uppercase.
You are using an Array<String>, but java.util.Arrray doesn't exist. I assume you mean List<String>.
Use this code for readFile() method:
private static List<String> readFile(String fileName, List<String> inputLines) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
// System.out.println(scanner.nextLine());
inputLines.add(scanner.nextLine());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return inputLines;
}
and then call this readFile() method as below:
List<String> inputLinesObject = new ArrayList<String>();
inputLinesObject = readFile("/Users/s.matthew.english/codes.txt", inputLinesObject);
for(String str : inputLinesObject){
System.out.println(str);
}
Create a singleton class with a composition of ArrayList.
You can create a sinleton like this
import java.util.ArrayList;
import java.util.List;
public class FileLines {
private List<String> lines;
private FileLines() {
lines = new ArrayList();
}
private static class FileListHolder {
private final static FileLines instance = new FileLines();
}
public static FileLines getInstance() {
return FileListHolder.instance;
}
public void addLine(String line) {
lines.add(line);
}
public String getLine(int lineNumber) {
return lines.get(lineNumber);
}
}
and in your main program use it
FileLines fileLines = FileLines.getInstance();
fileLines.addLine(scanner.nextLine());
And in other part of your programm you can retrieve a line with
FileLines fileLines = FileLines.getInstance();
fileLines.getLine(12);
so I'm trying to figure out how to print the actual contents, not memory locations, of my array list
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class hw2redo
{
public static void main(String args[]) throws FileNotFoundException
{
//Scan file for data
GeometricObject g = null;
BufferedReader file = new BufferedReader(new FileReader("file.txt"));
Scanner diskScanner = new Scanner(file);
//Create dynamic array list
ArrayList<GeometricObject> list = new ArrayList<GeometricObject>();
//Scan data and add data to list
while(diskScanner.hasNext())
{
String geolist = diskScanner.nextLine();
g = recreateObject(geolist);
list.add(g);
}
showObjects(list);
}
private static GeometricObject recreateObject(String data)
{
GeometricObject object = new GeometricObject(data);
return object;
}
private static void showObjects(ArrayList<GeometricObject> list)
{
for(GeometricObject o : list)
System.out.println(o);
}
}
class GeometricObject
{
public GeometricObject(String data) {
// TODO Auto-generated constructor stub
}
}
So here is my code. I have tried using the toString() and Arrays.toString() but they dont seem applicable for an arraylist (I tried because they worked on my regular arrays).
The output I'm recieving is
// Output
GeometricObject#55f96302
GeometricObject#3d4eac69
GeometricObject#42a57993
GeometricObject#75b84c92
GeometricObject#6bc7c054
GeometricObject#232204a1
which is good because I'm close, I just need to figure out how to print the actual contents.
The content I'm looking for in my file.txt is
Circle,green,false,4.0
Circle,blue,false,2.0
Circle,blue,true,7.0
Rectangle,orange,true,10.0,6.0
Rectangle,green,false,5.0,11.0
Rectangle,red,true,14.0,12.0
Any help would be much appreciated. Thanks!
You need a toString method in your class:
class GeometricObject
{
private String data;
public GeometricObject(String data) {
this.data = data;
}
#Override
public String toString() {
return data;
}
}
Without the Override, you are using Object.toString(). Object's toString prints out the class name and the hashcode of the object, as you have observed.
System.out.println(o);
When you call System.out.println, That apparently calls the toString() method of your Object. Since you didn't ovveride toString(), it calls the default implementation. Ovveride toString() method to print as you wish.
public class GeometricObject {
....
#Override
public String toString() {
// return string representation of your object.
}
}
To starts with :What is the best standard style for a toString implementation?
I am trying to return an arraylist from this method
import java.io.*;
import java.util.*;
/** The class reader read the file 2RainfallDataLanc.txt and stores is as an ArrayList.
* It also parses the variables within the file by white spaces, making variables accessible.
*
*/
public class reader {
public ArrayList<String[]> getRows(){
try {
BufferedReader reader = new BufferedReader(new FileReader("2RainfallDataLanc.txt"));
String line = null;
ArrayList<String[]> rows = new ArrayList<String[]>();
while((line=reader.readLine())!=null)
{String[] row = line.split("\\s+");
rows.add(row);
}
for (String[] row : rows) {
System.out.println(Arrays.toString(row));
return rows;
}
} catch (IOException e) {
}
return null;
}
}
As I wish to use it in another class. The second class currently looks like this :
public class mean extends reader{
public static void main(String[] args) {
reader newarray = new reader();
}
}
Could someone tell me what am I doing wrong? Whenever I try to return rows I get an error message saying that void methods cannot return a value.
You didn't create a method in your reader object with which to return something from. Create a method signature like the following:
public ArrayList<String[]> getRows() {
// Rest of your code here.
}