how to put user`s input to save as a file and repen a file after that...

hi all..this problem confuse me a lot ...pls give me some suggustion to solve this problem...i got a run-time problem after i compier my code

*****

Please enter your CD`s title : ivan

Please enter your CD`s Artist/GroupName : jdd

Please enter your CD`s year of release : 2009

Please enter your CD`s MusicGenre(e.g.: Jazz, Blues, Funk, Classical, Rock, etc...) : rock

Please enter your CD`s comment : jfjfw

Do you have another Cd ? (Y/N) : n

Saving to file

Exception in thread "main" java.lang.NullPointerException

at Demo.saveDate(Demo.java:48)

at Demo.readDataFromConsole(Demo.java:126)

at Demo.main(Demo.java:197)

>Exit code: 1

import java.util.ArrayList;

import java.io.*;

publicclass Demo{

readOperation theRo =new readOperation();

errorCheckingOperation theEco =new errorCheckingOperation();

ArrayList<MusicCd> MusicCdList;

public Demo()

{

}

privatevoid heading()

{

System.out.println("\tTesting read data from console, save to file, reopen that file\t");

}

privatevoid saveDate()

{

try

{

File f =new File("jessica.txt");

FileOutputStream fos =new FileOutputStream(f);

ObjectOutputStream oos =new ObjectOutputStream(fos);

oos.writeObject(new Integer(MusicCdList.size()));

for( MusicCd s : MusicCdList)

oos.writeObject(s);

oos.close();

}

catch (IOException ioe)

{

ioe.printStackTrace();

}

}

privatevoid loadDate()

{

MusicCdList =new ArrayList<MusicCd>( );

try

{

File g =new File("jessica.txt");

FileInputStream fis =new FileInputStream(g);

ObjectInputStream ois =new ObjectInputStream(fis);

ArrayList<String> stuff = (ArrayList<String>)ois.readObject();

for( String s : stuff ) System.out.println(s);

ois.close();

}catch (Exception ioe)

{

ioe.printStackTrace();

}

}

privatevoid readDataFromConsole()

//private void insertCd()

{

ArrayList<MusicCd> MusicCdList =new ArrayList<MusicCd>( );

readOperation theRo =new readOperation();

errorCheckingOperation theEco =new errorCheckingOperation();

MusicCd theCd;

String muiseCdsTitle;

String muiseCdsArtistOrGroupName;

int muiseCdsYearOfRelease;

int validMuiseCdsYearOfRelease;

String muiseCdsMusicGenre;

String muiseCdsAComment;

while(true)

{

String continueInsertCd ="Y";

do

{

muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");

muiseCdsArtistOrGroupName = theRo.readString("Please enter your CD`s Artist/GroupName : ");

muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");

validMuiseCdsYearOfRelease = theEco.errorCheckingInteger(muiseCdsYearOfRelease, 1000, 9999);

muiseCdsMusicGenre = theRo.readString("Please enter your CD`s MusicGenre(e.g.: Jazz, Blues, Funk, Classical, Rock, etc...) : ");

muiseCdsAComment = theRo.readString("Please enter your CD`s comment : ");

MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsArtistOrGroupName, validMuiseCdsYearOfRelease ,

muiseCdsMusicGenre, muiseCdsAComment));

MusicCdList.trimToSize();

//saveToFile(MusicCdList);

continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");

}while(continueInsertCd.equals("Y") || continueInsertCd.equals("y") );

if(continueInsertCd.equals("N") || continueInsertCd.equals("n"));

{

System.out.println("Saving to file ");

//MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));

saveDate();

loadDate();

break;

}

}

}

publicstaticvoid main(String[] args)

{

Demo one =new Demo();

one.readDataFromConsole();

}

}

The following code for better understnd of what i did

import java.util.*;

publicclass readOperation{

public String readString(String userInstruction)

{

String aString =null;

try

{

Scanner scan =new Scanner(System.in);

System.out.print(userInstruction);

aString = scan.nextLine();

}

catch (NoSuchElementException e)

{

//if no line was found

System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);

}

catch (IllegalStateException e)

{

// if this scanner is closed

System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);

}

return aString;

}

publicchar readTheFirstChar(String userInstruction)

{

char aChar =' ';

String strSelection =null;

try

{

//char charSelection;

Scanner scan =new Scanner(System.in);

System.out.print(userInstruction);

strSelection = scan.next();

aChar = strSelection.charAt(0);

}

catch (NoSuchElementException e)

{

//if no line was found

System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);

}

catch (IllegalStateException e)

{

// if this scanner is closed

System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);

}

return aChar;

}

publicint readInt(String userInstruction){

int aInt = 0;

try{

Scanner scan =new Scanner(System.in);

System.out.print(userInstruction);

aInt = scan.nextInt();

}catch (InputMismatchException e){

System.out.println("\nInputMismatchException error occurred (the next token does not match the Integer regular expression, or is out of range) " + e);

}catch (NoSuchElementException e){

System.out.println("\nNoSuchElementException error occurred (input is exhausted)" + e);

}catch (IllegalStateException e){

System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);

}

return aInt;

}

}

import java.io.Serializable;

publicclass MusicCdimplements Serializable

{

private String musicCdsTitle;// CD`s title

private String artistOrGroupName;// CD`s artist/GroupName,

privateint yearOfRelease;//CD`s yearOfRelease

private String musicGenre;//Cd`s music genre

private String aComment;

public MusicCd()

{

musicCdsTitle ="None";

artistOrGroupName ="None";

yearOfRelease = 1000;

musicGenre ="None";

aComment ="None";

}

public MusicCd(String newMusicCdsTitle, String newArtistOrGroupName,int newYearOfRelease,

String newMusicGenre, String aNewComment)

{

musicCdsTitle = newMusicCdsTitle;

artistOrGroupName = newArtistOrGroupName;

/*

if((newYearOfRelease >= 1000) && (newYearOfRelease <= 9999))

{

yearOfRelease = newYearOfRelease;

}

else

{

System.out.println("Invalid years..Try again!!");

// System.exit(0);

return;

}

*/

yearOfRelease = newYearOfRelease;

musicGenre = newMusicGenre;

aComment = aNewComment;

}

public String getTitle()

{

return musicCdsTitle;

}

public String getArtistOrGroupName()

{

return artistOrGroupName;

}

publicint getYearOfRelease()

{

return yearOfRelease;

}

public String getMusicGenre()

{

return musicGenre;

}

public String getAComment()

{

return aComment;

}

publicvoid setTitle(String newMusicCdsTitle)

{

musicCdsTitle = newMusicCdsTitle;

}

publicvoid setArtistOrGroupName(String newArtistOrGroupName)

{

artistOrGroupName = newArtistOrGroupName;

}

publicvoid setYearOfRelease(int newYearOfRelease)

{

yearOfRelease = newYearOfRelease;

}

publicvoid setMusicGenre(String newMusicGenre)

{

musicGenre = newMusicGenre;

}

publicvoid setAComment(String aNewComment)

{

aComment = aNewComment;

}

/*

public boolean equalsName(MusicCd otherCd)

{

if(otherCd == null)

return false;

else

return (musicCdsTitle.equals(otherCd.musicCdsTitle));

}

*/

public String toString()

{

return("Title: " + musicCdsTitle +"\t"

+"Artist/GroupName: " + artistOrGroupName +"\t"

+"Year of release: " + yearOfRelease +"\t"

+"Music Genre: " + musicGenre +"\t"

+"Comment: " + aComment +"\t" );

}

}

import java.util.Scanner;

import java.util.InputMismatchException;

import java.util.NoSuchElementException;

publicclass errorCheckingOperation

{

publicint errorCheckingInteger(int checkThing,int lowerBound,int upperBound)

{

int aInt = checkThing;

try

{

while((checkThing < lowerBound ) || (checkThing > upperBound) )

thrownew Exception("Invaild value....Please enter the value between " + lowerBound +" & " + upperBound );

}

catch (Exception e)

{

String message = e.getMessage();

System.out.println(message);

}

return aInt;

}

publicint errorCheckingSelectionValue(String userInstruction)

{

int validSelectionValue = 0;

try

{

int selectionValue;

Scanner scan =new Scanner(System.in);

System.out.print(userInstruction);

selectionValue = scan.nextInt();

validSelectionValue = errorCheckingInteger(selectionValue , 1, 5);

}

catch (NoSuchElementException e)

{

//if no line was found

System.out.println("\nNoSuchElementException error occurred (no line was found) " + e);

}

catch (IllegalStateException e)

{

// if this scanner is closed

System.out.println("\nIllegalStateException error occurred (scanner is closed)" + e);

}

return validSelectionValue;

}

}

[18876 byte] By [Ivan1238a] at [2007-11-27 5:42:07]
# 1

Step one: find out what line raised the runtime error:

Exception in thread "main" java.lang.NullPointerException

at Demo.saveDate(Demo.java:48)

Line 48 isoos.writeObject(new Integer(MusicCdList.size()));

Step two: find out which reference is null. Since oos is initialized on the previous line, it must be the case that MusicCdList is null.

Step three: find the crack in the logic. You are assuming this field is non-null,

so you must think you've initialized it earlier, but made a mistake in doing so.

A quick look through you code shows this line, in method readDataFromConsole:

ArrayList<MusicCd> MusicCdList = new ArrayList<MusicCd>( );

Note that MusicCdList is a *local* variable, not a field here. The fix:

MusicCdList = new ArrayList<MusicCd>( );

Do you see the steps taken to solve these simple sorts of bugs?

Hippolytea at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 2
thx you for your advice....but i am still stunk on that problem...i `ve tested more than 50 times before i post here....pls give me more directions on that..thank a million...
Ivan1238a at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 3
ArrayList<MusicCd> MusicCdList; public Demo(){MusicCdList = new ArrayList<MusicCd> ();}
AnanSmritia at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 4

> thx you for your advice....but i am still stunk on

> that problem...i `ve tested more than 50 times before

> i post here....pls give me more directions on

> that..thank a million...

I made the change I pointed out, and that got rid of the NullPointerException.

That's the good news. The bad news is that it blows up at another

runtime error, but are you saying that you changed the line to

MusicCdList = new ArrayList<MusicCd>( );

and you still get the same NullPointerException?

Hippolytea at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 5

There are many errors in the Demo Class.

Try this :

import java.util.ArrayList;

import java.io.*;

public class Demo {

readOperation theRo = new readOperation();

errorCheckingOperation theEco = new errorCheckingOperation();

ArrayList<MusicCd> MusicCdList;

public Demo() {

}

private void heading() {

System.out.println("\tTesting read data from console, save to file, reopen that file\t");

}

private void saveDate() {

try {

File f = new File("jessica.txt");

FileOutputStream fos = new FileOutputStream(f);

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(new Integer(MusicCdList.size()));

oos.writeObject(MusicCdList);///////////////CHANGE HERE

oos.close();

} catch (IOException ioe) {

ioe.printStackTrace();

}

}

private void loadDate() {

MusicCdList = new ArrayList<MusicCd>();

try {

File g = new File("jessica.txt");

FileInputStream fis = new FileInputStream(g);

ObjectInputStream ois = new ObjectInputStream(fis);

//first : list size (Integer)

Integer i = (Integer)ois.readObject(); ///////////////CHANGE HERE

System.out.println("List size = "+i);

//second

ArrayList<MusicCd> stuff = (ArrayList<MusicCd>) ois.readObject();

for (MusicCd s : stuff)

System.out.println(s.getTitle());

ois.close();

} catch (Exception ioe) {

ioe.printStackTrace();

}

}

private void readDataFromConsole()

// private void insertCd()

{

MusicCdList = new ArrayList<MusicCd>();///////////////CHANGE HERE

readOperation theRo = new readOperation();

errorCheckingOperation theEco = new errorCheckingOperation();

MusicCd theCd;

String muiseCdsTitle;

String muiseCdsArtistOrGroupName;

int muiseCdsYearOfRelease;

int validMuiseCdsYearOfRelease;

String muiseCdsMusicGenre;

String muiseCdsAComment;

while (true) {

String continueInsertCd = "Y";

do {

muiseCdsTitle = theRo.readString("Please enter your CD`s title : ");

muiseCdsArtistOrGroupName = theRo.readString("Please enter your CD`s Artist/GroupName : ");

muiseCdsYearOfRelease = theRo.readInt("Please enter your CD`s year of release : ");

validMuiseCdsYearOfRelease = theEco.errorCheckingInteger(muiseCdsYearOfRelease, 1000, 9999);

muiseCdsMusicGenre = theRo.readString("Please enter your CD`s MusicGenre(e.g.: Jazz, Blues, Funk, Classical, Rock, etc...) : ");

muiseCdsAComment = theRo.readString("Please enter your CD`s comment : ");

MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsArtistOrGroupName, validMuiseCdsYearOfRelease, muiseCdsMusicGenre, muiseCdsAComment));

MusicCdList.trimToSize();

// saveToFile(MusicCdList);

continueInsertCd = theRo.readString("Do you have another Cd ? (Y/N) : ");

} while (continueInsertCd.equals("Y") || continueInsertCd.equals("y"));

if (continueInsertCd.equals("N") || continueInsertCd.equals("n"))

;

{

System.out.println("Saving to file ");

// MusicCdList.add(new MusicCd(muiseCdsTitle, muiseCdsYearOfRelease));

saveDate();

loadDate();

break;

}

}

}

public static void main(String[] args) {

Demo one = new Demo();

one.readDataFromConsole();

}

}

See comments (//CHANGE HERE)

Hope That Helps

java_2006a at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 6
thx you for u guy `s help.....it does help me a lot .thx a milllon....could i ask one more question on this....how do i make a function that if the user have enter the same cd`s title ..then my program don`t let them to be insert to the arrayList...thx
Ivan1238a at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 7

The usual way one avoid duplication is to employ a data structure designed

with the appropriate notion of uniqueness. For example:

1. In a java.util.Set, elements are unique.

2. In a java.util.Map, keys are unique.

If you haven't already, take the collections tutorial: http://java.sun.com/docs/books/tutorial/collections/index.html

Hippolytea at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 8
thx for your suggestion...i learned that idea before...but i am wondering how do i implemented the funtion that there is no Cd inserting if there is that cd in the arrayList.. (none of the cd to be inserted have the same Cd`s title )..pls help....
Ivan1238a at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 9
> thx you for u guy `s help.....it does help me a lot> .thx a milllon....... ...-- -.-- -.- . -.-- -... .- .-. -.... ...... - ..- -.-. -.-!
cotton.ma at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 10

It would go something like this

public boolean checkForDuplicate(ArrayList array, MusicCD newCD) {

boolean found = false;

for(int i = 0; i < array.size; i++){

MusicCD cd = array.get(i);

if(cd.getName.equals(newCD.getName())){

found = true;

}

}

return found;

}

You might want to make your MusicCD class an equals method, because obviously you could have two seperate cd's with the same name.

RedUnderTheBeda at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...
# 11

> > thx you for u guy `s help.....it does help me a

> lot

> > .thx a milllon....

>

> ... ...

>

> -- -.--

> -.- . -.-- -... .- .-. -..

> .. ...

> ... - ..- -.-. -.-

> !

LOL! I can't believe I went here to translate that: http://webnet77.com/cgi-bin/helpers/morse.pl

Hippolytea at 2007-7-12 15:20:20 > top of Java-index,Java Essentials,Java Programming...