I have provided the background info:
So we have are working on a project of creating Facebook Lite. And in it we have this array profiles[idx]; idx is the index number, nop is the number of profiles. There is a switch case for choosing options from the menu; the professor wants us that, when the user exits the program, it should save their profiles (profile consists of first name, last name, friends, age) and when the program loads, the code should be able to load all the profiles. It's complicated.
Here's my read/write code which doesn't seem to work. First, it just makes a file which has stuff like "Profile#21bcffb5" this written. Instead of First Name:, Last Name: etc (elements inside the array). Also it doesn't load the profiles and my program gets stuck in an endless loop.
public void write()
{
try{
PrintStream writer = new PrintStream( new File("ProfileData.txt"));
for (int i=0; i<nop; i++){
writer.println(profiles[idx]);
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
public void read()
{
try {
Scanner s = new Scanner ( new File("ProfileData.txt"));
while(nop>0){
System.out.println(profiles[idx]);
}
}
catch(IOException e){
System.out.println(e);
}
}
It is printing the memory location at which Profile object is stored accessed by profiles[idx]. You should implement toString() method in Profile class which will print all the properties of the object
Related
so part of my program does is to create a card with a name. ill then check if the name exists in my dat file.
first, what i do is i read in my dat file and stores into an arraylist. then i implement a method to check if name exists. if not, then go ahead with creation.
but the thing is, after creation, i need to update my existing arraylist as my dat file has been updated with the newly added name.
what im thinking now is to clear my existing arraylist and then reading+store it again.
but i keep running into exceptions when i introduce the clear method. Here are my tested codes:
private ArrayList<Cards> cardList;
public void readGameCards()
{
cardList = new ArrayList<Cards>();
//clearCards(this.cardList); -> not sure where to add this
try // get data from dat file and store it into arraylist
{
Scanner myScanner = new Scanner(new File("GameCards.dat"));
while (myScanner.hasNextLine())
{
//converting codes
Cards c = new Cards(//para);
cardList.add(c);
}
myScanner.close();
}
catch (FileNotFoundException fe)
{
System.out.println("...");
}
}
public void clearCards(ArrayList<Cards> cardList)
{
if (!cardList.isEmpty())
{
cardList.clear();
//cardList = new ArrayList<Cards>();
}
}
it works fine for the first run, but on second run, the newly added name is not reflected in the arraylist.
My program currently has this working:
Bank bank = new Bank();
bank.openAccount(new CheckingAccount(10100, new Customer("First", "Last"),500.00,false));
bank.openAccount(new CheckingAccount(10101, new Customer("First", "Last"),2000.00,true));
bank.openAccount(new SavingsAccount(2010, new Customer("First", "Last"),5000.00,0.02));
Now I am trying to load this information from a file instead, but I ran into a bit of a wall. I want the new Customer information to include both the first and last name which are stored in separate index positions as separate variables, but while this will work:
new Customer[FIRST_INDEX],
I can't seem to get it to accept two index positions without creating a new Customer again. This is turn is causing issue with the method in Accounts where I'd like to keep the same format. How can I go about doing this?
public CheckingAccount(int accountNumber, Customer owner, double currentBalance, boolean freeChecks)
{
super(accountNumber, owner, currentBalance);
this.freeChecks = freeChecks;
}
Another problem I am running into is that the last index position can be one of two variables depending on if I am dealing with a checking account or a savings account:
private final static int FREE_CHECKS_INDEX = 4; // This loads a boolean
private final static int INTEREST_INDEX = 4; // This loads a double
Given this, I'm not entirely sure if my above approach would even work at all. The program is supposed to load either a Checking Account or Savings Account object, but since both types of accounts are stored in the same file I am wondering if I could read the last index position of each line of the text file before creating the object, but I'm not really sure how to go about doing that.
To be clear, I have this problem working perfectly without loading the data from the file, I am just unsure about the best approach for adapting it without having to rewrite all my other classes. Here's the new thing I am trying to do which I know isn't right:
protected static void loadAccountInformationFromFile() throws Exception
{
try ( Scanner fin = new Scanner(new File(INPUT_CUSTOMER_FILE)) )
{
String record;
String[] fields;
while ( fin.hasNext() )
{
record = fin.nextLine();
fields = record.split(",");
Bank bank = new Bank();
bank.openAccount
(
new CheckingAccount(Integer.parseInt(accountNumber[ACCOUNT_NUMBER_INDEX]),
new Customer[FIRST_INDEX, LAST_INDEX],
currentBalance[BALANCE_INDEX],
freeChecks[FREE_CHECKS_INDEX]
)
);
}
} catch (Exception e)
{
throw e;
} // end try
}
I'm writing a Restaurant Program.
When the user confirms his order, the order gets stored in an array of type order. Why? because when the user chooses to close the program, all orders get saved in a file with item's names and information about each item.
Also, every order object has an array of type item inside it!
Could you help me on how to write that file?
I know it'll be in the method processWindowEvent.
This is my try, i know that i should remove textArea.getText() but i don't know how to print all items, neither.
protected void processWindowEvent(WindowEvent e){
if (e.getID() == WindowEvent.WINDOW_CLOSING) {
JOptionPane.showMessageDialog(this,"All operation have been saved ");
try{
outFile=new File("Orderslist.txt");
out=new FileOutputStream(outFile);
ob=new PrintWriter(out);}
catch(IOException M){M.getMessage(); }
for(int i=0;i<o2.length;i++){
if(o2[i]!=null){
if(o2[i].getCount()<=4)
ob.println(o2[i].toString()+"\n--------------\n"+textArea.getText()+"--------------\n"+"\nTotal: "+o2[i].getTotalPrice());
else if(o2[i].getCount()>4)
ob.println(o2[i].toString()+"\n--------------\n"+textArea.getText()+"--------------\n"+"\nTotal Price#: "+o2[i].getTotalPrice()+"\n\nDiscount 20%\n\n--------------\nTotal price#: "+(o2[i].getTotalPrice()-(o2[i].getTotalPrice()*0.2)));
}
}
In the constructor of your Widnow add this:
public Window() {
this.addWindowListener(new WindowAdapter(){
#Override
public void windowClosing(WindowEvent arg0) {
writeFile(textArea.getText()); //Call your method
System.exit(0);
}
});
...
}
For writing the file:
File file = new File("myFile.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Texto to write");
bw.close();
After ob.println() do ob.close(); or ob.flush();.
If you dont close the stream or flush the stream , nothing will be printed in your file.
Really this isn't the best design, you should write changes to the file immediately as they are made. The reason for this is that if the application closes for any other reason (power cut, task manager kill, crash, etc) then you don't want to lose the user's data. It would also be worth automatically backing up that file (for example copying it after startup) so if you corrupt the current session somehow you can revert.
To actually implement the saving you want to use a FileOutputStream of some sort but the exact implementation will vary a lot depending on the format that you want the data inside the stream. For example XML, JSON, plan text, binary serialization etc are all fairly easy but you need to pick one :)
please, could anyone tell me, how can i check if file exists on URL where is only FTP protocol? Im using this code:
public boolean exists(String URLName) throws IOException {
input = null;
boolean result = false;
try {
input = new URL(URLName).openStream();
System.out.println("SUCCESS");
result = true;
} catch (Exception e) {
System.out.println("FAIL");
} finally {
if (input != null) {
input.close();
input = null;
}
}
return result;
}
It doesnt work when i send there more then one or two, it just sais
sun.net.ftp.FtpProtocolException: Welcome message: 421 Too many connections (2) from this IP
at sun.net.ftp.FtpClient.openServer(FtpClient.java:490)
at sun.net.ftp.FtpClient.openServer(FtpClient.java:475)
at sun.net.www.protocol.ftp.FtpURLConnection.connect(FtpURLConnection.java:270)
at sun.net.www.protocol.ftp.FtpURLConnection.getInputStream(FtpURLConnection.java:352)
at java.net.URL.openStream(URL.java:1010)
at bibparsing.PDFImage.exists(PDFImage.java:168)
at bibparsing.PDFImage.main(PDFImage.java:189)
It works great when the protocol is HTTP. I mean adresses like:
ftp://cmp.felk.cvut.cz/pub/cmp/articles/chum/Chum-TR-2001-27.pdf
ftp://cmp.felk.cvut.cz/pub/cmp/articles/martinec/Kamberov-ISVC2006.pdf
and something like that
The problem here is that this method isn't thread safe; if two threads use this method simultaneously one can overwrite the instance variable named input, causing the other thread to not closing the connection it opened (and closing either nothing, or the connection opened by the other thread).
This is easily fixed, by making the input variable local:
InputStream input=null;
Code style: within a method, you can return the result as soon as you know it. Beginners often declare the variables first, then execute the logic and return the result at the end of the method. You can save a lot of code and complexity by
declaring variables as late as possible (when you first need them)
declaring as few variables as necessary (readability is always a good reason to add variables, but less variables means less complexity)
returning as soon as you know the result (reducing paths through your code, and thus reducing complexity)
The code can be simply written as:
public static boolean exists (String urlName) throws IOException {
try {
new URL(urlName).openStream().close();
return true;
} catch (IOException e) {
return false;
}
}
I used the following coding to display user accounts in my domain.But in that coding it display only first 100 records.But in my domain nearly 500 users account.I don't know what problem in this coding
import java.net.URL;
import java.util.List;
import com.google.gdata.client.appsforyourdomain.UserService;
import com.google.gdata.data.appsforyourdomain.provisioning.UserEntry;
import com.google.gdata.data.appsforyourdomain.provisioning.UserFeed;
public class Readuser {
public int i3;
public String rn[]=new String[100];
public void read(){
try
{
// Create a new Apps Provisioning service
UserService myService = new UserService("My Application");
myService.setUserCredentials(admin,password);
// Get a list of all entries
URL metafeedUrl = new URL("https://www.google.com/a/feeds/"+domain+"/user/2.0/");
System.out.println("Getting user entries...\n");
UserFeed resultFeed = myService.getFeed(metafeedUrl, UserFeed.class);
List<UserEntry> entries = resultFeed.getEntries();
for(i3=0; i3<entries.size(); i3++) {
UserEntry entry = entries.get(i3);
rn[i3]= entry.getTitle().getPlainText();
System.out.println(rn[i3]);
}
System.out.println("\nTotal Entries: "+entries.size());
}
catch(Exception e) { System.out.print(e);}
}
public static void main(String args[])
{
Readuser ru=new Readuser();
ru.read();
}
}
You only allocate 100 entries.
public String rn[]=new String[100];
Hint from your code : public String rn[]=new String[100];
Do you really need to have i3 and rn as class members ? Do you really need rn ? A List seems more comfortable as an Object than a String[].
There is no need for the string array (String[]).
Arrays are fixed size; and in this case you have allocated 100 "slots" for Strings, and when You try to assign a string to position 100 ( you know, the 101:th string) it fails.
You catch an exception in the end. Print the stack trace to find out whats going on
catch(Exception e) {
e.printStackTrace();
}
Learn to read it an find out what is says... However you should not catch the exception in this method. It is better to abort whatever the program was doing. Catch it in your main method - just printing or logging it is fine, so that you can correct the programming error.
Anyway; The result you get is a List of user entries. Lists are part of the (java.util)collections framework. Collections have a lot of features; in this case you want to iterate over all entries in the list. You can do this by using the iterator() method -read the javadoc...OR you can use for-loop syntactic sugar for doing this:
for( UserEntry user : entries ) {
// user is the current UserEntry
System.out.println(user.getTitle().getPlainText());
}
The variables i3 and rn are no good... They shouldn't be class variables, and if you need "temporary" variables, define them close to where you are going to use them.
As for naming of variables, a name like "entry" is less useful than "user". Actually a class called UserEntry should probably be called just User, but I don't know about this API, so...