I can't get this part of my project to work. (fileOut() and fileIn() methods). I would appreciate any help!
I am trying to construct a method to open a text file and to write the details of an ArrayList of type to it.
I am also trying to construct a second method to open the text file containing details of all the bank’s accounts and uses the incoming data to create BankAccount objects using a BankAccount Constructor and storing each account in an ArrayList.
Please note that other methods in the class need to use the information stored in the arraylist(s).
Here is the main bit of code to focus on(reading and writing):
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is the code for the whole class:
import javax.swing.JOptionPane;
import java.util.ArrayList;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;
public class MyBankController
{
private ArrayList<BankAccount> bankAccArrayList;
public MyBankController()
{
bankAccArrayList = new ArrayList<BankAccount>();
}
public void createAccount (String accNum, String custName)
{
bankAccArrayList.add(new BankAccount( accNum,custName));
printAccountDetails(bankAccArrayList.get(bankAccArrayList.size()-1));
}
private void printAccountDetails(BankAccount incomingAcc)
{
JOptionPane.showMessageDialog(null,incomingAcc.toString(),"Account Details",JOptionPane.PLAIN_MESSAGE);
}
public void listAllAccounts()
{
String outputStr = "List of all accounts :\n\n";
for(BankAccount account : bankAccArrayList){
outputStr += account + "\n\n";
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Accounts",JOptionPane.PLAIN_MESSAGE);
}
public void listAllActiveAccounts()
{
String outputStr = "List of all active accounts :\n\n";
for(BankAccount account : bankAccArrayList){
if(account.getActive()) {
outputStr += account + "\n\n";
}
}
JOptionPane.showMessageDialog(null,outputStr,"List of all Active Accounts",JOptionPane.PLAIN_MESSAGE);
}
private int getIndex(String bankAccNum)
{
for (int i = 0; i < bankAccArrayList.size(); i++) {
if (bankAccNum.equals(bankAccArrayList.get(i).getAccNumber()))
{
return i;
}
}
JOptionPane.showMessageDialog(null,"Bank Account Number: " + bankAccNum + " is invalid","Error wrong account number",JOptionPane.ERROR_MESSAGE);
return -1;
}
public void makeWithdrawal(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeWithdraw(amount);
}
}
public void makeLodgement(String accNumber, double amount)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).makeLodgement(amount);
}
}
public void displayAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
JOptionPane.showMessageDialog(null,(bankAccArrayList.get(getIndex(accNumber)).toString()),"Accounts Details",JOptionPane.PLAIN_MESSAGE);
}
}
public void closeAccount(String accNumber)
{
if(getIndex(accNumber) != -1){
bankAccArrayList.get(getIndex(accNumber)).closeAccount();
}
}
public void removeAccount(String accNumber)
{
int index = getIndex(accNumber);
if(index != -1){
BankAccount myAcc = bankAccArrayList.get(index);
if ((myAcc.getActive() == false) && (myAcc.getAccBalance() == 0)){
bankAccArrayList.remove(index);
}else if((myAcc.getActive() == false) && (myAcc.getAccBalance() > 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account has a balance,do you wish to withdraw this balance " +
"so as to remove the account ?"," Balance in inactive account",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
myAcc.makeWithdraw(myAcc.getAccBalance());
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else if((myAcc.getActive() == true) && (myAcc.getAccBalance() == 0)){
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status, do you wish to change its status so as to remove account ?"
,"Account Active",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.setActive();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
} else{
int dialogResult = JOptionPane.showConfirmDialog(null," This account still has an active status and a balance, do you wish to close the account so as remove it"
,"Account Active with Balance",JOptionPane.PLAIN_MESSAGE);
if(dialogResult == JOptionPane.YES_OPTION){
myAcc.closeAccount();
bankAccArrayList.remove(index);
JOptionPane.showMessageDialog(null,"Account Removed","Confirmation",JOptionPane.PLAIN_MESSAGE);
}
}
}
}
public void customerInterface()
{
String accNumber = JOptionPane.showInputDialog(null,"Please enter your account number","Account Login",JOptionPane.PLAIN_MESSAGE);
if(getIndex(accNumber) != -1)
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Make a lodgment:\n\n [2] Make a withdrawal:\n\n [3] Display account details:\n\n" +
" [4] Close account:\n\n [5] Exit","MyBank ATM",JOptionPane.PLAIN_MESSAGE);
if (numOption == null) //User presses cancel or 'x'.
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE);
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Brings up lodgement interface
String amount = JOptionPane.showInputDialog("Please enter the amount you would like to lodge.");
makeLodgement(accNumber, Double.parseDouble(amount)); // Lodges amount into account.
customerInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
String amount = JOptionPane.showInputDialog("Please enter the amount you wish to withdraw.");
makeWithdrawal(accNumber, Double.parseDouble(amount)); //Call on makeWithdrawl method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
displayAccount(accNumber); //Calls on displayAccount method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
closeAccount(accNumber); //Call on close account method.
customerInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
return; //Exits system.
}
else if(Integer.parseInt(numOption) > 5 || Integer.parseInt(numOption) < 1) //If number enter is outside of 1-5.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-5 and try again.","Error",JOptionPane.ERROR_MESSAGE);
customerInterface();
}
}
}
public void bankInterface()
{
String numOption = JOptionPane.showInputDialog(null,"Please select an option below:\n\n" +
" [1] Display All Accounts:\n\n [2] Display All Active Accounts:\n\n [3] Open a New Account:\n\n" +
" [4] Close an Existing Account:\n\n [5] Run Start of Day:\n\n [6] Run End of Day:\n\n [7] Exit:","MyBank System",JOptionPane.PLAIN_MESSAGE);
if (numOption == null)
{
JOptionPane.showMessageDialog(null,"Goodbye.","MyBank System",JOptionPane.INFORMATION_MESSAGE); //User presses cancel or 'x'.
}
else if(Integer.parseInt(numOption) == 1) //Converts numOption from String to Integer.
{
//Displays all accounts.
listAllAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 2)
{
//Display all active accounts.
listAllActiveAccounts();
bankInterface();
}
else if(Integer.parseInt(numOption) == 3)
{
//Open a new account
String accNum = JOptionPane.showInputDialog("Please allocate an account number:");
String custName = JOptionPane.showInputDialog("Please enter the customers name:");
createAccount (accNum, custName);
bankInterface();
}
else if(Integer.parseInt(numOption) == 4)
{
//Close an existing account.
String accNumber = JOptionPane.showInputDialog("Please enter the account number you would like to close:");
closeAccount(accNumber);
bankInterface();
}
else if(Integer.parseInt(numOption) == 5)
{
//Run start of day file.
fileIn();
bankInterface();
}
else if(Integer.parseInt(numOption) == 6)
{
//Run end of day file.
fileOut();
bankInterface();
}
else if(Integer.parseInt(numOption) == 7)
{
//Exits system.
return;
}
else if(Integer.parseInt(numOption) > 7 ||Integer.parseInt(numOption) < 1) //If user enters number outside of 1-7.
{
JOptionPane.showMessageDialog(null,"Please enter a number between 1-7 and try again.","Error",JOptionPane.ERROR_MESSAGE);
bankInterface();
}
}
public void fileOut()
{
File fileName = new File("BankAccountFiles.txt");
try{
FileWriter fw = new FileWriter(fileName);
Writer output = new BufferedWriter(fw);
int numEntries = bankAccArrayList.size();
for (int i = 0; i < numEntries; i++) {
output.write(bankAccArrayList.get(i).toString() + "\n");
}
output.close();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null,"File cannot be created");
}
}
public void fileIn()
{
ArrayList<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(line);
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
}
}
In your fileIn method, you're trying to add a String to an ArrayList of type BankAccount. Instead of aList.add(line), you should use aList.add(new BankAccount(line)).
Assuming your BankAccount constructor takes only a single String parameter, this should work.
Full method:
public void fileIn()
{
List<BankAccount> aList = new ArrayList<BankAccount>();
String line;
try {
BufferedReader input = new BufferedReader(new FileReader("BankAccountFiles.txt"));
if(!input.ready()) {
throw new IOException();
}
while ((line = input.readLine()) != null) {
aList.add(new BankAccount(line));
}
input.close();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,e);
}
aList.forEach(System.out::println); // Java8
}
I've also changed your aList to use the List interface, and added a lambda to print each value in aList at the end.
Related
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.
I want to validate email id which is entered by the user.
In my program the constraints are that there cannot be whitespaces,(-),(_) and more than one (#).
This is the code i have written but its not giving the right output.
the code is:
import java.io.*;
class test
{
void main() throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter your email-address");
String emailid=br.readLine().trim();
boolean ans=true;
int n=0;
while(ans)
{
for(int i=0;i<emailid.length();i++)
{
char temp=emailid.charAt(i);
if( Character.isLetterOrDigit(temp)==false && temp!='#' && temp!='.')
{
System.out.println("A email id can consist of only alphabets,numerics and '.'");
emailid=br.readLine().trim();
ans=true;
continue;
}
else
{
ans=false;
}
if(temp=='#')
{
n+=1;
}
if(n>1)
{
System.out.println("email id can have only one #..Please try again");
emailid=br.readLine().trim();
ans=true;
continue;
}
else
{
ans=false;
}
}
}
}
}
As the topic states im trying to get a specific string that is usually auto generated into the same string and it seems to work because the temp file is created and the string is replaced with "" but its seems that there is an IOException when it comes to renaming to original when deleting , help please?
import java.io.*;
import java.util.Scanner;
/**
* Main class to test the Road and Settlement classes
*
* #author Chris Loftus (add your name and change version number/date)
* #version 1.0 (24th February 2016)
*
*/
public class Application {
private Scanner scan;
private Map map;
private static int setting;
public Application() {
scan = new Scanner(System.in);
map = new Map();
}
private void runMenu() {
setting = scan.nextInt();
scan.nextLine();
}
// STEP 1: ADD PRIVATE UTILITY MENTHODS HERE. askForRoadClassifier, save and
// load provided
private Classification askForRoadClassifier() {
Classification result = null;
boolean valid;
do {
valid = false;
System.out.print("Enter a road classification: ");
for (Classification cls : Classification.values()) {
System.out.print(cls + " ");
}
String choice = scan.nextLine().toUpperCase();
try {
result = Classification.valueOf(choice);
valid = true;
} catch (IllegalArgumentException iae) {
System.out.println(choice + " is not one of the options. Try again.");
}
} while (!valid);
return result;
}
private void deleteSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
String generatedResult = "Name: " + name + " Population: " + p + " SettlementType " + newSetK;
String status = searchAndDestroy(generatedResult);
}
private String searchAndDestroy(String delete) {
File file = new File("C:\\Users\\Pikachu\\workspace\\MiniAssignment2\\settlements.txt");
try {
File temp = File.createTempFile("settlement", ".txt", file.getParentFile());
String charset = "UTF-8";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
for (String line; (line = reader.readLine()) != null;) {
line = line.replace(delete, "");
writer.println(line);
}
System.out.println("Deletion complete");
reader.close();
writer.close();
file.delete();
temp.renameTo(file);
}
catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 1");
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! 2");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Sorry! Can't do that! , IO Exception error incurred 3");
}
return null;
}
private void save() {
map.save();
}
private void load() {
map.load();
}
public void addSettlement() {
String name;
int p;
SettlementType newSetK = SettlementType.CITY;
int set;
System.out.println("Please type in the name of the settlement");
name = scan.nextLine();
System.out.println("Please type in the population of the settlment");
p = scan.nextInt();
scan.nextLine();
System.out.println("Please type in the number of the type of settlement .");
System.out.println("1: Hamlet");
System.out.println("2: Village");
System.out.println("3: Town");
System.out.println("4: City");
set = scan.nextInt();
scan.nextLine();
if (set == 1) {
newSetK = SettlementType.HAMLET;
}
if (set == 2) {
newSetK = SettlementType.VILLAGE;
}
if (set == 3) {
newSetK = SettlementType.TOWN;
}
if (set == 4) {
newSetK = SettlementType.CITY;
}
new Settlement(name, newSetK, p);
}
private void printMenu() {
System.out.println("Please type in the number of the action that you would like to perform");
System.out.println("1: Create Settlement");
System.out.println("2: Delete Settlement");
System.out.println("3: Create Road");
System.out.println("4: Delete Road");
System.out.println("5:Display Map");
System.out.println("6:Save Map");
}
public static void main(String args[]) {
Application app = new Application();
app.printMenu();
app.runMenu();
System.out.println(setting);
if (setting == 1) {
app.addSettlement();
}
if (setting == 2) {
app.deleteSettlement();
}
app.load();
app.runMenu();
app.save();
}
}
I checked if it was deletable (file.delete throws a boolean exception) so I tried deleting it directly via windows and apparently it was being used by java so I assumed eclipsed glitch and upon closing and booting up eclipse again it worked..... well... that was rather anti-climactic .... Thank you so much for the discussion , I would definitely never had figured it out if not for the discussion :D <3 You are all in my heart
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
Okay so I have a hashmap of the class Stock, which basically has data about different stocks from yahoo that a user can enter. Each time they enter a new stock, I add that Stock class to the hashmap, and I don't know how to print out the whole hashmap and display everything entered so far
public class AS4stocks {
static Map<String, Stock> mappin = new HashMap<String, Stock>();
public static void main(String[] args) throws IOException {
int menuchoice;
do {
Scanner in1 = new Scanner(System.in);
System.out
.println("What would you like to do \n1) Print table\n2) Add a stock\n3) Do something else");
menuchoice = in1.nextInt();
switch (menuchoice) {
case 1:
System.out.println(mappin);
break;
case 2:
System.out.print("Enter the stock's ticker symbol\n");
String ticker = in1.next();
addstock(ticker);
break;
case 3:
break;
}
} while (menuchoice != 0);
}
private static void Printtable(Map<String, Stock> mappin) {
fo
}
private static void addstock(String ticker) throws IOException {
URL url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s="
+ ticker + "&f=snd1ohgpvwm3m4&e=.csv");
URLConnection con = url.openConnection();
InputStream is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
Object[] otable = new String[11];
int counter = 0;
while ((line = br.readLine()) != null) {
String str = line;
StringTokenizer st = new StringTokenizer(str, ",\"");
while (st.hasMoreTokens()) {
String adder = st.nextToken();
otable[counter] = adder;
if (counter == 0) {
System.out.println("-------------------" + adder
+ "-------------------");
System.out.print("Ticker: ");
}
if (counter == 2) {
System.out.print("Company: ");
}
if (counter == 3) {
System.out.print("Open: ");
}
if (counter == 4) {
System.out.print("High: ");
}
if (counter == 5) {
System.out.print("Low: ");
}
if (counter == 6) {
System.out.print("Close: ");
}
if (counter == 7) {
System.out.print("Volume: ");
}
if (counter == 8) {
System.out.print("52 Week Range: ");
}
if (counter == 9) {
System.out.print("50 Day Average: ");
}
if (counter == 10) {
System.out.print("200 Day Average: ");
}
System.out.println(adder);
counter++;
}
Stock snew = new Stock(otable);
mappin.put(ticker, snew);
}
System.out.println();
}
static class Stock {
String compname;
String ticker;
String date;
String open;
String high;
String low;
String close;
String volume;
String range;
String average50;
String average200;
public Stock(Object otable[]) {
compname = (String) otable[0];
ticker = (String) otable[1];
date = (String) otable[2];
open = (String) otable[0];
high = (String) otable[1];
low = (String) otable[2];
close = (String) otable[3];
volume = (String) otable[4];
range = (String) otable[5];
average50 = (String) otable[6];
average200 = (String) otable[7];
}
}
}
You'll need to iterate through the map and print what you want for each entry. Easiest way to iterate through the values would be:
for (Stock stock : mappin.values()) {
System.out.println(stock.toString());
}
This assumes of course your Stock class has meaningful output for toString()