No Line Found Error (java.util.NoSuchElementException) - java

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

Related

Read and write an ArrayList to a .txt file

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.

Java creating a temp file , deleting a specific string and rename to original

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

Error String index out of range when crawling

I keep getting an error with my program after it craws the first 2 URL's "Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 0". The first couple of URL's craw as I want them to and I get the text from them using a method in another class. The other class could be the problem I don't know. Please have a look at my code and see whats happening.
package WebCrawler;
import java.util.Scanner;
import java.util.ArrayList;
import static TextAnalyser.Textanalyser.analyse;
public class Crawler {
public static void main(String[] args) {
// java.util.Scanner input = new java.util.Scanner(System.in);
// System.out.print("Enter a URL: ");
// String url = input.nextLine();
crawler("http://www.port.ac.uk/"); // Traverse the Web from the a starting url
}
public static void crawler(String startingURL) {
ArrayList<String> listOfPendingURLs = new ArrayList<String>();
ArrayList<String> listOfTraversedURLs = new ArrayList<String>();
listOfPendingURLs.add(startingURL);
while (!listOfPendingURLs.isEmpty() && listOfTraversedURLs.size() <= 100) {
String urlString = listOfPendingURLs.remove(0);
if (!listOfTraversedURLs.contains(urlString)) {
listOfTraversedURLs.add(urlString);
String text = urlString;
text = ReadTextfromURL.gettext(text);
text = analyse(text);
System.out.println("text : " + text);
System.out.println("Craw " + urlString);
for (String s: getSubURLs(urlString)) {
if (!listOfTraversedURLs.contains(s)) {
listOfPendingURLs.add(s);
}
}
}
}
}
public static ArrayList<String> getSubURLs(String urlString) {
ArrayList <String> list = new ArrayList<String>();
try {
java.net.URL url = new java.net.URL(urlString);
Scanner input = new Scanner(url.openStream());
int current = 0;
while (input.hasNext()) {
String line = input.nextLine();
current = line.indexOf("http:", current);
while (current > 0) {
int endIndex = line.indexOf("\"", current);
if (endIndex > 0) { // Ensure that a correct URL is found
list.add(line.substring(current, endIndex));
current = line.indexOf("http:", endIndex);
} else {
current = -1;
}
}
}
} catch (Exception ex) {
System.out.println("Error: " + ex.getMessage());
}
return list;
}
}

Why does a integer, after put into an array, change values?

SOLVED IT
I've written a program that loads Strings after an equal sign, and has it count how many times its done this. After counting, I tell it to tell me how large the int is. The value I'm looking for is 3, and it tells me, 3. I then change it to an String, the value stays three. Then, I put it into an 4d array, and It tells me the value is 2. What happened?
The Code:
int times=0;
else if (list.equals("Weapon")) {//If the word weapon is before the =
weapon = value; //take the string after the = and put it into String weapon
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray");
times++
//loops
The Output:
3weapontimes //Counted the equals sign 3 times, Note that this is from the part of the
omitted code
3string // Changed the integer to a string and got 3
2InArray // Put it into an array, and got 2 back
What Is going on?
(I know that I could just add 1 to the value, but I want to use this code for a unknown number of things later on)
To help, I've posted the entire code:
public class TroopLoader {
static String[][][][] troopStats;
static int times = 0;
static int weaponTimes = 0;
static int armorTimes = 0;
static int animalTimes = 0;
static String weaponTimesStr;
static String armorTimesStr;
static String animalTimesStr;
static String troop;
static String weapon;
static String armor;
static String animal;
static String speed;
static int total = 0;
/*
* [][][]
*
* [total number of troops (total)]
*
* [stats] 0= name 1= weapon 2= armor 3= animal 4= speed
*
* [different things within stat]
*/
public void readTroop() {
File file = new File("resources/objects/troops.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
// repeat until all lines is read
while ((text = reader.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
if (list.equals("Troop")) {
total++;
}
else {
}
} else {
}
}
troopStats = new String[total][5][10][2];
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
File file2 = new File("resources/objects/troops.txt");
BufferedReader reader2 = null;
try {
reader2 = new BufferedReader(new FileReader(file2));
String text = null;
// repeat until all lines is read
while ((text = reader2.readLine()) != null) {
StringTokenizer troops = new StringTokenizer(text, "=");
if (troops.countTokens() == 2) {
String list = troops.nextToken();
String value = troops.nextToken();
if (list.equals("Troop")) {
troop = value;
troopStats[times][0][0][0] = troop;
}
else if (list.equals("Weapon")) {
weapon = value;
troopStats[times][1][weaponTimes][0] = weapon;
weaponTimes++;
System.out.println(weaponTimes+"weapontimes"+times);
}
else if (list.equals("Armor")) {
armor = value;
troopStats[times][2][armorTimes][0] = armor;
armorTimes++;
}
else if (list.equals("Animal")) {
animal = value;
troopStats[times][3][animalTimes][0] = animal;
animalTimes++;
}
else if (list.equals("Speed")) {
speed = value;
troopStats[times][4][0][0] = speed;
}
else if (list.equals("Done")) {
weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr+"string");
armorTimesStr = Integer.toString(armorTimes);
animalTimesStr = Integer.toString(animalTimes);
troopStats[times][1][0][1] = weaponTimesStr;
troopStats[times][1][0][1] = armorTimesStr;
troopStats[times][1][0][1] = animalTimesStr;
System.out.println(troopStats[times][1][0][1]+"InArray"+times);
times++;
troop = "";
weapon = "";
armor = "";
animal = "";
speed = "";
weaponTimes = 0;
armorTimes = 0;
animalTimes = 0;
}
else {
}
} else {
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (reader2 != null) {
reader2.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
In the earlier part of the code, I had the program store a value in the location on the array with the weaponTimes variable, not storing the weaponTimes variable. My mistake, sorry for wasting your time.
I wrote a SSCCE with what you posted and it prints what you would expect:
public static void main(String[] args) {
String[][][][] troopStats = new String[4][4][4][4];
int times = 2;
int weaponTimes = 3;
String weaponTimesStr = Integer.toString(weaponTimes);
System.out.println(weaponTimesStr + "string"); //prints 3string
troopStats[times][1][0][1] = weaponTimesStr;
System.out.println(troopStats[times][1][0][1] + "InArray"); //prints 3InArray
}
So the problem is most likely something/somewhere else.
The following:
public class Foo {
public static void main(String[] args) {
String[][][][] troopStats = new String[2][2][2][2];
String weaponTimesStr = Integer.toString(3);
System.out.println(weaponTimesStr+"string");
troopStats[0][1][0][1] = weaponTimesStr;
// You said in a comment that 'times' is equal to 0 in this case so have subbed that in
System.out.println(troopStats[0][1][0][1]+"InArray");
}
}
Gives me the expected output:
3string
3InArray
Sorry I've wasted your time, my mistake was because I stored values in the array using the values of weaponTimes, and not storing weaponTimes in the array.
troopStats[times][1][weaponTimes][0] = weapon;
That was the mistake.

how to reset program to main string args?

I am writing a program and if it catches an Exception I want to reset the whole program is there anyway please tell me I really need to finish it tonight ?
public static void readinfile(ArrayList<ArrayList> table,
int numberOfColumns,ArrayList<String> header,
ArrayList<ArrayList<String>> original,
ArrayList<String> sntypes, ArrayList<Integer> displaySize,
ArrayList<String> writeOut, Scanner inputStream) {
//System.out.print("enter data file: ");
Scanner keyboard = new Scanner(System.in);
System.out.print("enter data file: ");
String fileName = keyboard.nextLine();
try {
System.out.println("try " + fileName);
inputStream = new Scanner(new FileInputStream(fileName));
System.out.println(inputStream);
} catch (FileNotFoundException E) {
System.out.println("Error in opening file ");
//readinfile(table, numberOfColumns, header,
//original, sntypes,displaySize, writeOut, inputStream );
}
// file is now open and input scanner attached
if (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList<String> rowOne = new ArrayList<String>();
while (lineparse.hasNext()) {
String temp = lineparse.next();
String originaltemp = temp;
writeOut.add(temp);
temp = temp + "(" + (++numberOfColumns) + ")";
displaySize.add(temp.length());
// row.add(lineparse.next());
if (temp.trim().substring(0, 2).equalsIgnoreCase("S ")
|| temp.trim().substring(0, 2).equalsIgnoreCase("N ")) {
rowOne.add(originaltemp);
header.add(temp.substring(2));
sntypes.add(temp.toUpperCase().substring(0, 2).trim());
} else {
System.out.println("Invalid file please enter a new file: ");
//readinfile(table, numberOfColumns, header, original, sntypes,displaySize,writeOut,Name);
readinfile(table, numberOfColumns, header,
original, sntypes, displaySize, writeOut, inputStream);
}
}
// add table here it gives problem later on...
original.add(rowOne);
}
while (inputStream.hasNextLine()) {
String Line = inputStream.nextLine();
Scanner lineparse = new Scanner(Line);
lineparse.useDelimiter(",");
ArrayList row = new ArrayList();
int j = 0;
while (lineparse.hasNextLine()) {
String temp = lineparse.next().trim();
int sizeOfrow = temp.trim().length();
if (sizeOfrow > displaySize.get(j)) {
displaySize.set(j, sizeOfrow);
}
if (j < numberOfColumns && sntypes.get(j).equalsIgnoreCase("N")) {
try {
if (temp.equalsIgnoreCase("")) {
row.add(new Double(0.0));
} else {
row.add(new Double(temp.trim()));
}
} catch (NumberFormatException E) {
System.out.println("Opps there is a mistake "
+ "I was expecting a number and I found: " + temp);
System.out.println("This row will be ignored");
// break;
}
} else {
if (temp.equalsIgnoreCase("")) {
row.add((" "));
} else {
row.add(temp);
}
}
j++;
}
if (row.size() == numberOfColumns) {
table.add(row);
}
}// close for while
inputStream.close();
}
homework?
Here's a clue on how to think about it:
main:
start loop
start
do stuff
set ok to end
catch exception
set not ok to end
loop if not ok to end
I'm not sure if you meant this, but the following code will run again and again until it succeeds (as in: doesn't throw an exception):
public static void main(String[] args){
while(true){
try{
// execute your code
break; // if successful, exit loop
}catch(SomeException e){
// handle exception
}catch(SomeOtherException e){
// handle exception
}finally{
// clean up, if necessary
}
}
}
Note: while(true) is an awful construct that I'm sure your teachers won't like. Perhaps you'll find a better way to rephrase that.
This is a bit of a hack but you could try calling the main method again, passing the arguments. As long as you didn't modify the string array of arguments, just call main(args); from a try/catch block in the main routine. Of course, if the exception keeps happening you'll loop infinitely and blow the stack:P

Categories