I have been working on this sort of ATM (With a maximum of 50 customers), where I read a .txt file, and then create multiple instances, store them in an array, so that other classes can call on them.
When I read the file, only the last customer's information are inputted correctly - I can't ever get the first few customers to have their output correct.
There are multiple methods for each 'Set', just in case the field says 'none', so that I can leave it as a
Double.NaN or null, for example.
I have researched on a few websites, and there wasn't very much on storing instances in arrays, although on one website, it said that I should declare it just like a normal array.
private static String firstname = "";
private static String lastname = "";
private static int sin = 0;
private static int year = 0;
private static int month = 0;
private static int day = 0;
private static double sbalance = 0.0;
private static double cbalance = 0.0;
private static double cardbal = 0.0;
private static boolean confirm = false;
public int customernumber;
public static customer [] customerarray = new customer [50];
public static void readfile(){
String sb = "";
String cb = "";
String ca = "";
int counter = 0;
String thisLine;
try {
BufferedReader br = new BufferedReader(new FileReader("bankinfo.txt"));
while ((thisLine = br.readLine()) != null) {
customerarray[counter].setLastName(thisLine);
System.out.print (customerarray[counter].getLastName());
customerarray[counter].setFirstName(br.readLine());
System.out.print (customerarray[counter].getFirstName());
customerarray[counter].setSin(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getSin());
customerarray[counter].setYear(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getYear());
customerarray[counter].setMonth(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getMonth());
customerarray[counter].setDay(Integer.parseInt(br.readLine()));
System.out.print (customerarray[counter].getDay());
sb = br.readLine();
if (sb.equals("none")){
customerarray[counter].setSBalance("none") ;
System.out.print (customerarray[counter].getSBalance());
}
else {
customerarray[counter].setSBalance(Double.parseDouble(sb));
System.out.print (customerarray[counter].getSBalance());
}
cb = br.readLine();
if (cb.equals ("none")){
customerarray[counter].setCBalance ("none");
}
else if (cb != "none"){
customerarray[counter].setCBalance(Double.parseDouble(cb));
}
else{
System.out.print ("error CBalance");
}
ca = br.readLine();
if (ca.equals("none")){
customerarray[counter].setSBalance("none") ;
}
else {
customerarray[counter].setCardbal(Double.parseDouble(ca));
}
counter = counter + 1;
}
br.close();
}
catch (IOException e) {
System.err.println("Error: " + e);
}
}
The text file is fairly simple- it is composed of 9 fields for each customer.
If they do not have a certain account, it is listed as 'none', and when the reader reads them, it uses a variant method with a String input, and sets the double = Double.NaN();
The following is an example of the text file.
Each customer has 9 fields.
Tam
Christian
984635684
1996
6
12
none
10233.52
none
Yang
Wesley
324917400
1996
8
1
3233.36
none
none
Lin
Sophia
1984
1985
5
6
912.12
58.96
95.63
I don't see where you're instantiating each individual location of your customer[] with actual customer objects.
Add this line before after the start of your while loop:
customerarray[counter] = new customer();
When creating an object array, all of the elements in it default to null. You can't dereference null, so you're running into issues.
Related
I need to parse multiple files and get access to the object's methods outside of where they were initialized.
This is my code:
public static void main(String[] args) {
try {
File Attrationfile = new File("attractions.txt");
Scanner attractionscanner = null;
attractionscanner = new Scanner(Attrationfile);
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("#");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
String type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
RollerCoaster rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File Customerfile = new File("customers.txt");
Scanner Customerscanner = new Scanner(Customerfile);
while (Customerscanner.hasNext()) {
String nextline = Customerscanner.nextLine();
String[] Customercomponents = nextline.split("#");
int accountnumber =Integer.parseInt(Customercomponents[0]);
String name = Customercomponents[1];
int age = Integer.parseInt(Customercomponents[2]) ;
int balance = Integer.parseInt(Customercomponents[3]) ;
String discount = Customercomponents.length <= 4
? String.valueOf(0) : Customercomponents[4];
Customer customer= new Customer(accountnumber,name, age, balance, discount);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
This works but I can't get access to the objects outside of their loops. I am not sure how the Сustomer class would get information about the roller coaster, such as the name and price. For example, if the customer and rollercoaster objects were in the same area, I would be able to update the customer balance by taking away rollercoaster.getprice from the customer.getbalance, and setting customer.setbalance to the value of the calculation. As you have probably already gathered, I am a beginner, so I am probably going about this in the wrong way - thanks.
You can change the scope for those variables by declaring them at the start of the main method.
public static void main(String[] args) {
Customer customer = null;
RollerCoaster rollerCoaster = null;
try {
File Attrationfile = new File("attractions.txt");
Scanner attractionscanner = null;
attractionscanner = new Scanner(Attrationfile);
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("#");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
String type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
File Customerfile = new File("customers.txt");
Scanner Customerscanner = new Scanner(Customerfile);
while (Customerscanner.hasNext()) {
String nextline = Customerscanner.nextLine();
String[] Customercomponents = nextline.split("#");
int accountnumber =Integer.parseInt(Customercomponents[0]);
String name = Customercomponents[1];
int age = Integer.parseInt(Customercomponents[2]) ;
int balance = Integer.parseInt(Customercomponents[3]) ;
String discount = Customercomponents.length <= 4 ? String.valueOf(0) :
Customercomponents[4];
customer= new Customer(accountnumber,name , age , balance, discount);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Welcome to SO! As Hovercraft pointed out, the objects are declared within the scope of the loop, meaning you can't access them outside of it as you noticed. Also, they are overwritten on every iteration, since you declare and initialize the object on every pass. Consider using an ArrayList like so (here just for the customers):
ArrayList<Customer> customerList = new ArrayList<>();
try {
while (customerScanner.hasNext()) {
// ...
customerList.add(new Customer(accountnumber,name, age, balance, discount));
}
} catch (...) {
// ...
}
Here's the doc for the ArrayList. <T> is a generic type, which for you means that you can have an ArrayList<Customer>, ArrayList<RollerCoaster>, ArrayList<String> ...
Sidenote: By convention, variable names start with a lowercase letter, like Scanner customerScanner instead of Scanner Customerscanner.
Is it a question of scope? Try to declare an object outside the body of the loop.
Because in Java, the brace is a scope. The more nested braces, the smaller the scope. You can try to declare the objects you need to call in the external scope in the same or larger scope
String type = null;
RollerCoaster rollerCoaster = null;
while (attractionscanner.hasNext()) {
String nextline = attractionscanner.nextLine();
String[] Attractioncomponents = nextline.split("#");
String ridename =Attractioncomponents[0];
int price = Integer.parseInt(Attractioncomponents[1]);
type = Attractioncomponents[2];
int unknown = Integer.parseInt(Attractioncomponents[3]) ;
double speed = Attractioncomponents.length <= 4 ? 0 :
Double.parseDouble(Attractioncomponents[4]);
rollerCoaster = new RollerCoaster(ridename, price , unknown, speed);
}
So I am trying to create an object array that from a text file. The objects I am placing in the array are people objects with 4 parameters. 1st name, last name, an ID number and a height. The text file has a certain number of lines and each element is separated by an exclamation mark. I am trying to take each of the 4 elements to create an object and then place that object into an object array. Here is my code up until now. Also because I am new to java, there is not a lot that I know so the code needs to be simple.
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Participants {
public static void main(String[] args) {
String array[] = new String[35];
Object participants[] = new Object[35];
int count = 0;
int counter = -1;
try {
File myFile1 = new File("Participants.txt");
Scanner scan1 = new Scanner(myFile1);
while (scan1.hasNext()) {
counter++;
array[counter] = scan1.next();
}
} catch (IOException ioe) {
System.out.println("The file can not be read");
}
for (int i = 0; i < array.length; i++) {
StringTokenizer st = new StringTokenizer(array[i], "!");
while (st.hasMoreTokens()) {
People person = new People(st.nextToken(), st.nextToken(), st.nextToken(),
st.nextToken());
participants[i] = person;
}
}
}
}
I commented that your code basically looks okay. There are some problems I spotted, and I think you may be running into them. You are probably getting a
Exception in thread "main" java.lang.NullPointerException
at java.util.StringTokenizer.<init>(Unknown Source)
at java.util.StringTokenizer.<init>(Unknown Source)
at Participants.main(Participants.java:22)
because arrays[i] is empty in
StringTokenizer st = new StringTokenizer(array[i], "!");
which is because you allocate 35 entries:
String array[] = new String[35];
and the file contains less lines than that. At least, that's what I'm getting it with this input file:
A!B!C!D
E!F!G!H
I!J!K!L
which is to be expected.
If I change the first line of the input file into
A!B!C
I get
Exception in thread "main" java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(Unknown Source)
at Text2ObjArray.main(Text2ObjArray.java:28)
which is because you only check once for a token, but then proceed to read four:
while (st.hasMoreTokens()) {
Person person = new Person(st.nextToken(), st.nextToken(), st.nextToken(), st.nextToken());
I'll update with a solution, if it is needed, but here are two suggestions:
1) use an ArrayList instead of an array[]:
2) Check what you parse: make sure there are 4 tokens per line, and deal with the exceptional case that they are not 4.
UPDATE
Basically, there's nothing wrong with your program. You already know "
How to put values from a text file into an object array in java?".
Your program runs just fine if you feed it a file with exactly 35 lines containing at least 3 exclamation marks each. If not, it throws the appropriate exceptions:
a NullPointerException if there are less than 35 lines and
an ArrayIndexOutOfBoundsException if there are more, and
a NoSuchElementException if there are less than 3 exclamation marks on any of the lines.
(Unless, there is a problem is in the People class which is unlikely if it is a POJO).
Your code only needed a few minor changes to make it work for files with other content. I've kept it simple:
import java.io.File;
import java.io.IOException;
import java.util.*;
public class Text2ObjArray {
public static void main(String[] args) {
Person[] participants = loadFile(new File(args.length > 0
? args[0] : "Participants.txt"));
for (Person p : participants)
System.out.println("Participant: " + p);
}
I split off main merely as good practice - see 'top-down' and 'bottom-up'.
To address the NullPointerException and ArrayIndexOutOfBoundsException We'll use an ArrayList instead of an array[] to keep track of the lines we read from the file. The advantage of an ArrayList is that it can grow and shrink, which is useful if you don't know for sure if "Participants.txt" always contains 35 lines.
Also it saves us from replacing our array with a bigger one when it's full. It's a cheap, handy upgrade from an array[], and all that has changed is writing
array.get(i) instead of array[i]
array.set(i,foo) instead of array[i]=foo and
array.add(foo) instead of array[counter++]=foo and
array.size() instead of array.length. It is a dynamic array, so you can insert into any position, remove etc.
private static Person[] loadFile(File file) {
List<String> lines = new ArrayList<>();
try (Scanner scan1 = new Scanner(file)) {
while (scan1.hasNext())
lines.add(scan1.next());
} catch (IOException e) {
System.out.println("File read error: " + e.getMessage());
}
This section is changed only in that it reads up to 4 tokens, dealing with the NoSuchElementException:
Person participants[] = new Person[lines.size()];
for (int i = 0; i < lines.size(); i++) {
StringTokenizer st = new StringTokenizer(lines.get(i), "!");
String[] fields = new String[4];
for (int k = 0; k < fields.length && st.hasMoreTokens(); k++)
fields[k] = st.nextToken();
participants[i++] = new Person(fields[0], fields[1], fields[2], fields[3]);
}
return participants;
}
}
To run it successfully you'll need to replace Person to People or use this Person class:
public class Person {
private String id;
private String lName;
private String fName;
private String height;
public Person(String id, String fName, String lName, String height) {
this.id = id;
this.fName = fName;
this.lName = lName;
this.height = height;
}
public String toString() {
return "Person[" + id + ": " + lName + ", " + fName + ", " + height + "]";
}
}
I hope that this has been helpful.
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 7 years ago.
So this is my text file:
CareFlight101 0 2
PiperCub 2 99
AirAmbulance 2 1
TransWorld122 2 5
Cessna152 3 99
Eastern429 4 10
They are suppose to be aircrafts name followed my arrival time and landing priority.
I am trying to splitting it so that it takes each into account. I am having trouble splitting it though because it it throwing a 'java.lang.ArrayIndexOutOfBoundsException: 1' error
This is what I have so far:
public class TheAircrafts {
public static ArrayList<Plane> planeList;
public static void main(String[] args){
try {
File f = new File("sample_data_p3.txt");
Scanner sc = new Scanner(f);
List<Plane> people = new ArrayList<Plane>();
while(sc.hasNextLine()){
String line = sc.nextLine();
String[] details = line.split("\\s+");
String flightID = details[0];
int arrivalTime = Integer.parseInt(details[1]);
int landingPriority = Integer.parseInt(details[2]);
Plane p = new Plane(flightID, arrivalTime, landingPriority);
planeList.add(p);
}
for(Plane p: planeList){
System.out.println(p.toString());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
And in my plane class I have:
public class Plane {
private String flightID;
private int arrivalTime;
private int landingPriority;
private int numRunways;
public Plane(String flightID, int arrivalTime, int landingPriority) {
this.setflightID(flightID);
this.arrivalTime = arrivalTime;
this.landingPriority = landingPriority;
}
followed by get and set and get methods for each of the variables
You get a IndexOutOfBoundsException in this case when there is a line which not more than i elements seperated by a space.
In your case there is a line which has only one word in it. And hence when you try to get the second word which didn't exist you get an Exception.
To avoid getting so, you can check if that line has 3 words or not.
String []details = line.split("\\s+");
if(details.length == 3)
{
//do your setting
}
So I am working on a PostFix calculator that is used in command line for a class project, and I am having a little trouble on developing a memory for it. I have been told to create a hashMap and I have researched it and understand the basics of it. I have the calculating method working, but what I am having trouble trying to implement a way for the user to declare variables. For example this what the user should be able to do:
> a = 3 5 + 1 -
7
> bee = a 3 *
21
> a bee +
28
> bee 3 %
0
> a = 4
4
> 57
57
> 2 c +
c not found
> mem
a: 4
bee: 21
> exit
As you can see the user can declare variables in the format " ="
My problem is, that I am not really sure how to Implement the hashMap, I have tried doing it by setting the variable name for the hashmap by getting it from an array list, and getting the integer value from it by getting the return value from my compute method, but all I get is this error:
>Exception in thread "main" java.lang.NumberFormatException: For input string: "
Error"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Program6.main(Program6.java:42)
Here is my code currently:
import java.util.*;
import java.io.*;
public class Program6
{
private static HashMap<String,Integer> memory = new HashMap<>();
public static void main(String args[])
{
System.out.println("Servando Hernandez");
System.out.println("RPN command line calculator");
Scanner scan = new Scanner(System.in);
System.out.print(">");
while(scan.hasNextLine())
{
System.out.print("> ");
String a = scan.nextLine();
String b = "quit";
String c = "mem";
String d = "clear";
if(a.equals(b))
{
System.exit(0);
}
else
{
System.out.println(compute(a));
}
System.out.print(">");
List<String> list = new ArrayList<String>();
if(!a.isEmpty())
{
StringTokenizer var = new StringTokenizer(a);
while(var.hasMoreTokens())
{
list.add(var.nextToken());
}
}
int pos = 0;
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
memory.put(list.get(list.size()-1),pos);
}
}
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error";
}
Stack<String> tempList = new Stack<String>();
Iterator<String> iter = processedList.iterator();
while (iter.hasNext())
{
String temp = iter.next();
if (temp.matches("[0-9]*"))
{
tempList.push(temp);
}
else if (temp.matches("[*-/+]"))
{
if (temp.equals("*"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls * rs;
tempList.push("" + result);
}
else if (temp.equals("-"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls - rs;
tempList.push("" + result);
}
else if (temp.equals("/"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls / rs;
tempList.push("" + result);
}
else if (temp.equals("+"))
{
int rs = Integer.parseInt(tempList.pop());
int ls = Integer.parseInt(tempList.pop());
int result = ls + rs;
tempList.push("" + result);
}
}
else
{
return "Error";
}
}
return tempList.pop();
}
}
Does anyone know how i can make the hashMap memory on the post fix calculator work to where the user can assign variables and be able to call them back, or a better way to approach this?
Your problem is you are adding "Error" from you else clause in the compute method and then trying to parse it as a int.
public static String compute(String input)
{
List<String> processedList = new ArrayList<String>();
if (!input.isEmpty())
{
String myRegex = "[^a-zA-Z]";
StringTokenizer st = new StringTokenizer(input);
while (st.hasMoreTokens())
{
processedList.add(st.nextToken());
processedList.remove(myRegex);
processedList.remove("=");
}
}
else
{
return "Error"; //-->> problem
}
Parsing it as an int. This point compute(a) will not be null as it has "Error".
Next step you are trying to parse it as an int.
if (compute(a) != null)
{
pos = Integer.parseInt(compute(a));
}
You can change your code as
if (compute(a) != null && !compute(a).equals("Error"))
{
pos = Integer.parseInt(compute(a));
}
Also you should try you put your Integer.parseInt() code in a try catch.
Your HashMap can be used to store the variable names and their values. The key for the map will be the variable name, and the value is the number assigned to it. You currently have Integer but you might want something that handles decimals if you're going to allow things like a = 10 3 /.
In your compute(..) method you expect the input to be of the form var = <calculation> so you should first parse out the variable name which will be the key used in the hashmap memory, and after computing the calculation, store that result with memory.put(var,result);.
When computing the <calculation> part, if a variable name is encountered, look it up to find its value using memory.get(var) and use that value in the computation. With a postfix calculator, you just have to get the 2 values, followed by the operation and perform the math. The result of that is the first value of the next pair to operate on, and so on until you run out of operations and finally assign the result to the variable.
This code looks through hundreds of names and finds the popularity and meaning of them. I have two questions. what I am trying to accomplish where the error is, is to print text of the meaning of the name on to the top of my graph.
1. How can I fix this error:
BabyNames.java:82: error: cannot find symbol
String meanings = findingStatistics(console,meaningsFile);
2. By the time findingStatistics runs through twice, variable statistics is only holding the information for the meaning of the name. How can I access the popularity of the name to use my graph? Right now I have the whole method equal to the statistics, which is just the meaning.
Here is my code:
import java.util.*;
import java.io.*;
import java.awt.*;
public class BabyNames{ //ADD COMMENTS
public static final int STARTINGYEAR = 1890;
public static final int WIDTH = 60;
public static final int HEIGHT = 30;
private static String nameFinal;
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
DrawingPanel panel = new DrawingPanel(780,560);
Graphics g = panel.getGraphics();
Scanner nameFile = new Scanner(new File("names.txt"));
Scanner meaningsFile = new Scanner(new File("meanings.txt"));
Scanner nameFile2 = new Scanner(new File("names2.txt"));
intro();
fixedGraph(g);
nameFinal = nameToLowerCase(console);
if(STARTINGYEAR == 1890){
findingStatistics(console,nameFile);;
changingGraph(console,g);
}
else{
findingStatistics(console, nameFile2);
changingGraph(console,g);
}
findingStatistics(console,meaningsFile);
}
public static void intro(){
System.out.println("This program allows you to search through the");
System.out.println("data from the Social Security Administration");
System.out.println("to see how popular a particular name has been");
System.out.println("since 1890" );
System.out.println();
System.out.print("Name: ");
}
public static String nameToLowerCase(Scanner console){
String originalName = console.next();
String name = "" ;
int lengthOfName = originalName.length();
String beginingOfName = originalName.substring(0,1).toUpperCase();
String endOfName = originalName.substring(1,lengthOfName).toLowerCase();
name = beginingOfName + endOfName;
return name;
}
public static String findingStatistics(Scanner console, Scanner data){
// String nameFinal = nameToLowerCase(console);
boolean goesThroughOnce = false; //
String statistics = "";
String currWord = "";
String currLine = "";
while (data.hasNext() && goesThroughOnce == false){
currLine = data.nextLine();
Scanner lineBeingRead = new Scanner(currLine); //make other scanners?? for each file
currWord = lineBeingRead.next(); //
if (currWord.equals(nameFinal) || currWord.equals(nameFinal.toUpperCase())){ //
statistics = currLine;
goesThroughOnce = true;
System.out.println(statistics);
}
else{
}
}
return statistics;
}
public static void fixedGraph(Graphics g){ //Draws fixed things such as gray blocks and black lines
g.setColor(Color.LIGHT_GRAY);
g.fillRect(0,0,780,HEIGHT);
g.fillRect(0,560-HEIGHT,780,HEIGHT);
g.setColor(Color.BLACK);
g.drawLine(0,HEIGHT,780,HEIGHT);
g.drawLine(0,560-HEIGHT,780,560-HEIGHT);
}
public static void changingGraph(Scanner console, Graphics g){
String meanings = findingStatistics(console,meaningsFile);
g.drawString("" + meanings,0,16); //draws meaning text
int startingYear = STARTINGYEAR;
int amountOfDecades = 0;
if(startingYear == 1890){
amountOfDecades = 13;
}
else{
amountOfDecades = 8;
}
g.drawString("" + startingYear,0,552); //fencepost
for(int i=0; i<=amountOfDecades;i++){
int year = startingYear + (10 * i);
g.drawString("" + year,(WIDTH*i),552); //draws decade numbers
}
}
}
If I add a // on what the error was and not include that, just so one can understand the code better, for the name "Aaron" it should print out:
Name: AARON
Aaron f 0 0 0 0 0 0 0 0 0 883 0 0 0
AARON m English, Biblical From the Hebrew name ??????? ('Aharon) which is most likely of unknown Egyptian origin.
Shortly, I'm trying to make it print text on the graph, and making two variables for the meaning and popularity (I have them both under statistics).
Your changingGraph method is only using console in order to work out meanings, for which of course, it also needs meaningsFile. It would make far more sense to remove the call to findingStatistics from changingGraph, especially since you are calling it from main anyway.
So change the signature of changingGraph so that it takes meanings as a parameter, as well as removing the first line of the method body. It will then look like this.
public static void changingGraph(String meanings, Graphics g){
g.drawString("" + meanings,0,16); //draws meaning text
// ... and so on.
Then, when you call it, pass the value that was returned from the previous call to findingStatistics. So in your main method, you'll have this.
if(STARTINGYEAR == 1890){
findingStatistics(console,nameFile);
}
else{
findingStatistics(console, nameFile2);
}
String meanings = findingStatistics(console, meaningsFile);
changingGraph(meanings, g);