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
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'm trying to use a specific code but it won't work for some reason. I have to methods in the same class:
public void InputEnter()
{
if(Input.GetKey(getCoords)) {
Move(GetTransform().GetPos());
System.out.println((GetTransform().GetPos()));
}
}
this method gives me some coordinates of Vector3f once I hit enter. The other code writes to a file.
public void ProcessText()
{
System.out.println("ProcessText Operational");
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords file = new ProcessCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2]));
}
}
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("Coordinates Saved!");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
What I wanted to do is to use the InputEnter method in the ProcessText method so I just deleted InputEnter and used the Input code in the ProcessText method:
public void ProcessText()
{
System.out.println("ProcessText Operational");
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords file = new ProcessCoords(file_name);
String[] aryLines = file.OpenFile();
int i;
for (i = 0; i < aryLines.length; i++)
{
System.out.println(aryLines[i]);
if(aryLines[i].startsWith("makeGrass:")) {
String Arguments = aryLines[i].substring(aryLines[i].indexOf(":")+1, aryLines[i].length());
String[] ArgArray = Arguments.split(",");
this.makeGrass(Double.parseDouble(ArgArray[0]),
Double.parseDouble(ArgArray[1]),
Double.parseDouble(ArgArray[2]));
}
}
if(Input.GetKey(getCoords)) {
Move(GetTransform().GetPos());
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("pressing enter doesn't work!!");
System.out.println((GetTransform().GetPos()));
}
System.out.println("Input.GetKey doesn't work anymore, but why and how to fix it??");
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
however now, pressing enter does no longer give me the coordinates as it did before, I really do not understand why and I would need some help.
Thanks a lot!
Okay it took me a while but I've figured it out, It's actually very simple:
As you can see in ProcessText() I've included both the code that reads from a file and the code that writes to a file.
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("Coordinates Saved!");
My idea was then to put the Input method into the ProcessText method as you can see here:
if(Input.GetKey(getCoords)) {
Move(GetTransform().GetPos());
ProcessCoords data = new ProcessCoords(file_name);
data.writeToFile("makeGrass:");
System.out.println("pressing enter doesn't work!!");
System.out.println((GetTransform().GetPos()));
This is almost correct but well.. to have the input work for a gameObject I need to add the Input class as a component:
gameObject.addComponent(new InputClass());
All I had to do instead is to take it out from my ProcessText method and move it into my Input class so it looks like this:
public void Input(float delta)
{
String file_name = "C:/Users/Server/Desktop/textText.txt";
try
{
ProcessCoords data = new ProcessCoords(file_name);
if(Input.GetKey(getCoords)) {
data.writeToFile("makeGrass:" + (GetTransform().GetPos()));
System.out.println("Coordinates Saved!");
System.out.println((GetTransform().GetPos()));
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
After that I was able to actually use the input for the respective gameObject and obviously get the apropriate coordinates writen to the text file only if I press enter.
And here's the result: http://www.pic-upload.de/view-27748157/AnotherExample.png.html
I hope my answer will help someone else in the future!
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
This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 9 years ago.
I created a PrintWriter and new text file and want to print my answers into the text file. However, because the code is embedded within the program's loop, every time the loop is restarted, a new text file is created to replace the last one. How do I write the code so that the text file isn't recreated every time the loop starts over?
Here is my code:
public class Wordler {
public static void main(String[] args) throws IOException{
//introduces the game
System.out.println("Wordler: Finding words within a word");
System.out.println(" ");
System.out.println("Directions:");
System.out.println("Create as many words as you can with the letters in the word given. Once you have written as many words as you can think of, type");
System.out.println("'x' and then hit the enter key to end the game round. Good luck!");
System.out.println("--------------------------------------------------------------------------------------------------------------------------");
runGame();
}
//method to run the game
public static void runGame() throws FileNotFoundException{
//array list of arrays that contains all the possible words
ArrayList<String> wholeList = new ArrayList<String>();
wholeList.add("vulnerability");
wholeList.add("calculate");
wholeList.add("virtual");
//PrintWriter and File
File results = new File("WordlerResults.txt");
PrintWriter output = new PrintWriter(results);
//list of words and their answers (as a sublist)
ArrayList<String> arr1 = new ArrayList<String>();
arr1.add("vulnerabiliy");
arr1.add("ability");
arr1.add("nearby");
arr1.add("lite");
arr1.add("near");
arr1.add("bare");
arr1.add("rule");
arr1.add("bury");
arr1.add("lair");
arr1.add("rile");
arr1.add("bear");
arr1.add("liberality");
arr1.add("virulently");
arr1.add("vulnerably");
arr1.add("inevitably");
arr1.add("tenurially");
arr1.add("inertially");
arr1.add("neutrally");
arr1.add("unlivable");
arr1.add("unitarily");
arr1.add("veniality");
arr1.add("reliantly");
arr1.add("brilliant");
arr1.add("urinative");
arr1.add("nailbiter");
arr1.add("illuviate");
arr1.add("unitively");
arr1.add("veritably");
arr1.add("trivially");
arr1.add("vibratile");
arr1.add("virtually");
// stopped at #20, www.wordplays.com/w/13810606276/vulnerability
List<String> arr1Sub = arr1.subList(1, 30);
ArrayList<String> arr2 = new ArrayList<String>();
arr2.add("calculate");
arr2.add("late");
arr2.add("call");
arr2.add("teal");
arr2.add("talc");
arr2.add("catcall");
arr2.add("tall");
arr2.add("cult");
arr2.add("lace");
arr2.add("tela");
arr2.add("acute");
arr2.add("lacteal");
arr2.add("callet");
arr2.add("acuate");
arr2.add("luteal");
arr2.add("actual");
arr2.add("cullet");
arr2.add("caecal");
arr2.add("alulae");
arr2.add("acetal");
arr2.add("alate");
arr2.add("caeca");
arr2.add("aceta");
arr2.add("eclat");
arr2.add("cecal");
arr2.add("lutea");
arr2.add("cella");
arr2.add("cleat");
arr2.add("tulle");
arr2.add("culet");
arr2.add("alula");
arr2.add("calla");
arr2.add("tale");
arr2.add("tace");
arr2.add("celt");
arr2.add("clue");
arr2.add("alec");
arr2.add("tell");
arr2.add("cull");
arr2.add("alae");
arr2.add("cate");
arr2.add("acta");
arr2.add("tule");
arr2.add("caca");
arr2.add("ceca");
arr2.add("tael");
arr2.add("latu");
arr2.add("lute");
arr2.add("caul");
arr2.add("cute");
arr2.add("luce");
arr2.add("cell");
arr2.add("tala");
List<String> arr2Sub = arr2.subList(1, 52);
ArrayList<String> arr3 = new ArrayList<String>();
arr3.add("virtual");
arr3.add("ritual");
arr3.add("vault");
arr3.add("virtu");
arr3.add("vital");
arr3.add("trial");
arr3.add("rival");
arr3.add("viral");
arr3.add("ultra");
arr3.add("urial");
arr3.add("trail");
arr3.add("aril");
arr3.add("vair");
arr3.add("tali");
arr3.add("virl");
arr3.add("lair");
arr3.add("rail");
arr3.add("airt");
arr3.add("vita");
arr3.add("lati");
arr3.add("vial");
arr3.add("alit");
arr3.add("tail");
arr3.add("lair");
arr3.add("rial");
arr3.add("vatu");
arr3.add("latu");
arr3.add("tirl");
arr3.add("ulva");
arr3.add("litu");
arr3.add("lira");
arr3.add("lari");
arr3.add("vail");
List<String> arr3Sub = arr3.subList(1, 32);
//input list
ArrayList<String> inputList = new ArrayList<String>();
Scanner input = new Scanner(System.in);
//to print the words for the game
int r = (int) (Math.random() * 2);
String word = wholeList.get(r);
System.out.println(word);
while (input.hasNextLine()){
String words = input.nextLine();
if (words.equalsIgnoreCase("x")){
break;
}
else{
inputList.add(words);
}
}
//check answers
ArrayList<String> validAnswers = new ArrayList<String>();
ArrayList<String> wrongAnswers = new ArrayList<String>();
ArrayList<String> notFound = new ArrayList<String>();
List<String> compare = new ArrayList<String>();
if (r == 0){
compare = arr1Sub;
}
else if (r == 1){
compare = arr2Sub;
}
else if(r == 2){
compare = arr3Sub;
}
else{
compare.add("error");
System.out.println(compare);
}
for (int i = 0; i < inputList.size(); i++){
if (compare.contains(inputList.get(i))){
validAnswers.add(inputList.get(i));
}
else if (!compare.contains(inputList.get(i))){
wrongAnswers.add(inputList.get(i));
}
else{
notFound.add(compare.get(i));
}
}
System.out.println("Valid Answers: " + validAnswers);
System.out.println("Wrong Answers: " + wrongAnswers);
output.println(wholeList.get(r));
output.println("Valid Answers: " + validAnswers);
output.println("Wrong Answers: " + wrongAnswers);
output.close();
System.out.println(" ");
System.out.println("Would you like to play again? (Y/N)");
String response = input.nextLine();
System.out.println(" ");
if (response.equalsIgnoreCase("y")){
repeatGame();
}
else if (response.equalsIgnoreCase("n")){
System.out.println(" ");
System.out.println("Thank you for playing!");
}
}
public static void repeatGame(){
try {
runGame();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Supposing that you want appending data by keeping the old written data in the file: Creating an instance of FileOutputStream(file, append) and wrapping it with PrintWriter should work:
PrintWriter writer = new PrintWriter(new FileOutputStream(myFile, true));
writer.write("a String");
writer.close();
put the creating file codez into the main before you start the game
the main would be like this
public static void main(String[] args) throws IOException{
...
File results = new File("WordlerResults.txt");
PrintWriter output = new PrintWriter(results);
runGame(output);
}
and the run game accept the output as input argument
public static void runGame(PrintWriter output) throws FileNotFoundException{
...
//also remove these two lines from here
// File results = new File("WordlerResults.txt");
// PrintWriter output = new PrintWriter(results);
}
but still the file is going to overridden for the next call(application run), so you just need to check the file exist state, and just markup the cursor to the end.
by the way don't forget to flush and close the output at the end of the programming life cycle as
output.flush();
output.close();
I have 2 files where 1(OrderCatalogue.java) reads in contents of a external file and 2(below). But I'm having the "FileNotFoundException must be caught or declard to be thrown" error for this line "OrderCatalogue catalogue= new OrderCatalogue();" and I understand that because its not in a method. But if i try puting it in a method, the code under the "getCodeIndex" and "checkOut" methods can't work with the error message of "package catalogue does not exist". Anyone has any idea how i can edit my code to make them work? Thank you!!
public class Shopping {
OrderCatalogue catalogue= new OrderCatalogue();
ArrayList<Integer> orderqty = new ArrayList<>(); //Create array to store user's input of quantity
ArrayList<String> ordercode = new ArrayList<>(); //Create array to store user's input of order number
public int getCodeIndex(String code)
{
int index = -1;
for (int i =0;i<catalogue.productList.size();i++)
{
if(catalogue.productList.get(i).code.equals(code))
{
index = i;
break;
}
}
return index;
}
public void checkout()
{
DecimalFormat df = new DecimalFormat("0.00");
System.out.println("Your order:");
for(int j=0;j<ordercode.size();j++)
{
String orderc = ordercode.get(j);
for (int i =0;i<catalogue.productList.size();i++)
{
if(catalogue.productList.get(i).code.equals(orderc))
{
System.out.print(orderqty.get(j)+" ");
System.out.print(catalogue.productList.get(i).desc);
System.out.print(" # $"+df.format(catalogue.productList.get(i).price));
}
}
}
}
And this is my OrderCatalogue file
public OrderCatalogue() throws FileNotFoundException
{
//Open the file "Catalog.txt"
FileReader fr = new FileReader("Catalog.txt");
Scanner file = new Scanner(fr);
while(file.hasNextLine())
{
//Read in the product details in the file
String data = file.nextLine();
String[] result = data.split("\\, ");
String code = result[0];
String desc = result[1];
String price = result[2];
String unit = result[3];
//Store the product details in a vector
Product a = new Product(desc, code, price, unit);
productList.add(a);
}
It seems the OrderCatalogue constructor throws FileNotFoundException. You can initialize catalogue inside Shopping constructor and catch the exception or declare it to throw FileNotFoundException.
public Shopping() throws FileNotFoundException
{
this.catalogue= new OrderCatalogue();
or
public Shopping()
{
try{
this.catalogue= new OrderCatalogue();
}catch(FileNotFoundException e)
blah blah
}