3 Different Files Using Encapsulation (Data Hiding) - Object Creation Error

Mar 21, 2015

I have my code in 3 different files using encapsulation (Data hiding) and i have 1 problem at the very end of my code in my if and else statement (very bottom) when trying to call the classes from the other 2 documents. I will put the code in 1st document to 3rd document.

// FIRST DOCUMENT
public class CollegeCourse { //class name
//variables
String deptName;
int courseNum;
int credits = 3;
double fee;

[Code] ....

UPDATE: error message is

UseCourse.java:24: error: cannot find symbol
LabCourse lc = new LabCourse(department, course, Credits);
^
symbol: variable department
location: class UseCourse
UseCourse.java:24: error: cannot find symbol
LabCourse lc = new LabCourse(department, course, Credits);

[Code] ....

4 errors

View Replies


ADVERTISEMENT

Process 10000 XML Files / Verify And Insert Data Into Database - Java Heap Memory Error

Oct 12, 2013

I need to process 10000 xml files and verify and insert the data into database. I am loading all the files in the file object and iterating one by one. I am getting the memory issue. How to handle this?

View Replies View Related

How To Apportion Responsibilities And Organize Object Creation

Aug 15, 2014

I have a couple of objects, which I will call height and width. The latter may depend on the former and I access them through an interface:

interface Height
{
double getHeight();
}
interface Width
{
double getWidth( Height height );
}

I then have something I will call a RectangleMaker, which represents some set of rectangles that can be made. It takes a list of heights and widths and keeps track of which ones have been selected and which ones can still be made. For example, the possible heights might be 2 or 3 and the possible widths 3 or 4. It needs to determine if it can make a rectangle with a specific area and if selected to make that rectangle, disallow any other heights. So if I said, you are in charge of 2 x 3 rectangles, it could still potentially also make 2 x 4 rectangles, but 3 x 3 rectangles would no longer be an option. For the most part I think these details are irrelevant to my question, which is really about organization and assignment of responsibilities.

interface RectangleMaker
{
void setHeights( ArrayList<Height> );
void setWidths( ArrayList<Width> );
boolean isAreaAvailable( double Area );
void selectDimension( Height height, Width width );
Height listAllowedHeight();
ArrayList<Width> listAllowedWidths();
}

Now I have a new requirement. The lists of heights now need to be associated with a source, as do the widths. I should keep track of a list of RectangleMakers and pick the 'most appropriate' one for a particular area. The rule is to sort first on the height source and then on the width source and the first one able to handle the area, gets the job. So I created two enums heightSource and widthSource and had RectangleMaker implement Comparable, so I can make an ArrayList<RectangleMaker> and sort it based on the rules. Then I traverse the list and the first one that returns isAreaAvailable() true gets the job.

The final bit is that these sources also imply a specific set of Heights or Widths. How I get that set varies, it may be a fixed value or values, or might be read from a file. So in principle I could have:

ArrayList<Height> buildHeights( RectangleMaker.SOURCE source )
{
switch ( source )
{
}
}

and have a lot of specific code that builds each list by whatever method is appropriate. I still need to deal with the fact I might need additional information to build the lists. For example, one source might require a min, max and increment and another might require a file name. So I started working in the direction of more interfaces.

interface HeightList
{
ArrayList<Height> getHeights();
RectangleMaker.Source getSource();
}

I am not totally comfortable with my enum lists. They solve the sorting problem, but I am not exactly sure which class should define them. Right now they are defined by the RectangleMaker. I would need to update this class every time I added an implementation of HeightList or WidthList.

I was also thinking that since the list is built from a specific source, that source should be associated with the list. That would lead me to make this change:

interface RectangleMaker
{
void setHeights( HeightList heightList );
void setWidths( WidthList widthList );
boolean isAreaAvailable( double Area );
void selectDimension( Height height, Width width );
Height listAllowedHeight();
ArrayList<Width> listAllowedWidths();
}

It seems maybe there should be a factory in here somewhere, but this is where I am having trouble sorting out exactly who has what responsibility. I can do this sort of thing with my HeightList interface:

class SpacedHeight implements HeightList
{
int start;
int end;
int step;
ArrayList<Height> heights;
RectangleMaker.SOURCE source;

[Code] ....

Should I be thinking of putting one more layer over all of this? What complicates my thinking are two things: multiple instances may have the same source and some of these instances are dynamic. For example, two SpacedHeight instances may have different ranges, but they are both SpacedHeight and it doesn't matter which gets picked first. Exactly what SpacedHeight instances get created is determined by prompting the user for the values. If the heights come from a file, every instance would be associated with a different source and the file names would be hard-coded.

I think I want to make a HeightFactory and I think then it would make sense to move my enum definitions there. I see how I would do that if I could hard-code a specific instance of a HeightList with a specific enum. I am less clear on how to handle the case where the factory needs different parameters for different HeightList implementations.

View Replies View Related

Effect Of Hiding In Polymorphism

Aug 25, 2014

I have difficulty understanding the following behaviour.

class A {
public String string = "a";
public String toString() {
return string;
}
}

class B extends A {

[code]...

The output of the program is 'c'. This is expexted behaviour. But if class B is changed as follows,

class B extends A {
public String string = "b";
}

Now the program prints 'a' instead of 'c'. Why the statement: b.string = "c"; is not taken into account?

View Replies View Related

How Does Encapsulation Improve Maintainability

Jan 29, 2014

I understand making things private and using getters and setters to prevent corrupt data/valdiation. I am having trouble picturing a scenario where I can change my code without breaking others. What can I change without breaking existing code? One example I can think of is I can change an instance variable name since the getter for it will return it regardless. I am looking for a more vivid example...

View Replies View Related

JSP :: Selectively Showing And Hiding Buttons?

Sep 26, 2014

I am thinking of creating a quiz application and facing one problem.

On first question I don`t have to show previous button and on last question I don`t have to show next button.And for in between question I have to show both the buttons.
.
How can I do that in a JSP page.

View Replies View Related

Hiding User-drawn Graphics

Apr 15, 2014

I'm creating a game called Mouse Trap and I'm having an issue with a graphic drawn using AWT. Basically, when the mouse collides with the cheese, I want the cheese to disappear, or call (cheese[i].hide()). However, the cheese does not appear. hide() works for all other objects that inherit from PFigure, but the cheese will not. It's created a major issue in my game, and basically the only task left to accomplish.I believe my problem lies within Cheese.java, method draw(). For example, if I replace it with an example drawing, this problem goes away!:

public void draw() {
Graphics g = panel.getGraphics();
g.setColor(Color.blue);
g.drawOval(x + width / 4 , y + 1, width / 2, height / 2);

[Code] ....

I have three classes below that most likely involve the problem, feel free to ask if you need the others.PFigure.java (This class cannot be changed as a requirement to my project)

import java.awt.*;
 public abstract class PFigure implements Comparable {
protected int x, y; // Current position of the figure
protected int width, height; // Drawn (displayed) this size
protected int priority; // Can use to determine "winner"
protected Panel panel; // Panel the figure lives on

[code]....

View Replies View Related

Hiding Unsafe Methods Through Polymorphism

Feb 17, 2015

Recently I have been thinking of using additional interfaces in one of my libraries to hide certain "unsafe" methods of my classes from the user. I would like to get the opinion of other, more advanced java programmers on this issue.
What I do is something like the following (heavily simplified):

public interface ReadOnly {
public int getValue();
}
 public interface ReadWrite extends ReadOnly {
public void setValue(int value);

[Code] ....

The user would have access to the ExternalInterface. The ExternalInterface is controlling the values of the InternalComponent. The user can get the InternalComponent, but typecasted to a ReadOnly which does not expose the setters.

Now the thing is the user can still access the setValue method by typecasting the ReadOnly to an InternalComponent or to a ReadWrite, and that is not bad. If the user knows exactly what he/she is doing this will give him/her more flexibility and more power. But this way it *should* become obvious that this is not the intended use and perhaps the extra work of typecasting will discourage the user from doing this.

View Replies View Related

Does Encapsulation Mean That Variables By Default Need To Be Private

Apr 9, 2015

I just recently started learning about encapsulation, how to set variables private and only accessible to other classes through setters() and getters(). I've seen a couple of programming examples, perhaps not enough but some from here, and I sort of built the assumption that by default all variables need to be private. to make things more clear, here's a card dealer I made which simply

1- generates a fulll deck of 52 cards
2- lets user decide how many players, with 5 as Max number allowed as each player is dealt 10 cards.
3- deal cards

I approached this by making A deck , card , player and game class

import java.util.ArrayList;
public class Deck {
//an Object of this Class would generate a full deck ie an ArrayList of 52 Cards
private String[] suits={"Spades","Diamond","Clubs","Hearts"};
private int[] number={1,2,3,4,5,6,7,8,9,10,11,12,13};
ArrayList<Cards> deck= new ArrayList<Cards>();

[code]....

I can understand why for example Deck class's suit and number arrays are set to private , as they only need to be accessed by this class only. however, both the Deck class's deck arraylist and the Player class arraylist are not private, as I need to transfer these values from one to the other and it felt to me that setting them to private would make it more difficult to deal with them, but what I did instead is to set the Game class dealCard(), which is the only method that have access to them as private. does this achieve the same effect or do I need to set both of these arrayList to private?a follow up question, this is more related to the actual card dealer program, in this code

private void dealCards(){

for(int x = 0 ; x < playerCount ; x++){
for(int y = 0 ; y < 10; y++){
playerList.get(x).pile.add(deck.deck.get(0));
deck.deck.remove(0);
}
}
}

is there an API in ArrayList class that moves(adds to receiver and remove from giver) element across ArrayLists?

View Replies View Related

Encapsulation Hide Private Variable

Sep 10, 2014

As below code showing that you cannot directly access the private variable as i understood,  
 
public class EncapsulationDemo{   private int ssn;  
private String empName;   private int empAge;   //Getter and Setter methods  
public int getEmpSSN(){   return ssn;   }  
public String getEmpName(){   return empName;  

[Code] .....

View Replies View Related

Error When Trying To Write Files?

Feb 16, 2015

I'm trying to write information into a file using PrintWriter. The program complies correctly but when it get's to the following part of the program, an error is given. "Exception in thread 'main' java.io.FileNotFoundException" What is wrong with it?

System.out.print("Enter the filename:");
filename = kb.nextLine();
PrintWriter outputFile = new PrintWriter(filename);
outputFile.println(balance);
outputFile.print(item1+" "+item1Price);
outputFile.println(" "+item1Quantity);
outputFile.print(item2+" "+item2Price);
outputFile.println(" "+item2Quantity);
outputFile.print(item3+" "+item3Price);
outputFile.println(" "+item3Quantity);
outputFile.close();
System.out.println("Data written to the file.");

View Replies View Related

Encapsulation - Protected Attributes Should Be Visible To Child Classes

Jun 7, 2013

I found the following inheritance and encapsulation issue . Suppose you have a parent class with a non-static protected attribute.

package package1;
public class Parent{
protected int a = 10; // this is the non-static protected attribute in question
public static void main(String args[]){
// whatever logic
}// end Parent class
}// end main()

Now suppose you have a child class in another package and you have imported in the parent class.

package package2;
import package1.Parent;
public class Child extends Parent{
public static void main(String[] args){
Parent p = new Parent();
Child c = new Child();

System.out.println(p.a); //should print out 10 BUT DOES NOT
System.out.println(c.a); //should print out 10
}// end main()
}// end Child class

My observation is that p.a produces an error even though, to the best of my knowledge, it should not. I believe the statement "System.out.println(p.a);" should print out a 10.

Am I misunderstanding something about inheritance and encapsulation?

View Replies View Related

Parsing Data From Files?

Apr 5, 2014

I am suppose to display some information from some text files I tried to do that but the output gives me information from one text file and not information from all text files.

public static void main(String args[]) throws IOException {
String occupations;
double unemployRate_By_Occupations_2008;
double unemployRate_By_Occupations_2009;
double unemployRate_By_Occupations_2010;
//declare the file object and open the file "occupations.txt";
File myFile = new File("occupations.txt");

[code]....

The first text file is:

2.5
3.3
2.6
3.1
2.4
2.7
2.6

[code]....

the second text file is:

4.6
5.7
5.2
6.9
4.5
4.3

[code]....

The third text file is :

4.8
5.6
5.2
6.2
4.6
4.6
2.7

[code]....

Reason for edit:: Renamed title to be more descriptive, added code tags, and removed font formatting

View Replies View Related

Extract Data From Two Different Files?

Feb 13, 2015

how can I extract data from two different files but produce one output. For example, the first three columns are from text_file_1 and the last column (the last foruth column of the output) is from text_file_2.

View Replies View Related

Load Some Information From Previous Object Files And Add New Objects To Them Afterwards

Dec 17, 2014

I have a project in java that asks me to load some information from previous object files and add new objects to them afterwards. I created the files, but when I close the program and search for the previous information that should've been saved in the object file , it return nothing.

Here is the code.

Add method:

public boolean addUser (User u){
users[Ucount]=u;
Ucount++;
return true;
}

The save method:

public void saveUser (){
try{
FileOutputStream FOS = new FileOutputStream("User.txt", true);
ObjectOutputStream OOS = new ObjectOutputStream (FOS);

[Code] ....

The read method:

public void readUser (){
try{
FileInputStream FIS = new FileInputStream ("User.txt");
ObjectInputStream OIS = new ObjectInputStream (FIS);
for (int i=0;i<Ucount;i++){

[Code] ....

*Note: When I open the object file I could see that the information are actually there, so I think there's a problem with the read method I'm not sure what it is.

View Replies View Related

Storing Data Of Particular Class In Files

Jul 29, 2014

I need to store the data of a bunch of objects of a particular class in files in a predefined directory. Later, I want to get all the files from the directory and turn them into the objects again. Ideally, I'd like to have one file per object and have the files be human-readable and editable without too much difficulty. The class used by the objects will likely be subject to change in the future, as well. To keep things simple, all the data members are either primitives, Strings, or arrays of them. What is the best library/API to use to deal with this situation? Or should I write my own classes for these operations?

I read into serialization, but I read that it doesn't deal well with classes that are frequently modified. I also found articles on Preferences, but none of the ones I saw seem to explain how to best handle reading and writing to and from multiple objects, especially when I don't know a prior all the objects that were written to disk.

View Replies View Related

Read CSV Files And Organize Data In Java?

Apr 13, 2014

I am trying to write a program that read from a csv file called matches.csv.

A single football match can end with a win or a draw: in first case the winner team get 3 points and the loser none, in the second case of draw each of the two teams get 1 point.

For example, the first line of the file matches.txt is as follow:

In the file it contains the following data.

17/08/2013ArsenalAston Villa13
24/08/2013Aston VillaLiverpool01

This means that a match has been played on the 17/08/2013 where Arsenal scored 1 goal while Aston Villa 3 goals: thus Arsenal got 0 points while Aston Villa 3 points.

How can I structure my output to make it make it read

Position Team Played Points
1 Aston Villa 2 3
2 Liverpool 1 3
3 Arsenal 1 0

import java.io.File;

import java.io.FileNotFoundException;
import java.util.Scanner;
 public class Teams { 
public static void main(String[] args) {
String fileName = "matches.csv";
File file = new File(fileName);

[code]....

View Replies View Related

Read CSV Files And Organizing Data In Java

Apr 14, 2014

I am trying to write a program that read from a csv file called matches.csv.

A single football match can end with a win or a draw: in first case the winner team get 3 points and the loser none, in the second case of draw each of the two teams get 1 point.

For example, the first line of the file matches.txt is as follow:

In the file it contains the following data.

17/08/2013 Arsenal Aston Villa 1 3
24/08/2013 Aston Villa Liverpool 0 1

This means that a match has been played on the 17/08/2013 where Arsenal scored 1 goal while Aston Villa 3 goals: thus Arsenal got 0 points while Aston Villa 3 points.

How can I structure my output to make it make it read

Position Team Played Points

1 Aston Villa 2 3
2 Liverpool 1 3
3 Arsenal 1 0

Java Code:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Teams
{
public static void main(String[] args)
{
String fileName = "matches.csv";

[Code] ....

View Replies View Related

Networking :: Error While Sending Files Between Two Systems Using Socket

Mar 11, 2014

I've been trying to send a file(text & image files) from one system to another. somewhat I did, but file is not send originally in destination system. It shows AccessDeniedException on the destination system. What should do to avoid this exception.

View Replies View Related

Create Individual XML Files From Parsed Data Output Of XML File?

Feb 26, 2015

I have written a program (DOM Parser) that parses data from a XMl File. I would like to create an individual file with the corresponding name for each set of data parsed from the xml document. If the parsed output is Single, Double, Triple, I would like to create an individual xml file (Single.xml, Double.xml, Triple.xml)with those corresponding names. How do I create the xml files and give each file the name of my parsed data output?

import java.io.IOException; 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;

[code]....

View Replies View Related

Application Web Java To Insert Data Into Database Oracle From XML Files

Oct 27, 2014

I want to create an application wich can handle xml files ( display xml files's data on a html page) + insert those data into an oracle database.

I'm new to that, it a project for my internship. wich API is the most appropriate for that ( Jdom or Xstream or other), wich framework i can use ( there is only 3 IHM : connexion, upload file, display data, confirmation insertion data)?

View Replies View Related

How To Create Individual XML Files From Parsed Data Output Of XML File

Feb 26, 2015

I have written a program (DOM Parser) that parses data from a XMl File. I would like to create an individual file with the corresponding name for each set of data parsed from the xml document. If the parsed output is Single, Double, Triple, I would like to create an individual xml file (Single.xml, Double.xml, Triple.xml)with those corresponding names. How do I create the xml files and give each file the name of my parsed data output? 
 
import java.io.IOException;import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;import org.w3c.dom.Element;

[Code] ....

View Replies View Related

Reading Multiple Text Files From A Folder - Cannot Resolve Syntax Error

Apr 29, 2015

In the current program I am trying to read multiple text files from a folder. I keep getting the following syntax error

"Syntax error on token ";", { expected after this token".

I highlighted the line where im getting this error in red.
 
import java.io.*;
import java.util.*;
 public class CacheData {
  // Directory path here
    String path = "C:myfiles*.txt";
 
[Code] ....

View Replies View Related

ArrayList Only Adding 1 Item Even Though There Are Multiple Items (Setting Data To Files)

Oct 25, 2014

I managed to retrieve data, and set data in my own ways in which I like. But my problem is, if the file does not contain anything (fully empty), when I try to use my

set("", "");

method, it only sets the last one that is called.

Example:

set("section1", "section1Item");
set("section2", "section2Item");
set("section3", "section3Item");

Only section3 would get set, and not the others.

Otherwise, if the file contained a section already, then each section (section1, section2, section3) would get set.

Here's how I set the data to the file:

public static void set(String section, String data) {
files.openFileWriter();
files.file.delete();
reCreateFile();
String beforeItem = section + ":" + files.dataList.get(section);

[code]....

And here is how a retrieve the data and set them to my arraylist/hashmap:

public void getData() {
String line = null;
openFileReader();
StringBuffer sb = new StringBuffer();

[code]....

View Replies View Related

How To Cache Data Reading From Collection Of Text Files In A Directory Using TreeMap

May 4, 2015

How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap? Currently my program reads the data from several text files in a directory and the saves that information in a text file called output.txt. I would like to cache this data in order to use it later. How can I do this using the TreeMap Class? These are the keys,values: TreeMap The data I'd like to Cache is (date from the file, time of the file, current time).
 
import java.io.*; 
public class CacheData {
  public static void main(String[] args) throws IOException {
  String target_dir = "C:Files";
  String output = "C:Filesoutput.txt";
  File dir = new File(target_dir);
  File[] files = dir.listFiles();
 
 [Code] ....

View Replies View Related

Creating Object Of Inner Class - Getting Error

Aug 23, 2014

package home;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Box{
int x=70;
int y=70;

[Code] ....

L a = new L(); causing the error. It will be great to know why it is showing error.

View Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved