Importing from text file into Java Array - java

Currently I am trying to import data from a text file regarding pets and doctors, and sending it to my "petArray" and "doctorArray".
I am extremely new to Java and as such am having great difficulty. This is what ive attempted to do, but it doesnt seem too work.
Please see attached Java code and text file (screenshot at link).
public void readFile() {
String fileName = "VetManagement.txt";
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening file: " + fileName);
System.exit(0);
}
while (inputStream.hasNextLine()) {
String line = inputStream.nextLine();
String initName = "";
String initSize = "";
String initType = "";
String initDoctor = "";
double initWeight = 0.0;
int initAge = 0;
if (line.equals("Pets")) {
inputStream.nextLine();
if (line.equals("type cat")) {
initType = "cat";
System.out.print(initType);
} else if (line.equals("type dog")) {
initType = "dog";
System.out.print(initType);
}
inputStream.nextLine();
if (line.equals("size small")) {
initSize = "small";
} else if (line.equals("size medium")) {
initSize = "medium";
} else if (line.equals("size large")) {
initSize = "large";
} else System.out.println("error");
inputStream.nextLine();
if (line.startsWith("name")) {
initName = inputStream.next();
} else {
System.out.println("error");
}
inputStream.nextLine();
if (line.startsWith("weight")) {
initWeight = inputStream.nextDouble();
} else {
System.out.println("error");
}
inputStream.nextLine();
if (line.startsWith("age")) {
initAge = inputStream.nextInt();
} else {
System.out.println("error");
}
inputStream.nextLine();
if (line.startsWith("doctor")) {
initDoctor = inputStream.toString();
} else {
System.out.println("error");
}
petArray[sumPets] = new Pet();
petArray[sumPets].setType(initType);
petArray[sumPets].setSize(initSize);
petArray[sumPets].setName(initName);
petArray[sumPets].setWeight(initWeight);
petArray[sumPets].setAge(initAge);
petArray[sumPets].setDoctorName(initDoctor);
} else if (line.equals("Doctors")) ;
}
inputStream.close();
}
TEXT FILE:
Pets
type cat
size small
name Lara
weight 4
age 5
doctor Joao
type dog
size large
name Biro
weight 15
age 12
doctor Maria
type cat
size large
name Benny
weight 7
age 10
doctor no doctor assigned
Doctors
name Joao
specialisation cat
name Maria
specialisation dog

nextLine can solve the problem easily no need to over-complicate the work
As the TEXT FILE contains information in format like
type cat
size small
name Lara
weight 4
age 5
doctor Joao
You can easily store information in desired variable using
nextLine = inputStream.nextLine().split(" ");
where nextLine[0] represent first column and nextLine[1] represent second column
I Hope this helps let me know if you have any other problem here is FULL CODE (in case you need)
public static void readFile() {
String fileName = "F:\\document\\eclipse\\JavaAZ\\src\\VetManagement.txt";
Scanner inputStream = null;
try {
inputStream = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error opening file: " + fileName);
System.exit(0);
}
String[] name = new String[100];
String[] size = new String[100];
String[] type = new String[100];
String[] doctor = new String[100];
double[] weight = new double[100];
int[] age = new int[100];
if (inputStream.hasNextLine()) {
String[] nextLine = inputStream.nextLine().split(" ");
int petCounter = 0;
int doctorCounter = 0;
String workingArray = new String(nextLine[0]);
while(inputStream.hasNextLine()) {
if(workingArray.equals("Pets")) {
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("Doctors")) {
workingArray = "Doctors";
continue;
}
if (nextLine[0].equals("type")) {
type[petCounter] = nextLine[1];
//System.out.println(type);
}
else System.out.println("type error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("size")) {
size[petCounter] = nextLine[1];
//System.out.println(size);
}
else System.out.println("size error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("name")) {
name[petCounter] = nextLine[1];
//System.out.println(name);
}
else System.out.println("name error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("weight")) {
weight[petCounter] = Double.parseDouble(nextLine[1]);
//System.out.println(weight);
}
else System.out.println("weight error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("age")) {
age[petCounter] = Integer.parseInt(nextLine[1]);
//System.out.println(age);
}
else System.out.println("age error");
nextLine = inputStream.nextLine().split(" ");
if (nextLine[0].equals("doctor")) {
doctor[petCounter] = nextLine[1];
//System.out.println(doctor);
}
else System.out.println("doctor error");
petCounter++;
}
else if(workingArray.equals("Doctors")) {
// CODE HERE
doctorCounter++;
break;
}
}
}
System.out.println("PET NAME: "+name[0]+" and its Weight: "+weight[0]);
inputStream.close();
}

if (line.equals("Pets")) {
String nextLine = inputStream.nextLine();
if (nextLine.equals("type cat")) {
initType = "cat";
System.out.print(initType);
}
else if (nextLine.equals("type dog")) {
initType = "dog";
System.out.print(initType);
}
String lineAfterThat=inputStream.nextLine();
You have to store every line before you can do anything with that.
You are assuming that inputStream.nextLine() reads the same line again and again, but each time you use inputStream.nextLine() it reads the next line of the file and reaches the end of the file eventually. That's what is wrong.
You're not understanding the way Scanner works
Use this:
if (line.equals("Pets")) {
String nextLine = inputStream.nextLine();
if (nextLine.equals("type cat")) {
initType = "cat";
System.out.print(initType);
}
else if (nextLine.equals("type dog")) {
initType = "dog";
System.out.print(initType);
}
String lineAfterThat=inputStream.nextLine();
if (lineAfterThat.equals("size small")) {
initSize = "small";
} else if (lineAfterThat.equals("size medium")) {
initSize = "medium";
} else if (lineAfterThat.equals("size large")) {
initSize = "large";
} else System.out.println("error");
String nextFirstWord=inputStream.next(); //so that it reads only till the space
if (nextFirstWord.equals("name")) {
initName = inputStream.nextLine();
} else {
System.out.println("error");
}
String ageLineFirstWord = inputStream.next();
if (ageLineFirstWord .equals("age")) {
initAge =inputStream.nextInt();
} else {
System.out.println("error");
}
inputStream.nextLine(); //this is to move the scanner to the nextline
String doctorLineFirstWord = inputStream.next();
if (doctorLineFirstWord .equals("doctor")) {
initDoctor = inputStream.nextLine();
} else {
System.out.println("error");
}

Related

Is it possible to re-open a file after close() without creating it again in the same java program?

I have to figure out a way to re-open a file that was initially an output file in order to make my program work.
My program needs to read from the input file first and then write to an output file.
Then I will prompt the user to enter code here`e option to input more or search any data from the output file.
My program starts with the option to 1-Insert more data, 2-Search Data, 3-Quit program.
I could close the I/O files after the user has input more data, but what if the user wants to search data first?
if(readFile==0)
{
FileReader inFile = new FileReader("DATA4STUDENTS.txt");
BufferedReader br = new BufferedReader(inFile);
FileWriter fw1 = new FileWriter("PASSED_STUDENTS.txt");
BufferedWriter bw1= new BufferedWriter(fw1);//Files i want to write and read again later on in the same program.
FileWriter fw2 = new FileWriter("FAILED_STUDENTS.txt");
BufferedWriter bw2 = new BufferedWriter(fw2);
PrintWriter pw1 = new PrintWriter(bw1);
PrintWriter pw2 = new PrintWriter(bw2);
pw1.print("STUDENT ID\t"+"SUBJECT CODE\t"+"CARRY MARK\t"+"STATUS\t"+"FINAL EXAM\t"+"STATUS\t"+"TOTAL MARK\t"+"STATUS\t"+"GRADE\t"+"GRADE SCORE");
pw1.println();
pw2.print("STUDENT ID\t"+"SUBJECT CODE\t"+"CARRY MARK\t"+"STATUS\t"+"FINAL EXAM\t"+"STATUS\t"+"TOTAL MARK\t"+"STATUS\t"+"GRADE\t"+"GRADE SCORE");
pw2.println();
int index=0;
Assessment [] a = new Assessment[100];
Assessment [] b = new Assessment[100];
double[] CM=new double[100]; //array for CarryMark
double[] FM= new double[100]; //array for FullMark
boolean[] PG=new boolean[100]; //array for Passing-Grade
while(((inData=br.readLine()) !=null))
{
StringTokenizer st = new StringTokenizer(inData,"#");
StudName=st.nextToken();
StudID=st.nextToken();
SubName=st.nextToken();
FullOn=Integer.parseInt(st.nextToken());
FullEX=Integer.parseInt(st.nextToken());
mark=Double.parseDouble(st.nextToken());
fullM=Integer.parseInt(st.nextToken());
EMark=Double.parseDouble(st.nextToken());
fullEM=Integer.parseInt(st.nextToken());
a[index]=new Ongoing_Assessment(StudName, StudID, SubName,FullOn, FullEX, mark, fullM);
b[index]=new Final_Exam_Assessment(StudName, StudID, SubName,FullOn,FullEX,EMark, fullEM);
if(a[index] instanceof Ongoing_Assessment)
{
Ongoing_Assessment OA=(Ongoing_Assessment) a[index];
CM[index]=OA.getFinalMark();
}
if(b[index] instanceof Final_Exam_Assessment)
{
Final_Exam_Assessment FEA=(Final_Exam_Assessment) b[index];
FM[index]=FEA.getFinalMark();
}
if((CM[index]+FM[index])>=a[index].PassingGrade())
{
PG[index]=true;
}
else
{
PG[index]=false;
}
index++;
}
for(int i=0;i<index;i++)
{
String mss=" ";
String mss1=" ";
String mss2=" ";
String grade=" ";
double grade2=0.00;
if(PG[i])
{
mss="PASS";
}
else
{
mss="FAIL";
}
if(a[i] instanceof Ongoing_Assessment)
{
Ongoing_Assessment OA=(Ongoing_Assessment) a[i];
mss1=OA.toString();
}
if(b[i] instanceof Final_Exam_Assessment)
{
Final_Exam_Assessment FEA=(Final_Exam_Assessment) b[i];
mss2=FEA.toString();
}
if(mss.equals("PASS"))
{
if((CM[i]+FM[i])>=91 &&(CM[i]+FM[i])<=100)
{
grade="A+";
grade2=4.00;
}
else if((CM[i]+FM[i])>=80 &&(CM[i]+FM[i])<=90)
{
grade="A";
grade2=4.00;
}
else if((CM[i]+FM[i])>=75 &&(CM[i]+FM[i])<=79)
{
grade="A-";
grade2=3.67;
}
else if((CM[i]+FM[i])>=70 &&(CM[i]+FM[i])<=74)
{
grade="B+";
grade2=3.33;
}
else if((CM[i]+FM[i])>=65 &&(CM[i]+FM[i])<=69)
{
grade="B";
grade2=3.00;
}
else if((CM[i]+FM[i])>=60 &&(CM[i]+FM[i])<=64)
{
grade="B-";
grade2=2.67;
}
else if((CM[i]+FM[i])>=55 &&(CM[i]+FM[i])<=59)
{
grade="C+";
grade2=2.33;
}
else if((CM[i]+FM[i])>=50 &&(CM[i]+FM[i])<=54)
{
grade="C";
grade2=2.00;
}
}
else if(mss.equals("FAIL"))
{
if((CM[i]+FM[i])>=47 &&(CM[i]+FM[i])<=49)
{
grade="C-";
grade2=1.67;
}
else if((CM[i]+FM[i])>=44 &&(CM[i]+FM[i])<=46)
{
grade="D+";
grade2=1.33;
}
else if((CM[i]+FM[i])>=40 &&(CM[i]+FM[i])<=43)
{
grade="D";
grade2=1.00;
}
else if((CM[i]+FM[i])>=30 &&(CM[i]+FM[i])<=39)
{
grade="E";
grade2=0.67;
}
else if((CM[i]+FM[i])>=0 &&(CM[i]+FM[i])<=29)
{
grade="F";
grade2=0.00;
}
}
if(mss.equals("PASS"))
{
**strong text**pw1.print(mss1+mss2+"\t"+df.format((CM[i]+FM[i]))+"%\t\t"+mss+"\t"+grade+"\t"+df.format(grade2));
pw1.println();
}
else
{
pw2.print(mss1+mss2+"\t"+df.format((CM[i]+FM[i]))+"%"+mss+"\t"+grade+"\t"+df.format(grade2));
pw2.println();
}
}
br.close();
pw1.close();
pw2.close();
}
Files cannot be reopened after they are closed. There is no way do that without recreating a object.
See https://stackoverflow.com/a/12347891/10818862 for more information.

After 1st try to save data and cant open after close the program

public class internetCalculator extends javax.swing.JFrame {
ArrayList<User> list = new ArrayList<User>();
public internetCalculator() throws IOException {
initComponents();
loadDataFromFile();
jPanel1.hide();
mainMenuJ.show(true);
}
public void saveDataToFile() throws IOException {
//Below is Internet Plan, D for DIGI, M for Maxis....
double D = 0.05, M = 0.10, C = 0.02, R1 = 0.12;
double total = 0, tax = 0; //Plan Tax Rate Per MB
double normal = 30.0, pro = 45.0, superPro = 65.0, ultra = 90;//Package
try {
String name = nameTF.getText();
String phNo = phNoTF.getText();
String usage = usageTF.getText();
String bPlan = planCB.getSelectedItem().toString();
String bPackage = packageCB.getSelectedItem().toString();
double internetUsage = Double.parseDouble(usage);
//First Calculation ***PLAN***
if (planCB.getSelectedItem().toString().equals("Digi Plan")) {
total = internetUsage * D;
} else if (planCB.getSelectedItem().toString().equals("Maxis Plan")) {
total = internetUsage * M;
} else if (planCB.getSelectedItem().toString().equals("Celcom Plan")) {
total = internetUsage * C;
} else if (planCB.getSelectedItem().toString().equals("Red1 Plan")) {
total = internetUsage * R1;
}
if (packageCB.getSelectedItem().toString().equals("Normal")) {
tax = total + normal;
} else if (packageCB.getSelectedItem().toString().equals("Pro")) {
tax = total + pro;
} else if (packageCB.getSelectedItem().toString().equals("SuperPro")) {
tax = total + superPro;
} else if (packageCB.getSelectedItem().toString().equals("UltraHighSpeed")) {
tax = total + ultra;
}
User users = new User(name, phNo, bPlan, bPackage, tax);
list.add(users); //add object s to array
File outFile = new File("Internet_Tax.txt");
FileWriter outFileStream = new FileWriter(outFile, true);
PrintWriter outStream = new PrintWriter(outFileStream);
outStream.println(name);
outStream.println(phNo);
outStream.println(bPlan);
outStream.println(bPackage);
outStream.println(tax);
outStream.close();
//If User Didnt Choose any Plan and Package , Display Error
if ((packageCB.getSelectedItem().toString().equals("Select"))
|| (planCB.getSelectedItem().toString().equals("Select"))) {
throw new Exception("Please Select PLAN or PACKAGE to Perform Calculation !");
}
if (!name.matches("[a-zA-Z]+")) {
throw new Exception("Name With Letter with A - Z ONLY !");
}// name with only Letter
if (!phNo.matches("[0-9]+")) {
throw new Exception("Phone Number with DIGIT number ONLY! ");
}//Phone number only DIGIT
if (!usage.matches("[0-9]+")) {
throw new Exception("Internet Usage with DIGIT number ONLY! ");
}//Internet Usage only DIGIT
} catch (Exception e) {
outputTA.setText(e.getMessage());
}
}//End Save Data To File
public void loadDataFromFile() throws FileNotFoundException, IOException {
File inFile = new File("Internet_Tax.txt");
if (inFile.exists()) {
FileReader fileReader = new FileReader(inFile);
Scanner scanner = new Scanner(inFile);
list.clear();
DefaultTableModel stable = new DefaultTableModel(0, 0);
String header[] = new String[]{"Name", "Phone", "Plan","Package","Total_Tax"};
stable.setColumnIdentifiers(header);
tableT.setModel(stable);
while (scanner.hasNextLine()) {
String name = scanner.nextLine();
String phNo = scanner.nextLine();
String bPlan = scanner.nextLine();
String bPackage = scanner.nextLine();
double tax = scanner.nextDouble();
User users = new User(name, phNo, bPlan, bPackage, tax);
stable.addRow(new Object[]{name, phNo, bPlan, bPackage, tax});
list.add(users);
}
scanner.close();
fileReader.close();
nameTF.setText(""); // name
phNoTF.setText(""); // matric
usageTF.setText(""); // Phone
planCB.setSelectedItem("Select");
packageCB.setSelectedItem("Select");
} else {
DefaultTableModel stable = new DefaultTableModel(0, 0);
String header[] = new String[]{"Name", "Phone", "Plan","Package","Total_Tax"};
stable.setColumnIdentifiers(header);
tableT.setModel(stable);
}
}
During the first try of running this program, the program seems to run well and display the data in table. After I close the program and run the program again, it displays errors. I don't know what is the error inside my code. The Exception error show on the loadDataFromFile():
I think this way will show you where is the problem..
Put your scanning codes in to try catch and add a condition before getting double value.
For example :
while (scanner.hasNextLine()) {
try {
String name = scanner.nextLine();
String phNo = scanner.nextLine();
String bPlan = scanner.nextLine();
String bPackage = scanner.nextLine();
if(scanner.hasNextDouble()){
double tax = scanner.nextDouble();
}else{System.out.println("Value is not Double!")}
} catch (Exception e) {
System.out.println("WARNING : " + e.getMessage());
}finally {
scanner.close();
User users = new User(name, phNo, bPlan, bPackage, tax);
stable.addRow(new Object[]{name, phNo, bPlan, bPackage, tax});
list.add(users);
}
}

No Line Found Error (java.util.NoSuchElementException)

I'm trying to handle multiple exceptions in my code, while using the Scanner to let the user enter a new path if the current one is incorrect, however I keep getting the same error, "No Line Found". Any help would be appreciated. The problem is occurring in the catch blocks at "path = sc.nextLine()".
public class Deck {
private static ArrayList<Card> monsters = new ArrayList<Card>();
private static ArrayList<Card> spells = new ArrayList<Card>();
private ArrayList<Card> deck = new ArrayList<Card>();
private static String monstersPath = "Database-Monster.csv";
private static String spellsPath = "Database-Spells.csv";
// private static Board board;
public Deck() throws IOException, UnknownCardTypeException,
UnknownSpellCardException, MissingFieldException,
EmptyFieldException {
if (monsters== null) {
monsters = loadCardsFromFile(monstersPath);
}
if (spells == null) {
spells = loadCardsFromFile(spellsPath);
}
// shuffleDeck();
buildDeck(monsters, spells);
shuffleDeck();
}
/*
* public static Board getBoard() { return board; }
*
* public static void setBoard(Board board) { Deck.board = board; }
*/
public ArrayList<Card> loadCardsFromFile(String path) throws IOException,
UnknownCardTypeException, UnknownSpellCardException,
MissingFieldException, EmptyFieldException {
Scanner sc = new Scanner(System.in);
int trials = 3;
String currentLine = null;
//String newPath = "";
for (int i = 0; i <=trials ; i++) {
try {
FileReader fileReader = new FileReader(path);
BufferedReader br = new BufferedReader(fileReader);
ArrayList<Card> temp = new ArrayList<Card>();
int sourceLineNumber = 1; // Source line
while ((currentLine = br.readLine()) != null) {
String[] mOrS = new String[6]; // Monsters or Spells
mOrS = currentLine.split(",");
int sourceFieldNumber = 0;
while (sourceFieldNumber < mOrS.length) {
if (mOrS[sourceFieldNumber].equals("")
|| mOrS[sourceFieldNumber].equals(" ")) {
throw new EmptyFieldException(path,
sourceLineNumber, sourceFieldNumber + 1); // Depends
// on
// the
// Splitted
// String
// array,
// loop
// on
// every
// field
// and
// check
}
sourceFieldNumber++;
}
if (mOrS[0].equals("Monster")) {
if (mOrS.length == 6) {
int attack = (int) (Integer.parseInt(mOrS[3]));
int defense = (int) (Integer.parseInt(mOrS[4]));
int level = (int) (Integer.parseInt(mOrS[5]));
MonsterCard monster = new MonsterCard(mOrS[1],
mOrS[2], level, attack, defense);
temp.add(monster);
} else {
throw new MissingFieldException(path,
sourceLineNumber); // Depends on the amount
// of fields in the
// String array, Monster
// should have 6, Type
// and 5 attributes.
}
} else if (mOrS[0].equals("Spell")) {
if (mOrS.length != 3) {
throw new MissingFieldException(path,
sourceLineNumber); // Depends on the amount
// of fields in the
// String Array, Spells
// should have 3, Type
// and 2 attributes
}
if (mOrS[1].equals("Card Destruction")) {
CardDestruction cardDestruction = new CardDestruction(
mOrS[1], mOrS[2]);
temp.add(cardDestruction);
} else if (mOrS[1].equals("Change Of Heart")) {
ChangeOfHeart changeOfHeart = new ChangeOfHeart(
mOrS[1], mOrS[2]);
temp.add(changeOfHeart);
} else if (mOrS[1].equals("Dark Hole")) {
DarkHole darkHole = new DarkHole(mOrS[1], mOrS[2]);
temp.add(darkHole);
} else if (mOrS[1].equals("Graceful Dice")) {
GracefulDice gracefulDice = new GracefulDice(
mOrS[1], mOrS[2]);
temp.add(gracefulDice);
} else if (mOrS[1].equals("Harpie's Feather Duster")) {
HarpieFeatherDuster harpieFeatherDuster = new HarpieFeatherDuster(
mOrS[1], mOrS[2]);
temp.add(harpieFeatherDuster);
} else if (mOrS[1].equals("Heavy Storm")) {
HeavyStorm heavyStorm = new HeavyStorm(mOrS[1],
mOrS[2]);
temp.add(heavyStorm);
} else if (mOrS[1].equals("Mage Power")) {
MagePower magePower = new MagePower(mOrS[1],
mOrS[2]);
temp.add(magePower);
} else if (mOrS[1].equals("Monster Reborn")) {
MonsterReborn monsterReborn = new MonsterReborn(
mOrS[1], mOrS[2]);
temp.add(monsterReborn);
} else if (mOrS[1].equals("Pot of Greed")) {
PotOfGreed potOfGreed = new PotOfGreed(mOrS[1],
mOrS[2]);
temp.add(potOfGreed);
} else if (mOrS[1].equals("Raigeki")) {
Raigeki raigeki = new Raigeki(mOrS[1], mOrS[2]);
temp.add(raigeki);
} else {
throw new UnknownSpellCardException(path,
sourceLineNumber, mOrS[1]); // We have 10
// spells, if
// there is an
// unknown one
// we throw the
// exception
}
} // else of Spell code
else {
throw new UnknownCardTypeException(path,
sourceLineNumber, mOrS[0]); // We have two
// types, Monster
// and Spell.
}
sourceLineNumber++;
}// While loop close
br.close();
return temp;
}// try Close
catch (FileNotFoundException exception) {
if (i == 3) {
throw exception;
}
System.out
.println("The file was not found, Please enter a correct path:");
path = sc.nextLine();
//path = newPath;
} catch (MissingFieldException exception) {
if (i == 3) {
throw exception;
}
System.out.print("The file path: " + exception.getSourceFile()
+ "At Line" + exception.getSourceLine()
+ "Contians a missing Field");
System.out.print("Enter New Path");
path = sc.nextLine();
//path = newPath;
} catch (EmptyFieldException exception) {
if (i == 3) {
throw exception;
}
System.out.println("The file path" + exception.getSourceFile()
+ "At Line" + exception.getSourceLine() + "At field"
+ exception.getSourceField()
+ "Contains an Empty Field");
System.out.println("Enter New Path");
path = sc.nextLine();
//path = newPath;
} catch (UnknownCardTypeException exception) {
if (i == 3) {
throw exception;
}
System.out.println("The file path:" + exception.getSourceFile()
+ "At Line" + exception.getSourceLine()
+ "Contains an Unknown Type"
+ exception.getUnknownType());
System.out.println("Enter New Path");
path = sc.nextLine();
//path = newPath;
} catch (UnknownSpellCardException exception) {
if (i == 3) {
throw exception;
}
System.out.println("The file Path" + exception.getSourceFile()
+ "At Line" + exception.getSourceLine()
+ "Contains an Unknown Spell"
+ exception.getUnknownSpell());
System.out.println("Enter New Path");
path = sc.nextLine();
//path = newPath;
}
} // For loop close
ArrayList<Card> noHope = null;
return noHope;
}// Method Close
You should use hasNext() before assigning path = sc.nextLine();
Something like :-
if (sc.hasNext()){
path = sc.nextLine();
}
else{
//print something else.
}
next
public String next() Finds and returns the next complete token from
this scanner. A complete token is preceded and followed by input that
matches the delimiter pattern. This method may block while waiting for
input to scan, even if a previous invocation of hasNext() returned
true. Specified by: next in interface Iterator Returns: the
next token Throws: NoSuchElementException - if no more tokens are
available IllegalStateException - if this scanner is closed See Also:
Iterator

Java Serialization issues

I have this code that writes an object:
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
And this code that loads the object:
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
I'm pretty sure that saving works, as when I opened the file in notepad++ I saw most of the data that I had saved, but when I load there is no data in module list.
Full source code:
import java.io.*;
import java.util.*;
public class Model implements java.io.Serializable {
private Student[] studentList = new Student[0];
private Module[] moduleList = new Module[0];
public void menu() {
while (true) {
System.out.println ("MENU");
System.out.println ("");
System.out.println (" 1 - Run Tests");
System.out.println (" 2 - Add Student");
System.out.println (" 3 - Add Module");
System.out.println (" 4 - Add Student To Module");
System.out.println (" 5 - Save System (Text file)");
System.out.println (" 6 - Load System (Text file)");
System.out.println (" 7 - Save System (Serialized)");
System.out.println (" 8 - Load System (Serialized)");
System.out.println (" 9 - Print Report");
System.out.println ("");
System.out.print ("Enter choice: ");
String input = keyboard.readString();
switch (input) {
case "1" :
runTests();
break;
case "2" :
System.out.print("First Name : ");
String fN = keyboard.readString();
System.out.print("Surname : ");
String sN = keyboard.readString();
System.out.print("Course Code : ");
String c = keyboard.readString();
System.out.print("User ID : ");
String iD = keyboard.readString();
AddStudent(iD, sN, fN, c);
break;
case "3" :
System.out.print("Module Code : ");
String code = keyboard.readString();
String[] temp = new String[0];
AddModule(code,temp);
break;
case "4" :
System.out.print("Module Code : ");
code = keyboard.readString();
Module m = findAModule(code);
if (m != null) {
System.out.print("User ID : ");
iD = keyboard.readString();
Student s = findAStudent(iD);
if (s != null) {
m.addThisStudent(s);
} else {
System.out.println("Student not found");
}
} else {
System.out.println("Module not found");
}
break;
case "5" :
saveToTextFiles();
break;
case "6" :
loadFromTextFiles();
break;
case "7" :
saveSerialized();
break;
case "8" :
break;
case "9" :
printReport();
break;
}
}
}
public void runTests() {
loadFromTextFiles();
saveSerialized();
printReport();
}
public void loadFromTextFiles() {
studentList = new Student[0];
moduleList = new Module[0];
try {
Scanner fileReader = new Scanner(new InputStreamReader(new FileInputStream("students.txt")));
int num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String u = fileReader.nextLine();
String sn = fileReader.nextLine();
String fn = fileReader.nextLine();
String c = fileReader.nextLine();
AddStudent(u, sn, fn, c);
}
fileReader.close();
fileReader = new Scanner(new InputStreamReader(new FileInputStream("modules.txt")));
num = fileReader.nextInt(); fileReader.nextLine();
for (int i = 0; i < num; i++) {
String code = fileReader.nextLine();
int numOfStudents = fileReader.nextInt(); fileReader.nextLine();
String[] students = new String[numOfStudents];
for (int j = 0; j < numOfStudents; j++) {
students[j] = fileReader.nextLine();
}
AddModule(code, students);
}
fileReader.close();
} catch (IOException e) {}
}
public void saveToTextFiles () {
try {
PrintWriter outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("students.txt")));
outfile.println(studentList.length);
for (int i = 0; i < studentList.length; i++) {
outfile.println(studentList[i].getUID());
outfile.println(studentList[i].getSN());
outfile.println(studentList[i].getFN());
outfile.println(studentList[i].getDegree());
}
outfile.close();
outfile = new PrintWriter(new OutputStreamWriter (new FileOutputStream("modules.txt")));
outfile.println(moduleList.length);
for (int i = 0; i < moduleList.length; i++) {
outfile.println(moduleList[i].getCode());
outfile.println(moduleList[i].getStudents().length);
for (int j = 0; j < moduleList[i].getStudents().length; j++) {
outfile.println(moduleList[i].getStudents()[j]);
}
}
outfile.close();
} catch (IOException e) {}
}
public void saveSerialized() {
try {
FileOutputStream fileOut = new FileOutputStream("Model.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(this);
out.close();
fileOut.close();
FileOutputStream fileOut2 = new FileOutputStream("Module.ser");
ObjectOutputStream out2 = new ObjectOutputStream(fileOut2);
out2.writeObject(studentList);
out2.close();
fileOut2.close();
FileOutputStream fileOut3 = new FileOutputStream("Student.ser");
ObjectOutputStream out3 = new ObjectOutputStream(fileOut3);
out3.writeObject(moduleList);
out3.close();
fileOut3.close();
} catch (IOException e) {}
}
public void loadSerialized() {
Model m = null;
try {
FileInputStream fileIn = new FileInputStream("Model.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
m = (Model) in.readObject();
in.close();
fileIn.close();
} catch (Exception e) {}
setStudentList(m.getStudentList());
setModuleList(m.getModuleList());
}
private Module[] getModuleList() {
return moduleList;
}
private Student[] getStudentList() {
return studentList;
}
private void setModuleList(Module[] m) {
moduleList = m.clone();
}
private void setStudentList(Student[] s) {
studentList = s.clone();
}
private void AddModule(String code, String[] students) {
int length = moduleList.length;
Module NewArray[] = new Module[length + 1];
for (int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Module(moduleList[i]);
}
}
NewArray[length] = new Module(code, students);
moduleList = NewArray.clone();
}
private void AddStudent(String u, String sn, String fn, String c) {
int length = studentList.length;
Student NewArray[] = new Student[length + 1];
for(int i = 0; i < length + 1; i++) {
if (i < length) {
NewArray[i] = new Student(studentList[i]);
}
}
NewArray[length] = new Student(u, sn, fn, c);
studentList = NewArray.clone();
}
public void printReport() {
for (int i = 0; i < moduleList.length; i++) {
System.out.println(moduleList[i].toString(this));
}
}
public Student findAStudent(String uid) {
for (int i = 0; i < studentList.length; i++) {
if (studentList[i].getUID().compareTo(uid) == 0) {
return studentList[i];
}
}
return null;
}
public Module findAModule(String code) {
for (int i = 0; i < moduleList.length; i++) {
if (moduleList[i].getCode().compareTo(code) == 0) {
return moduleList[i];
}
}
return null;
}
}
Look at your code sample, in particular the switch statement:
switch (input) {
...
case "8" :
break;
...
}
I'd assume the method loadSerialized should be called there but it's missing and is not called anywhere else in the code.
Once you actually call the method that does the loading, the code will work, assuming you have declared a serialVersionUID for both Student and Module.
Edit: why using serialization to persist objects is a bad idea
In simple terms, using serialization to persist objects is brittle.
An object's serialized form is tied to its class. Classes tend to change over time, meaning the serialized instance of the old cannot be loaded into the new.
While you can work round this by setting a serialVersionUID doing so introduces a reverse of the problem where, in the case new fields are introduced, the new cannot be read into objects of the old class, which can be a problem if you do rolling updates to the deployed system.
There's a host of other reasons - it's not easily readable (meaning you can't update it like you would a database or XML/JSON doc), it's inefficient, etc.

Java code not executing as expected

I've written some Java code, as shown below, but it isn't behaving as I expected. Right near the bottom, starting from the line if (upgrade == "Y"). I did a test, I entered Y but this line did not execute. Could you please help me figure out why this behaviour occurred?
import java.io.*;
class P4
{
public static int get_price(String day_of_week, String age_group)
{
int price=0;
if (day_of_week == "WD")
{
if (age_group == "adult")
price = 66;
else if (age_group == "child")
price=48;
else
price = 32;
}
else
{
if (age_group == "adult")
price = 72;
else if (age_group == "child")
price=52;
else
price = 36;
}
return price;
}
public static void main(String[] args)
{
String adult2=null;
String child2=null;
String senior2=null;
String day_of_week=null;
String upgrade=null;
System.out.println("Enter Number of Adult Ticket:");
BufferedReader adult1 = new BufferedReader(new InputStreamReader(System.in));
try
{
adult2 = adult1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Child Ticket:");
BufferedReader child1 = new BufferedReader(new InputStreamReader(System.in));
try
{
child2 = child1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Senior Ticket:");
BufferedReader senior1 = new BufferedReader(new InputStreamReader(System.in));
try
{
senior2 = senior1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Choose Weekday or Weekend Pass (WD/WE):");
BufferedReader day_of_week1 = new BufferedReader(new InputStreamReader(System.in));
try
{
day_of_week = day_of_week1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Upgrade to Express Pass (Y/N):");
BufferedReader upgrade1 = new BufferedReader(new InputStreamReader(System.in));
try
{
upgrade = upgrade1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
int adult = Integer.parseInt(adult2);
int child = Integer.parseInt(child2);
int senior = Integer.parseInt(senior2);
int total_a = adult * get_price(day_of_week, "adult");
int total_c = child * get_price(day_of_week, "child");
int total_s = senior * get_price(day_of_week, "senior");
int total_price = total_a + total_c + total_s;
int total_people = adult + child + senior;
int upgrade_price = 0;
if (upgrade == "Y")
{
if (day_of_week == "WD")
{
upgrade_price = total_people * 30;
}
else
{
upgrade_price = total_people * 68;
}
}
else
upgrade_price = 0;
int price = upgrade_price + total_price;
System.out.println("The total price is $" + price);
}}
Try using the .equal.. So else if (age_group.equals("child")
Check out the .equals() method: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equals(java.lang.Object)
and the .equalsIgnoreCase() method:
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)
import java.io.*;
class P4
{
public static int get_price(String day_of_week, String age_group)
{
int price=0;
if (day_of_week.equals("WD"))
{
if (age_group.equals("adult"))
price = 66;
else if (age_group.equals("child"))
price=48;
else
price = 32;
}
else
{
if (age_group.equals("adult"))
price = 72;
else if (age_group.equals("child"))
price=52;
else
price = 36;
}
return price;
}
You cannot compare strings with ==, you need to use equals()
if("Y".equals(upgrade))
(I tend to put the constant first, to handle the case where upgrade == null)
In java string comparison
String s = "something", t = "maybe something else";
if (s == t) // Legal, but usually WRONG.
if (s.equals(t)) // RIGHT
if (s > t) // ILLEGAL
if (s.compareTo(t) > 0) // CORRECT>
So in your case, use:
if(upgrade.equals("Y")) {
//your codes
}
import java.io.*;
class P4
{
public static int get_price(String day_of_week, String age_group)
{
int price=0;
if (day_of_week.equals("WD"))
{
if (age_group.equals("adult"))
price = 66;
else if (age_group.equals("child"))
price=48;
else
price = 32;
}
else
{
if (age_group.equals("adult"))
price = 72;
else if (age_group.equals("child"))
price=52;
else
price = 36;
}
return price;
}
public static void main(String[] args)
{
String adult2=null;
String child2=null;
String senior2=null;
String day_of_week=null;
String upgrade=null;
System.out.println("Enter Number of Adult Ticket:");
BufferedReader adult1 = new BufferedReader(new InputStreamReader(System.in));
try
{
adult2 = adult1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Child Ticket:");
BufferedReader child1 = new BufferedReader(new InputStreamReader(System.in));
try
{
child2 = child1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Enter Number of Senior Ticket:");
BufferedReader senior1 = new BufferedReader(new InputStreamReader(System.in));
try
{
senior2 = senior1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Choose Weekday or Weekend Pass (WD/WE):");
BufferedReader day_of_week1 = new BufferedReader(new InputStreamReader(System.in));
try
{
day_of_week = day_of_week1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
System.out.println("Upgrade to Express Pass (Y/N):");
BufferedReader upgrade1 = new BufferedReader(new InputStreamReader(System.in));
try
{
upgrade = upgrade1.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
int adult = Integer.parseInt(adult2);
int child = Integer.parseInt(child2);
int senior = Integer.parseInt(senior2);
int total_a = adult * get_price(day_of_week, "adult");
int total_c = child * get_price(day_of_week, "child");
int total_s = senior * get_price(day_of_week, "senior");
int total_price = total_a + total_c + total_s;
int total_people = adult + child + senior;
int upgrade_price = 0;
if (upgrade.equals("Y"))
{
if (day_of_week.equals("WD"))
{
upgrade_price = total_people * 30;
}
else
{
upgrade_price = total_people * 68;
}
}
else
upgrade_price = 0;
int price = upgrade_price + total_price;
System.out.println("The total price is $" + price);
}}
for equality condition in string you need equal method.
use
"Y".equals(upgrade); //is a good idea
instead of
upgrade == "Y"
Since Strings are objects, the equals(Object) method will return true if two Strings have the same objects. The == operator will only be true if two String references point to the same underlying String object. Hence two Strings representing the same content will be equal when tested by the equals(Object) method, but will only by equal when tested with the == operator if they are actually the same object.
refer http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
I notised that your update variable is String, thus you should use:
if (upgrade.compareTo("Y") == 0) {
//your code
}
this is the correct way to compare Strings.

Categories