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);
Related
I am trying to create program that shows 2 outputs to the screen.
The first one being null and the 2nd one, shows values from the input file that was stored in an array of objects.
Here is my code so far:
javax.swing.JOptionPane;
import java.util.Scanner;
import java.io.File;
public class Testing {
public static void main(String[] args) {
//error checking for commandline input
if(args.length != 1){
System.out.println("Please enter at least one input file into the argument.");
//terminates the program if more than 1 is entered
System.exit(1);
}
//make an array of bird objects
final Integer SIZE = 9;
HawaiiNativeForestBirds array[] = new HawaiiNativeForestBirds[SIZE];
//output array of Nature objects to the screen (should be "null" for all elements)
System.out.println("Hawai'i Native Forest Birds ");
System.out.println("index element ");
for (int i = 0; i < SIZE; i++) {
System.out.println(" " + i + " " + array[i] );
System.out.println();
//read from file and store data from file in your Nature array of objects
//by initializing each array element using the constructor
File file = new File(args[0]);
Scanner inputFromFile = null;
array[0] = new HawaiiNativeForestBirds("'akiapola'au"," hemignathus munroi"," yellow", 800);
array[1] = new HawaiiNativeForestBirds("akepa"," loxxops coccineus"," red", 9301);
array[2] = new HawaiiNativeForestBirds("hawai'i creeper"," oreomystis mana"," yellow green", 2501);
array[3] = new HawaiiNativeForestBirds("i'iwi"," vestiara conccinea"," red green", 2501);
array[4] = new HawaiiNativeForestBirds("apapane"," himatione sanguinea"," white red", 5001);
array[5] = new HawaiiNativeForestBirds("hawai'ian amakihi"," hemignathus virens"," yellow brown", 3001);
array[6] = new HawaiiNativeForestBirds("hawaii'an hawk"," buteo solitarius"," white gray", 1100);
array[7] = new HawaiiNativeForestBirds("puaiohi"," myadestes palmeri"," brown", 125);
array[8] = new HawaiiNativeForestBirds("anianiau"," magumma parva"," light yellow", 2000);
//use toString() to display the array again with data from input file
System.out.println("index name Scientific Name Color Population");
for(int x=0;x<SIZE;x++){
System.out.println(" " + i + " " + array[i]);
}
}//end of main() method
}// end of class LastnameFirstname08
/**
* Class HawaiianTheme stores and displays the data for each HawaiianTheme object
*
*
*/
class HawaiiNativeForestBirds {
// data fields that store each object's data
private String name;
private String scientificname;
private String color;
private Integer population;
//constructor - used to initialize the three data fields
/**
* Stores the name,scientific name, color and population of the Hawaiian Birds
* This is a Constructor, which is used to Create EAch Object & Initialize DAta Fields.
*
* #param
* #param
* #param
* #param
*/
public HawaiiNativeForestBirds(String birdName, String scientificName,String birdColor, Integer birdPopulation) {
name = birdName;
scientificname = scientificName;
color = birdColor;
population = birdPopulation;
}//end of constructor
//toString() method - returns a String with the 4 data fields
public String toString() {
String output = name +" "+ scientificname + " "+ color +" "+ population;
return output;
}//end of toString()
}//end of class HawaiianTheme
The only thing missing now is the method that reads from file and stores the array of objects by initializing the arrays.
I'm still no good at combining both of these and as you can see from the code, I don't have the method yet nor I know how the format would look like to combined both.
edit 2: I finally fixed my output . I initiliazed stuff, now how to read from file and store to the array? ;_;
Output:
Hawai'i Native Forest Birds
index element
0 null
1 null
2 null
3 null
4 null
5 null
6 null
7 null
8 null
9 null
index name Scientific Name Color Population
0 'akiapola'au hemignathus munroi yellow 800
1 akepa loxxops coccineus red 9301
2 hawai'i creeper oreomystis mana yellow green 2501
3 i'iwi vestiara conccinea red green 2501
4 apapane himatione sanguinea white red 5001
5 hawai'ian amakihi hemignathus virens yellow brown 3001
6 oma'o myadester obscurus gray 17001
7 hawaii'an hawk buteo solitarius white gray 1100
8 puaiohi myadestes palmeri brown 125
9 anianiau magumma parva light yellow 2000
All I want is to show two outputs but I gotta read and store the array of objects for the 2nd output
1.Display HawaiiNativeForestBirds array array[] without initializing elements:
2.Display HawaiiNativeForestBirds array[] again but shows the array values from the file after initializing elements:
edit:
My CSV Content:
birds.csv
Try reading in each String and storing it into its own index in a array of Strings. Then check out this algorithm and see if it works. I am sure this is not the best way to handle the situation, but I am in class and thought I would give it a intuitive shot. I am going off of the base that your constructor takes 4 parameters, and also assuming that the parameters in the txt file are in order of how they would be put into the constructor. You will also have to cast the 4th parameter into a int so it matches the expected argument type for your constructor.
//Create String array and use for loop to fill temp array with words from txt file
temp[i] = scan.next()
for(int i = 0; i < temp.length; i++) {
if (i != 0) {
i = i + 3;
HawaiiNativeForestBirds[i - (3*i/4)] = new HawaiiNativeForestBirds(temp[(i-4)+4], temp[(i-4)+5], temp[(i-4)+6], temp[(i-4)+7)];
}
else {
HawaiiNativeForestBirds[i] = new HawaiiNativeForestBirds(temp[i],temp[i+1], temp[i+2], temp[i+3]);
}
}
I would solve this problem in following way.
Create a HawaiiNativeForestBirds java class
class HawaiiNativeForestBirds {
private String name;
private String scientificname;
private String color;
private Integer population;
public HawaiiNativeForestBirds(){
}
public HawaiiNativeForestBirds(String name, String scientificname,
String color, Integer population) {
super();
this.name = name;
this.scientificname = scientificname;
this.color = color;
this.population = population;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getScientificname() {
return scientificname;
}
public void setScientificname(String scientificname) {
this.scientificname = scientificname;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Integer getPopulation() {
return population;
}
public void setPopulation(Integer population) {
this.population = population;
}
public String toString() {
String output = name +" "+ scientificname + " "+ color +" "+ population;
return output;
}
}
Edit: If you want read a csv file then you cans solve it as below:
Assuming csv file contains data in following format
puaiohi,myadestes palmeri,brown,125
puaiohi,magumma parva,yellow,2000
I have modified Testing class to read the csv file
public class Testing {
public static void main(String[] args) {
String csvFile = "birds.csv";
String line = "";
String cvsSplitBy = ",";
List<HawaiiNativeForestBirds> listofBirds = new ArrayList<HawaiiNativeForestBirds>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
// use comma as separator
String[] bird = line.split(cvsSplitBy);
HawaiiNativeForestBirds Hawaiinbird= new HawaiiNativeForestBirds(bird[0],bird[1],bird[2],Integer.valueOf(bird[3]));
listofBirds.add(Hawaiinbird);
}
} catch (IOException e) {
e.printStackTrace();
}
// First display null values
HawaiiNativeForestBirds[] hbirds=new HawaiiNativeForestBirds[listofBirds.size()];
System.out.println("index " + "element ");
int i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird);
}
// Now display actual values
hbirds= listofBirds.toArray(new HawaiiNativeForestBirds[listofBirds.size()]);
System.out.println("index " + "name "+ "Scientific Name "+ "Color " + "Population ");
i=0;
for (HawaiiNativeForestBirds hbird:hbirds){
i++;
System.out.println(i+" "+hbird.toString());
}
}
}
Note: HawaiiNativeForestBirds class would remain as it is.
I read a text file using a linked list.
20 10 8
4.5 8.45 12.2
8.0 2.5 4.0
1.0 15.0 18.0
3.5 3.5 3.5
6.0 5.0 10.0
Each column represents, Length, Width and Height respectively.
When I read the text file, each row is treated as a single node.
I'm trying to see if there's a way to find the product of each row, the volume?
If it's not possible, then I need to find a way to call on the values read, individually(l,w,h) from another class in which I've created a method to getVolume().
Well here's my code so far: As always thank you in advance for all your help!
import java.util.LinkedList;
import java.util.*;
import java.io.*;
public class Runtime2 {
public static void main(String args[])throws Exception {
String content = new String();
int count=0;
File file = new File("dims.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
}
catch (Exception e) {
e.printStackTrace();
System.out.println();
}
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.print("Node " + count++ + ": ");
System.out.println(i.next());
}
public class Box {
double length;
double width;
double height;
Box(double l, double w, double h ) {
length=l;
width=w;
height=h;
}
double getVolume() {
double vol=length*width*height;
return vol;
}
boolean isCube() {
if(length==width && width==height) {
System.out.println("The box is a cube.");
}
else
System.out.println("The box is not a cube.");
return true;
}
}
private static double getVol(String line)
// line = "2 3 4.5"
String[] nums = line.split(" ");
int len = nums.length;
double vol = 1;
for (int i = 0 ; i < len; i++){
vol*=Double.parseDouble(nums[i]);
}
return vol;
Use nextDouble thrice for each line/row: Demo
double a, b, c;
while(sc.hasNextLine()){
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
Box box = new Box(a, b, c); //System.out.println(a + " " + b + " " + c + "\n");
System.out.println("Volm of box with dimension {" + a + "," + b + "," + c + "} is :" +
box.getVolume() + "\n");
}
You've done a good job of defining your Box class to encode each row of your file so far. The piece that you're missing is mapping from each line of your file to a Box object.
You can create a new Box object using the new operator: new Box(l, w, h).
The next step is to get the length, width, and height from a line within your file. You've already figured out how to get the line into a String variable. The next step is to use the String's split method to extract the values. For example:
String string = "a b c";
String[] values = string.split(" ");
// values[0] now contains "a";
// values[1] now contains "b";
// values[2] now contains "c";
Finally, use the List add method to append the new `Box to your list. I recommend structuring your code so that the file reading is encapsulated within its own method, so you might try something like this:
public class Runtime2 {
public static void main(String args[]) throws Exception {
List<Box> boxes = readBoxesFromFile(new File("dims.txt"));
for (int i = 0; i < boxes.size(); i++) {
System.out.println("Box " + i + " volume: "
+ boxes.get(i).getVolume());
}
}
private static List<Box> readBoxesFromFile(File file) {
List<Box> boxes = new LinkedList<Box>();
/*
* - Create File object
* - Create Scanner for File
* - For each line in the file
* Split the line into a string array
* Create a 'Box' instance
* Add the Box to your list
*/
return boxes;
}
}
I've omitted the imports, and the definition of the Box class for Brevity, but you've already got those defined within your question.
With that in mind, try putting these pieces together to construct your method for converting your file into a List of Box objects.
This chapter of the course is teaching us about methods in Java, more specifically returning values. While the rubric called for it to just be able to apply values from a .txt list the 9 planets provided below the program. I wanted to go beyond and make it so that there would be no limit on the amount of celestial bodies this could apply to (as I did with the program that created the .txt as an output). I have a finished program by another student available to me. However, I'd rather try approaching it in another way(Though I must thank Omar because I had no idea you could return arrays from methods).
Currently, as is, the program compiles without any errors in BlueJ. However, It does not run, or even put out any test print statements I put in. It's been running for over an hour on core 2 of my overclocked i5, but nothing. Since the core is being stressed, I assume it's stuck in a loop somehow?
How may I solve this issue?
I really appreciate any advice, and hope to spend more time here in the future.
/**
* 7.04 This program will take gravity and textual data from a .txt
* and will perform calculations with it once I figure out how that may be done.
*
*
* #author ********
* #version (The Date)
*/
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Weight2
{
// write static methods here
// Note: formula for finding weight on a planet: Earth weight divided by Gravity constant times surface gravity
public static String[] getData(int arraylength,int i, int value) {
String [] Gravityscan = new String[arraylength]; //Initiates String Arrays to be used
String [] pregravity = new String[arraylength];
String [] names = new String[arraylength];
String [] prevalues = new String[arraylength];
String [] error = {"error"};
String delims = "[ |\\ ]+"; // Sets Delimiters
File data2 = new File("Gravityoutput.txt"); //Opens data source
Scanner inFile = new Scanner("Gravityoutput.txt");
for(int m = 0; m < arraylength ; m++)
{
Gravityscan[m] = inFile.nextLine(); //String for each line being run
prevalues = Gravityscan[m].split(delims); //Split into two (gravity name)
pregravity[m] = prevalues[0]; //Sorts gravity string to array
names[m]= prevalues[1]; //Sorts name string to array
}
inFile.close();
//if (value == 0){return Integer.toString(arraylength);}
if (value == 1){return pregravity;} //Returns pregravity string for first part of loop below
else if (value == 2){return names;} //Returns names to end of for string below
else {System.out.print("AN ERROR HAS OCCURED IN METHOD GETDATA"); return error;}
}
//public static double calcWeight() {
//}
public static void main(String[] args)throws IOException
{
Scanner in = new Scanner(System.in);//Scanner activated
File data = new File("Gravityoutput.txt"); //Select file to get data from
Scanner inFile = new Scanner("Gravityoutput.txt");
int arraylength = 0; //Works with loop to determine length of data
while (inFile.hasNext())
{
arraylength++;
}
inFile.close(); //Closes file
System.out.print("arraylength is " + arraylength);//Beta testing check
double [] gravities = new double[arraylength]; //Declaring double array for after string conversion
//String[] names = new String[arraylength]; //Declaring array to be used for names
System.out.print("Please enter your mass on Earth in lbs: "); //User input for math
double earthWeight = in.nextDouble();
for(int i=0; i < arraylength; i++)
{
int value = 1;
String[] stringgravity = getData(arraylength, i, value);
gravities[i] = Double.parseDouble(stringgravity[i]);
System.out.print(gravities[i] + " gravity ");
value++;
String[] names = getData(arraylength, i, value);
System.out.println(names[i] + "gravity");
// static method you write Double.parseDouble
}
//double[] weight = calcWeight(earthWeight, gravity); // static method you write
//printResults(names, gravity, weight); // static method you write
} //end main
}//end class
//Below is the data contained by Gravityoutput.txt
3.70 Mercury
8.87 Venus
9.82 Earth
3.70 Mars
24.78 Jupiter
10.44 Saturn
8.86 Uranus
11.13 Neptune
0.61 Pluto
Creating an instance of Scanner with Scanner inFile = new Scanner("Gravityoutput.txt"); does not read input from the file, it reads input from the String "Gravityoutput.txt".
Try Scanner inFile = new Scanner(data); instead.
Oh, and your code is stuck in a loop :
inFile.hasNext() always returns true, since you never read anything from the Scanner.
You can replace it with
while (inFile.hasNext())
{
String str = inFile.next();
arraylength++;
}
I marked where I got the exception and I don't know why it's happening. This code finds the popularity and meaning of a name that the user types in . It also makes a graph(but it doesn't work)
The files are too long to put on here but on line examples are: names.txt:
Brenda f 0 0 0 0 917 42 14 13 40 115 123 172 426 (popularity), meanings.txt:
BRITTANY f English From the name of the region in the northwest of France, called in French Bretagne.(meaning)
1. Why am I getting this exception?
2. How do I fix the exception?
3. Why isn't my graph drawing the bars (in method changingGraph)
Example Console Output:
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.
Exception:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:864)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at BabyNames.changingGraph(BabyNames.java:131)
at BabyNames.main(BabyNames.java:32)
my code:
import java.util.*;
import java.io.*;
import java.awt.*;
public class BabyNames{
public static final int STARTINGYEAR = 1890;
public static final int WIDTH = 60;
public static final int HEIGHT = 30;
private static String nameFinal;
private static String originalName;
public static int HEIGHTOFPANEL = 500 + (HEIGHT * 2);
public static void main(String[] args) throws FileNotFoundException{
Scanner console = new Scanner(System.in);
DrawingPanel panel = new DrawingPanel(780,HEIGHTOFPANEL);//DOES PANEL SIZE CHANGE????!?!?!?!??!?!?!?
Graphics g = panel.getGraphics(); //does there always need to be 500 free in the middle???
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);
String nameFinal;
nameFinal = nameToLowerCase(console, originalName);//changes to correct capitalization
String meanings = "";
String popularity = "";
if(STARTINGYEAR == 1890){
popularity = findingStatistics(console,nameFile, nameFinal);
}
else{
popularity = findingStatistics(console, nameFile2, nameFinal);
}
meanings = findingStatistics(console, meaningsFile, nameFinal);
changingGraph(meanings,g,popularity); //EXCEPTION HERE
}
//prints introduction to what the program does
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" + STARTINGYEAR );
System.out.println();
System.out.print("Name: ");
}
//Converts what the user types in so the first letter is
//capitalized and the rest is lower case
public static String nameToLowerCase(Scanner console, String originalName){
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){
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{
}
}
if(goesThroughOnce == false){
System.out.print(originalName + " not found"); //ASK ABOUT THE EXCEPTION
}
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,HEIGHTOFPANEL-HEIGHT,780,HEIGHT);
g.setColor(Color.BLACK);
g.drawLine(0,HEIGHT,780,HEIGHT);
g.drawLine(0,HEIGHTOFPANEL-HEIGHT,780,HEIGHTOFPANEL-HEIGHT);
}
public static void changingGraph(String meanings, Graphics g, String popularity){
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),HEIGHTOFPANEL-8); //draws decade numbers
}
Scanner popularityData = new Scanner(popularity);
Scanner meaningsData = new Scanner(meanings);
String currChar = popularityData.next();
boolean gender = false; //if it is a boys name
boolean stop = false;
while(meaningsData.hasNext() && stop == false){//determines which color the bars will be
if(currChar.equals("f")){
gender = true;
}
if(gender == true){
g.setColor(Color.PINK);
stop = true;
}
else{
currChar = meaningsData.next();
}
}
if(stop ==false){
g.setColor(Color.BLUE);
}
int ranking;
while(popularityData.hasNext() && stop == false){ //EXCEPTION HERE
ranking = popularityData.nextInt();
for(int i=0; i<=amountOfDecades;i++){
g.fillRect(WIDTH*i,(ranking/2)+30,WIDTH/2,(560-HEIGHT*2)-((ranking/2)+30) );
g.drawString("" + ranking, WIDTH*i, (ranking/2)+30);
}
}
}
}
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.