Error:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:0 - java

I get this error when running my code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Module11_13_RealWorldProblem.main(Module11_13_RealWorldProblem.java:194)
I am not sure how to fix it. I have a text doc that it should read for the information, but its not running.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class User
{
private final String id;
private final String lstName;
private final String FstName;
private final String addressLine1;
String addressLine2;
private final String City;
private final String State;
private final long zip;
long zipPlus4;
private final double payAmount;
private final String payDate;
private final double payDue;
public User(String id,String lstName,String fstName,
String addressLine1,String addressLine2,String City,
String State,long zip,long zipPlus4,
String payDate,double payAmount,double payDue)
{
this.id=id;
this.lstName=lstName;
this.FstName=fstName;
this.addressLine1=addressLine1;
this.addressLine2=addressLine2;
this.City=City;
this.State=State;
this.zip=zip;
this.zipPlus4=zipPlus4;
this.payAmount=payAmount;
this.payDate=payDate;
this.payDue=payDue;
}
public void setAddLine2(String add){
this.addressLine2=add;}
public void setZipPlus4(long zip){
this.zipPlus4=zip;}
public long getZip()
{
return zip;
}
public double getPayAMount()
{
return payAmount;
}
public double getDueAMount()
{
return payDue;
}
public String getDate()
{
return payDate;
}
public String getaddressLine1()
{
return addressLine1;
}
public String getaddressLine2()
{
return addressLine2;
}
public String getCity()
{
return City;
}
public String getState()
{
return State;
}
public String getlstName()
{
return lstName;
}
public String getId()
{
return id;
}
public String getfstName()
{
return FstName;
}
public long getZipPlus4(){
return zipPlus4;}
}
public class Module11_13_RealWorldProblem {
public static void main(String[] args){
List<User> lst=new ArrayList<User>();
Scanner in=new Scanner(System.in);
File file = new File(args[0]);
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
List<String> allLines = Files.readAllLines(Paths.get(args[0]));
for (String line : allLines) {
//System.out.println(line);
String[] str=line.split("\\^");
User user=new User(str[0],str[1],str[2],
str[3],"".equals(str[4])?"NoValue":str[4],str[5],str[6],
Long.valueOf(str[7]),"".equals(str[8])?Long.MAX_VALUE:Long.valueOf(str[8]),
str[9],Double.valueOf(str[10]),Double.valueOf(str[11]));
lst.add(user);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Do opertauiosn,");
System.out.println("Do you want to output the report to the screen ('S'), to a file ('F') or both ('B')");
String ch=in.nextLine();
StringBuilder sb=new StringBuilder();
for (User user : lst) {
sb.append(user.getId()+"^"+user.getlstName()+","+user.getfstName()+"^"+user.getaddressLine1()
+"^"+("NoValue".equals(user.getaddressLine2())?"":user.getaddressLine2())+"^"+user.getCity()+"^"+user.getState()+"^"+user.getZip()+"^"+(
Long.MAX_VALUE==user.getZipPlus4()?"":user.getZipPlus4())
+"^"+user.getPayAMount()+"^"+user.getPayAMount()+"^"+user.getDueAMount());
sb.append("\n");
}
if("S".equalsIgnoreCase(ch))
{
System.out.println(sb.toString());
}
else if("F".equalsIgnoreCase(ch))
{
System.out.println("Enter output file name with full path");
String outputFilename=in.nextLine();
log(sb.toString(),outputFilename);
System.out.println("File successfully written");
}
else if("B".equalsIgnoreCase(ch))
{
System.out.println(sb.toString());
System.out.println("Enter output file name with full path");
String outputFilename=in.nextLine();
log(sb.toString(),outputFilename);
System.out.println("File successfully written");
}
}
public static void log(String message,String fName){
try {
PrintWriter out = new PrintWriter(new FileWriter(fName, true), true);
out.write(message);
out.close();
} catch (Exception e) {
System.out.print("There is something wrong in output file/file path..retry !");
}
}
}
When producing the report
Skip those fields that are not part of the report format
Rearrange those fields that are in a different order so they correspond to the report format
Add a prompt to the user "Do you want to output the report to the screen ('S'), to a file ('F') or both ('B')".
If the user enters 'S' your code should display the report to the screen as it currently does.
Whether the user enters an uppercase or lowercase letter should not matter. For example 'S' or 's' should not matter. In both cases, the user should display the data as described above.
If the user enters "F" (or "f"), then the app should
Prompt the user for the desired file name (including the file path)
Output the report to a file using the file name / path the user entered. This output should be in the exact same format as the report is-if sent to the screen except that it outputs the report to a file.
If the user enters "B" (or "b"), then the app should output the report to both the screen and output it to a file.

The Program expects a input from command line while running the program.
File file = new File(args[0]);
args being a empty array, throwing an indexOutOfBoundException.
Make sure while running the program you are passing the file name.

Related

I am trying to open my text file but I do not know what the issue is

I am trying to make a program that takes in a students id number, first and last name along with their class grade. After I want to be able to read the data. But I am getting an error when I try to read the data ( or open the file). When I run the program I get "Error opening file". I have 5 classes and will attach them. Could someone try to help me out and find out what is wrong. I will attach the classes:
public class StudentRecords
{
private int IDnumber;
private String firstName;
private String lastName;
private double grade;
public StudentRecords()
{
this( 0, "", "", 0.0);
}
public StudentRecords( int id, String first, String last, double gr )
{
setIDnumber( id );
setFirstName( first);
setLastName( last );
setGrade( gr );
}
public void setIDnumber( int id)
{
IDnumber = id;
}
public int getIDnumber()
{
return IDnumber;
}
public void setFirstName( String first )
{
firstName = first;
}
public String getFirstName()
}
return firstName;
}
public void setLastName( String last)
{
lastName = last;
}
public String getLastName()
{
return lastName;
}
public void setGrade( double gr)
{
grade = gr;
}
public double getGrade()
{
return grade;
}
}
Here is the second class
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.Formatter;
import java.util.FormatterClosedException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class StudentTextFile
{
private Formatter output;
public void openFile()
{
try
{
output = new Formatter( "students.txt");
}
catch ( SecurityException securityException )
{
System.err.println(
"You do not have write access to this file.");
System.exit(1);
}
catch ( FileNotFoundException fileNotFoundException )
{
System.err.println( "Error opening or creating file." );
System.exit(1);
}
}
public void addStudentRecords()
{
StudentRecords record = new StudentRecords();
Scanner input = new Scanner( System.in);
System.out.printf("%s\n%s\n%s\n%s\n\n",
"To terminate input, type the end-of-file indicator",
"when you are prompted to enter input.",
"On UNIX/Linux/Mac OS X type <ctrl> d then press Enter",
"On Windows type <crtl> z then press enter");
System.out.printf( "%s\n%s",
"Enter student ID number (> 0), first name, last name and grade. ",
"? ");
while ( input.hasNext() )
{
try
{
record.setIDnumber( input.nextInt());
record.setFirstName( input.next());
record.setLastName(input.next());
record.setGrade( input.nextDouble());
if ( record.getIDnumber() > 0 )
{
output.format( "%d %s %s %.2f\n", record.getIDnumber(),
record.getFirstName(), record.getLastName(),
record.getGrade() );
}
else
{
System.out.println(
"Student ID Number must be greater than 0.");
}
}
catch ( FormatterClosedException formatterClosedException)
{
System.err.println( "Error writing to file.");
return;
}
catch ( NoSuchElementException elementException)
{
System.err.println( "Invalid input. Please try again.");
input.nextLine();
}
System.out.printf( "%s %s \n%s", "Enter student ID number (>0),",
"first name. last name and grade.", "? ");
}
}
public void closeFile()
{
if ( output != null )
output.close();
}
}
Here is the third class
public class StudentTextFileTest {
public static void main(String[] args)
{
StudentTextFile application = new StudentTextFile();
application.openFile();
application.addStudentRecords();
application.closeFile();
}
}
Here is the fourth class
import java.io.File;
import java.io.FileNotFoundException;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class ReadStudentTextFile
{
private Scanner input;
public void openfile()
{
try
{
input = new Scanner( new File( "studentrecords.txt"));
}
catch ( FileNotFoundException fileNotFoundException )
{
System.err.println( "Error opening file.");
System.exit(1);
}
}
public void readStudentRecords()
{
StudentRecords record = new StudentRecords();
System.out.printf( "%-10s%-12s%-12s%10s\n", "Student ID Number",
"First Name", "Last Name", "Balance");
try
{
while ( input.hasNext())
{
record.setIDnumber( input.nextInt());
record.setFirstName( input.next() );
record.setLastName( input.next());
record.setGrade( input.nextDouble());
System.out.printf( "%-10d%-12s%-12s%10.2f\n",
record.getIDnumber(), record.getFirstName(),
record.getLastName(), record.getGrade() );
}
}
catch ( NoSuchElementException elementException )
{
System.err.println( "File improperly formed. ");
input.close();
System.exit(1);
}
catch ( IllegalStateException stateException)
{
System.err.println(" Error reading from file.");
System.exit(1);
}
}
public void closeFile()
{
if (input!= null )
input.close();
}
}
Here is the fifth class
public class ReadStudentTextFileTest
{
public static void main(String[] args)
{
ReadStudentTextFile application = new ReadStudentTextFile();
application.openfile();
application.readStudentRecords();
application.closeFile();
}
}
I second trying to put the whole path instead.
For relative paths, if you're doing compiling and running in command line/terminal, you need to have that studentrecords.txt in the same directory of your code files.
If you're using an IDE, you need to put your studentrecords.txt under the src/ folder. This is assuming you're not in maven project setup; otherwise it should be put under /src/main/java/resources/ .
Hope this helps!
Instead of creating a file every time you read from it, you should try using a FileReader wrapped in a BufferedReader.
Change this:
input = new Scanner( new File( "studentrecords.txt"));
To:
input = new Scanner(new BufferedReader(new FileReader("studentrecords.txt")));
See the tutorial for the Scanner class for more info.
Also make sure that the file you're trying to read from exists. That is, it should be on the same folder as your code. Another easy option is to try providing the full path to the file.

Why can't I store data inside my .txt file?

This is a workout app that I'm working on. The idea is to create an account(text file) and store the data that you enter inside it. Here's what I have so far.
public static void main(String[] args) {
boolean start = true;
while (start == true) {
CreateNewMember();
start = DecideToAddOrQuit();
}
}
public static void CreateNewMember() {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a username: ");
String input = keyboard.nextLine();
createMember member = new createMember(input);
member.setMembership();
member.setInfo();
}
public static boolean DecideToAddOrQuit() {
Scanner keyboard = new Scanner(System.in);
out.println("\nPress 1 if you want to continue adding data.");
out.println("Press any other key if you want to leave.");
String decision = keyboard.nextLine();
if (decision.equals("1")) {
out.println("");
return true;
} else {
out.println("Goodbye!");
return false;
}
}
And here's the class responsible for adding data to the file:
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
private Formatter x;
public createMember(String name) {
this.name = name;
}
public void setMembership() {
try {
x = new Formatter(name);
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo () {
Scanner keyboard = new Scanner(System.in);
String fullNameIn, ageIn, experienceIn;
out.println("Enter your Full Name");
fullNameIn = keyboard.nextLine();
fullName = fullNameIn;
out.println("Enter your Age");
ageIn = keyboard.nextLine();
age = ageIn;
out.println("Enter your lifting experience\n");
experienceIn = keyboard.nextLine();
experience = experienceIn;
x.format("%s\t%s\t%s", fullName, age, experience );
}
}
The values that I enter(fullName, age, experience) are NOT stored in the username file. How do I fix this and why is it occuring?
If you are expecting output to be written as the program is running, you may not see it because Formatter buffers the output.
You must close() the file when you are done with it (x.close()) so that any remaining buffered data is written (this does not happen automatically, even on program exit). Also if you want the output to actually be written immediately, flush() it as soon as you write a line (x.flush()).
This question is not the clearest, but as far is I'm concerned you haven't ever told anything to actually write the data to a file at all. You should use PrintWriter. This will load the data you want into the file. Plus, in your code, your file is never created.
import java.io.PrintWriter;
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
// private Formatter x; not quite sure what this does. There seems to be no need for it.
PrintWriter write;
File f;
public createMember(String name) {
this.name = name;
}
public void setMembership() throws Exception {
try {
// x = new Formatter(name);
f = new File (name);
f.createNewFile(); // This throws a HeadlessException (i believe, as it might be a FileNotFoundException instead)
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo () throws Exception {
Scanner keyboard = new Scanner(System.in);
String fullNameIn, ageIn, experienceIn;
write = new PrintWriter(f.toString()); // This throws a FileNotFoundException
out.println("Enter your Full Name");
fullNameIn = keyboard.nextLine();
fullName = fullNameIn;
write.println (fullName);
out.println("Enter your Age");
ageIn = keyboard.nextLine();
age = ageIn;
write.println(age);
out.println("Enter your lifting experience\n");
experienceIn = keyboard.nextLine();
experience = experienceIn;
write.println(experience);
//x.format("%s\t%s\t%s", fullName, age, experience );
write.close(); // Be sure to close it, or it gives a warning and the file is never written.
}
}
I hope this is what you're looking for and happy coding!

I need to get a file reader to read a text file line by line and format them in Java

I have a text file, formatted as follows:
Han Solo:1000
Harry:100
Ron:10
Yoda:0
I need to make an arrayList of objects which store the player's name (Han Solo) and their score (1000) as attributes. I would like to be able to make this arrayList by reading the file line by line and splitting the string in order to get the desired attributes.
I tried using a Scanner object, but didn't get far. Any help on this would be greatly appreciated, thanks.
You can have a Player class like this:-
class Player { // Class which holds the player data
private String name;
private int score;
public Player(String name, int score) {
this.name = name;
this.score = score;
}
// Getters & Setters
// Overrride toString() - I did this. Its optional though.
}
and you can parse your file which contains the data like this:-
List<Player> players = new ArrayList<Player>();
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("input.txt"))); // I used BufferedReader instead of a Scanner
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(":"); // Split on ":"
players.add(new Player(values[0], Integer.parseInt(values[1]))); // Create a new Player object with the values extract and add it to the list
}
} catch (IOException ioe) {
// Exception Handling
}
System.out.println(players); // Just printing the list. toString() method of Player class is called.
You can create a Class call player. playerName and score will be the attributes.
public class Player {
private String playerName;
private String score;
// getters and setters
}
Then you can create a List
List<Player> playerList=new ArrayList<>();
Now you can try to do your task.
Additionally, you can read from file and split each line by : and put first part as playerName and second part as score.
List<Player> list=new ArrayList<>();
while (scanner.hasNextLine()){
String line=scanner.nextLine();
Player player=new Player();
player.setPlayerName(line.split(":")[0]);
player.setScore(line.split(":")[1]);
list.add(player);
}
If you have Object:
public class User
{
private String name;
private int score;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
}
Make an Reader class that reads from the file :
public class Reader
{
public static void main(String[] args)
{
List<User> list = new ArrayList<User>();
File file = new File("test.txt");
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null)
{
String[] splitedString = line.split(":");
User user = new User();
user.setName(splitedString[0]);
user.setScore(Integer.parseInt(splitedString[1]));
list.add(user);
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (reader != null)
{
try
{
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
for (User user : list)
{
System.out.println(user.getName()+" "+user.getScore());
}
}
}
The output will be :
Han Solo 1000
Harry 100
Ron 10
Yoda 0
Let's assume you have a class called Player that comprises two data members - name of type String and score of type int.
List<Player> players=new ArrayList<Player>();
BufferedReader br=null;
try{
br=new BufferedReader(new FileReader("filename"));
String record;
String arr[];
while((record=br.readLine())!=null){
arr=record.split(":");
//Player instantiated through two-argument constructor
players.add(new Player(arr[0], Integer.parseInt(arr[1])));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
if(br!=null)
try {
br.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
For small files (less than 8kb), you can use this
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class NameScoreReader {
List<Player> readFile(final String fileName) throws IOException
{
final List<Player> retval = new ArrayList<Player>();
final Path path = Paths.get(fileName);
final List<String> source = Files.readAllLines(path, StandardCharsets.UTF_8);
for (final String line : source) {
final String[] array = line.split(":");
if (array.length == 2) {
retval.add(new Player(array[0], Integer.parseInt(array[1])));
} else {
System.out.println("Invalid format: " + array);
}
}
return retval;
}
class Player {
protected Player(final String pName, final int pScore) {
super();
this.name = pName;
this.score = pScore;
}
private String name;
private int score;
public String getName()
{
return this.name;
}
public void setName(final String name)
{
this.name = name;
}
public int getScore()
{
return this.score;
}
public void setScore(final int score)
{
this.score = score;
}
}
}
Read the file and convert it to string and split function you can apply for the result.
public static String getStringFromFile(String fileName) {
BufferedReader reader;
String str = "";
try {
reader = new BufferedReader(new FileReader(fileName));
String line = null;
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append("\n");
}
str = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) {
String stringFromText = getStringFromFile("C:/DBMT/data.txt");
//Split and other logic goes here
}

How to increment a number from a saved text file?

*How to increment a number read from a saved text file?
I'm trying to add an account Number read from a file to an array and when I add a new data to the array the account number should be auto increment of the existing account number. The problem with my code is that it woks fine until i save it to a file. When I re-open the application the account number starts back from the beginning i.e if the saved acc number is 100,101 when I re-open the application the acc number starts from 100 again.
Please can any one Help Me read from the file and then write it back to file.*
The array is starting from the beginning when restart the application.But I was just wondering If any one can help me to find a solution for this
This is my code
import java.io.Serializable;
public class Student implements Serializable {
//--------------------------------------------------------------------------
protected static int nextBankID=1000;
protected int accountNumber;
protected String fname;
protected String lname;
protected String phone;
//--------------------------------------------------------------------------
//constructor
public Student(String fname, String lname, String phone){
this.accountNumber = nextBankID++;
this.fname = fname;
this.lname = lname;
this.phone=phone;
}
//--------------------------------------------------------------------------
public void setFname(String fname) {
this.fname = fname;
}
//--------------------------------------------------------------------------
public void setLname(String lname) {
this.lname = lname;
}
//--------------------------------------------------------------------------
public void setPhone(String phone) {
this.phone = phone;
}
//--------------------------------------------------------------------------
public int getAccountNumber() {
return accountNumber;
}
//--------------------------------------------------------------------------
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
//--------------------------------------------------------------------------
public String getFname() {
return fname;
}
//--------------------------------------------------------------------------
public String getLname() {
return lname;
}
//--------------------------------------------------------------------------
public String getPhone() {
return phone;
}
#Override
public String toString(){
return "\n #Acc\tFirst Name"+"\tLast Name\t#Phone"
+ "\tBalance"+ "\tOverdraft\t\t\n"+accountNumber+""
+ "\t"+fname+"\t"+lname+"\t"+phone;
}
}
//-------------------------------------------------------
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
#SuppressWarnings("unchecked")
public class ReadWrite{
//save stuAccount ArrayList will all stuAccount objects to file
public static void writeAccounts(String fileName,ArrayList<Student> stu) {
//Create a stream between the program and the file
try
{
FileOutputStream foStream = new FileOutputStream(fileName);
ObjectOutputStream outStream = new ObjectOutputStream(foStream);
outStream.writeObject(stu);
outStream.close();
}
catch(FileNotFoundException fnfEx)
{
JOptionPane.showMessageDialog(null,fnfEx.getMessage());
}
catch(IOException ioE)
{
JOptionPane.showMessageDialog(null,ioE.getMessage());
}
}
//read stuAccount ArrayList
public static ArrayList<Student> readAccounts(String fileName,ArrayList<Student> stu){ //throws IOException
try
{
//JOptionPane.showMessageDialog(null, "Enter subject details to display");
//StudentDriver.createSubject(); //create a subject to store stuAccount objects
FileInputStream fiStream = new FileInputStream(fileName);
ObjectInputStream inStream = new ObjectInputStream(fiStream);
stu = (ArrayList<Student>)inStream.readObject();
//© Increment's the stu account with 1
for (int i=0; i< stu.size(); i++){
Object b1 = stu.get(i);
if (b1 instanceof Student){
Student bAccount = (Student)b1;
if(bAccount.accountNumber==stu.get(i).getAccountNumber())
bAccount.accountNumber=stu.get(i).getAccountNumber();
}
}//for the next user entry
inStream.close();
}
catch(ClassNotFoundException cnfEx){
JOptionPane.showMessageDialog(null,cnfEx.getMessage());
}
catch(FileNotFoundException fnfEx){
JOptionPane.showMessageDialog(null,fnfEx.getMessage());
}
catch(IOException ioE){
JOptionPane.showMessageDialog(null,ioE.getMessage());
}
JOptionPane.showMessageDialog(null, ""+stu.size()
+ " stu account(s) found in the database....");
return stu; //return read objects to Driver class
}
}
// ----------------------------------------------
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class StudentDriver {
public static ArrayList<Student> stu = new ArrayList<>();
private static String fileName = "student.txt";
//------------------------------------------------------------------------------
public static void main(String [] vimal) throws IOException{
try{
stu = ReadWrite.readAccounts(fileName,stu);
if(stu.isEmpty()){
JOptionPane.showMessageDialog(null,"No account's found "
+ "in the datbase to load into memory!\n\n");
}else{
JOptionPane.showMessageDialog(null,"File contents "
+ "read and loaded into memory!\n");
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error encountered "
+ "while opening the file"
+ "\nCould not open file"
+ "\n" + e.toString());
}
//Initialise Main Menu Choice;
//------------------------------------------------------------------------------
int choice= mainMenu();
while (choice!=3){
switch (choice){
case 1:
createStudentAccount();//a new account Menu
break;
case 2:
list();//list method
break;
case -100:
JOptionPane.showMessageDialog(null,"You have selected cancel");
break;
case -99:
JOptionPane.showMessageDialog(null,"You must select 1-3");
break;
default:
JOptionPane.showMessageDialog(null,"Not a valid option .Plese"
+ " re-enter your option");
break;
}//END FO SWITCH STATEMENT
choice = mainMenu();
}//END OF WHILE LOOP
ReadWrite.writeAccounts(fileName,stu); //save ArrayList contents before exiting
System.exit(0);
}
//END MAIN , PROGRAM EXITS HERE
public static int mainMenu(){
String menu="US COLLEGE\n Main menu\n1.Add New Student\n2. Print All\n3. Exit\n\n";
String userSelection = (String)JOptionPane.showInputDialog(null,menu);
int option = validateSelection(userSelection);
return option;
}
//------------------------------------------------------------------------------
// CREATE ACCOUNT MENU SELECTION VALIDATION
public static int validateSelection(String createAccount){
//enter cancel
if (createAccount==null)
return-100;
//hit enter without entry = zero-length string
if (createAccount.length()<1)
return-99;
//entered more than one charecter
if (createAccount.length()>1)
return-101;
if (createAccount.charAt(0)< 49 ||
createAccount.charAt(0)>51)
return-101;
else
return Integer.parseInt(createAccount);
}
public static void createStudentAccount(){
String acctFirstName,acctLastName,strPhone;
try{
//Account name validation
acctFirstName = JOptionPane.showInputDialog(null,"Enter your first name");
acctLastName = JOptionPane.showInputDialog(null,"Enter Your Family Name");
strPhone =JOptionPane.showInputDialog(null,"Enter Your Phone nuber");
stu.add(new Student(acctFirstName,
acctLastName,strPhone));
}
catch(Exception e){}
}
public static void list(){
String accounts = "";
String College="\t======== US College ========\n";
JTextArea output = new JTextArea();
output.setFont(new Font("Ariel", Font.PLAIN, 12));
if(stu.isEmpty()){
JOptionPane.showMessageDialog(null,"No account's created yet");
}
else{
//for each Bank account in BankAccount ArrayList
for (Student s1: stu){
if(stu.isEmpty()){
JOptionPane.showMessageDialog(null,"No account's created yet");
}else{
accounts += s1.toString();
}
output.setText(College+accounts );
}
JOptionPane.showMessageDialog(null,output);
}
}
}
First create a table for maintaing account number.After writing text to the file, every time use to update the table of previous account no to new account no by incrementing the value of account no .

Using multiple classes getting Null pointer exception. Probably syntactical.

So I am supposed to make 3 classes and am given a 4th class to use for a user interface. One class (DBBinding) is supposed to have a String key and String value and take something like name:Alien or star: harry dean and make name or star be the "key" and the other is the "value" the next class (DBrecord) is to hold a group of these "bindings" as one record. I have chosen to keep a group of these bindings in a ArrayList. The third class(DBTable) is another ArrayList but of . I am at the point where I am reading in a line of txt from file where each line of txt is going to be one DBrecord that we know will be in correct formatting(key:value, key:value, key:value, and so on).
Where I am having trouble is within the DBrecord class. I have a method(private void addBindingToRecord(String key_, String value_)) that is called from (public static DBrecord createDBrecord(String record)) from within the DBrecord class here are each methods code.
I am having trouble with the addBindingToRecord method ... it null pointer exceptions on the first time used. I think it has to do with sytax and how I am calling the "this.myDBrecord.add(myDBBinding);"... have tried it multiple ways with same result....
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
myRecord.addBindingToRecord(temp2[0], temp2[1]);
}
}
return myRecord;
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);///Here is where my null pointer exception is.
}
I am going to post the full code of all my classes here so you have it if need to look at. Thank for any help, hints, ideas.
package DataBase;
import java.io.*;
public class CommandLineInterface {
public static void main(String[] args) {
DBTable db = new DBTable(); // DBTable to use for everything
try {
// Create reader for typed input on console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
int length = 0;
int selectedLength = 0;
// YOUR CODE HERE
System.out.println("\n" + length + " records (" + selectedLength + " selected)");
System.out.println("r read, p print, sa select and, so select or, da ds du delete, c clear sel");
System.out.print("db:");
line = reader.readLine().toLowerCase();
if (line.equals("r")) {
System.out.println("read");
String fname;
System.out.print("Filename:");
//fname = reader.readLine();////ADD BACK IN AFTER READ DEBUGED
// YOUR CODE HERE
fname="movie.txt";
db.readFromFile(fname);
}
else if (line.equals("p")) {
System.out.println("print");
// YOUR CODE HERE
DBTable.print();
}
else if (line.equals("da")) {
System.out.println("delete all");
// YOUR CODE HERE
}
else if (line.equals("ds")) {
System.out.println("delete selected");
// YOUR CODE HERE
}
else if (line.equals("du")) {
System.out.println("delete unselected");
// YOUR CODE HERE
}
else if (line.equals("c")) {
System.out.println("clear selection");
/// YOUR CODE HERE
}
else if (line.equals("so") || line.equals("sa")) {
if (line.equals("so")) System.out.println("select or");
else System.out.println("select and");
System.out.print("Criteria record:");
String text = reader.readLine(); // get text line from user
// YOUR CODE HERE
}
else if (line.equals("q") || line.equals("quit")) {
System.out.println("quit");
break;
}
else {
System.out.println("sorry, don't know that command");
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
package DataBase;
import java.util.*;
import java.io.*;
public class DBTable {
static ArrayList<DBrecord> myDBTable;
public DBTable()
{
ArrayList<DBrecord> myDBTable= new ArrayList<DBrecord>();
}
public static void addRecordToTable(DBrecord myRecord)//added static when added addRecordToTable in readFromFile
{
if(myRecord!=null)
{myDBTable.add(myRecord);}
}
public static void readFromFile(String FileName)
{
try
{
FileReader myFileReader=new FileReader(FileName);
String line="Start";
BufferedReader myBufferdReader=new BufferedReader(myFileReader);
while(line!="\0")
{
line=myBufferdReader.readLine();
if(line!="\0")
{
System.out.println(line);//TEST CODE
addRecordToTable(DBrecord.createDBrecord(line));// made addRecordToTable static.
}
}
}catch(IOException e)
{System.out.println("File Not Found");}
}
public static void print()
{
if (myDBTable==null)
{
System.out.println("EMPTY TABLE");
return;
}
else
{
for (int i=0; i<myDBTable.size(); i++)
{
System.out.println(myDBTable.get(i).toString());
}
}
}
}
package DataBase;
import java.util.*;
import java.lang.reflect.Array;
//import DataBase.*;//did not help ... ?
public class DBrecord {
boolean select;
String key;
//need some type of collection to keep bindings.
ArrayList<DBBinding> myDBrecord;
public DBrecord()
{
//DBrecord myRecord=new DBrecord();
select=false;
ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
//System.out.println(myDBBinding.toString());//for testing
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);
System.out.println(key_);//for testing
System.out.println(value_);//for testing
}
public String toString()
{
//out put key first then all values in collection/group/record. use correct formatting.
StringBuilder myStringbuilder=new StringBuilder();
for (int i=0;i<this.myDBrecord.size();i++)
{
myStringbuilder.append(myDBrecord.get(i).toString());
myStringbuilder.append(", ");
}
myStringbuilder.delete(myStringbuilder.length()-2, myStringbuilder.length()-1);//delete last ", " thats extra
return myStringbuilder.toString();
}
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
//System.out.println("HERE");//for testing
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
//System.out.println("HERE");//for testing
//for(int i=0; i<Array.getLength(temp); i++) ///for testing
//{System.out.println(temp[i]);}
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
System.out.println(temp2[0]);//for testing
System.out.println(temp2[1]);//for testing
myRecord.addBindingToRecord(temp2[0], temp2[1]);
System.out.println(temp2[0]+ " "+ temp2[1]);////test code
}
}
return myRecord;
}
}
package DataBase;
public class DBBinding {
private String key;
private String value;
public DBBinding(String key_, String value_)
{
key =key_;
value=value_;
}
public String getKey()
{return key;}
public String getValue()
{return value;}
public String toString()
{return key+": "+value;}
}
In your constructor: ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
You only create a local variable named myDbrecord and initialize it, instead of initializing the field myDBrecord.
You probably wanted instead:
myDBrecord = new ArrayList<DBBinding>();

Categories

Resources