I am running a 4*4 maze all possible solution finding programme.
I have set up a method that takes a random combination Value of"R, G, B, Y" as aStrin and checks if the given String is a valid solution or not. for instance, the given String is "RGGGBYYBBGYBGRR".
new Thread(() -> {
//List<String> temp1 = new ArrayList<>();
String[] letters = {"R","G","B","Y"};
int done = 0;
Cell start = MazeBuilder.mazeFor(REPO_NAME);
while (done != 1) {
String str = "";
int r = ThreadLocalRandom.current().nextInt(10, 48);
//done = check(temp1, letters, done, start, str, r);
for (int j = 0; j < r; j++) {
Random rnd = new Random();
int index = rnd.nextInt(letters.length);
str += letters[index];
}
if (Helper.isValidSolution(start, str)) {
done = 1;
try {
FileWriter FW = new FileWriter("ansGrid.txt");
FW.write(str);
FW.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
so my question is... if the programme crashes or it runs out of memory, how can I store the values of the temp1 variable in a file?
Related
Hi for my HW I am suppose to read a text file of '.' and 'x' representing cells in Conway's Game of Life. I'm having trouble with reading the given text input and adding it into my double integer arrays. Specifically the rowcounter and columncounter part I'm sure there is a better way to do it but when I tried for loops it only read one row. I included previous parts of the code just in case. Thanks.
// Initiate file
File inputfile = new File(inputfilename);
try {
input = new Scanner(inputfile);
} catch (Exception ie) {
}
// Get array size
int[] arraysize = new int[2];
while (input.hasNextInt()) {
for (int i = 0; i < 2; i++) {
int token = input.nextInt();
arraysize[i] = token;
}
}
//System.out.println(Arrays.toString(arraysize));
// Create Array
int[][] newarray = new int[arraysize[0]][arraysize[1]];
//System.out.println(Arrays.deepToString(newarray));
// Read initial
int rowcounter = 0;
int columncounter = 0;
while (input.hasNextLine()) {
Scanner inputtoken = new Scanner(input.nextLine());
while (inputtoken.hasNext()) {
String token = inputtoken.next();
//System.out.print(token);
char xchar = token.charAt(0);
if (xchar == 'x') {
newarray[rowcounter][columncounter] = 1;
} else {
newarray[rowcounter][columncounter] = 0;
//System.out.print(rowcounter);
}
columncounter = columncounter + 1;
//System.out.print(columncounter);
}
columncounter = 0;
System.out.println();
rowcounter = rowcounter + 1;
//System.out.print(rowcounter);
}
System.out.println(Arrays.deepToString(newarray));
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
When I am referencing lines as stringArray[i+2] (I mean, there was a problem with [i+1] as well), I get the ArrayIndexOutOfBoundsException. is there any way that I can safely reference those lines without the possibility of attempting to call an index that does not exist, without fundamentally changing my code?
import java.io.*;
import java.util.Scanner;
public class Test {
public static void main(String [] args) {
/** Gets input from text file **/
//defines file name for use
String fileName = "temp.txt";
//try-catches for file location
Scanner fullIn = null;
try {
fullIn = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("File Error : ");
}
Scanner in = null;
try {
in = new Scanner(new FileReader(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error: File " + fileName + " has not been found. Try adjusting the file address or moving the file to the correct location." );
e.printStackTrace();
}
//finds the amount of blocks in the file
int blockCount = 0;
for (;in.hasNext() == true;in.next()) {
blockCount++;
}
//adding "" to every value of stringArray for each block in the file; created template for populating
String[] stringArray = new String[blockCount];
for (int x = 0; x == blockCount;x++) {
stringArray[x] = "";
}
//we are done with first scanner
in.close();
//populating array with individual blocks
for(int x = 0; x < blockCount; x++) {
stringArray[x]=fullIn.next();
}
//we are done with second scanner
fullIn.close();
//for later
Scanner reader;
boolean isLast;
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
if (stringArray.length != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
if (currWord.equalsIgnoreCase("say") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)) {
System.out.println(nextWord.substring(1, nextWord.length()-1));
}
if (currWord.equalsIgnoreCase("say") && isFileThere.isFileThere(nextWord) == true){
System.out.println(VariableAccess.accessIntVariable(nextWord));
}
if (currWord.equalsIgnoreCase("lnsay") && nextWord.startsWith(quotes) && nextWord.endsWith(quotes)){
System.out.print(nextWord.substring(1, nextWord.length()-1) + " ");
}
if (currWord.equalsIgnoreCase("get")) {
reader = new Scanner(System.in); // Reading from System.ins
Variable.createIntVariable(nextWord, reader.nextInt()); // Scans the next token of the input as an int
//once finished
reader.close();
}
if (currWord.equalsIgnoreCase("int") && thirdWord.equalsIgnoreCase("=")) {
String tempName = nextWord;
try {
int tempVal = Integer.parseInt(fourthWord);
Variable.createIntVariable(tempName, tempVal);
} catch (NumberFormatException e) {
System.out.println("Integer creation error");
}
}
}
}
}
}
The problem is that you are looping over the entire stringArray. When you get to the last elements of the stringArray and this
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
executes, stringArray[nextNew + 2] will not exist because you are at the end of the array.
Consider shortening your loop like so
for (int i = 0; i < stringArray.length - 3; i++) {
Since you are already checking for last word, all you have to is move these 4 lines of code:
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
in your:
if (isLast == false) {
That should solve your problem. Also you should check for length - 1 and not length to check the last word.
for (int i = 0; i < stringArray.length; i++) {
isLast = true;
String currWord = stringArray[i].trim();
if (stringArray.length-1 != i) {
isLast = false;
}
String quotes = "\"";
if (isLast == false) {
int nextNew = i+1;
String nextWord = stringArray[nextNew].trim();
String thirdWord = stringArray[nextNew+1].trim();
String fourthWord = stringArray[nextNew+2].trim();
// rest of the code
I have 6 columns in one table and one of the column contains Chinese character and I have 200 records in that table.
I have written the code to save it one text file. The problem is while fetching all records, I am able to see the chinese text in the file. But while fetching only one record I am seeing the Chinese text is garbled.
I am using the below code.
public static void main(String args[]){
String outputFile = fileNameEncode("C:\\a\a.txt");
FileOutputStream os = new FileOutputStream(outputFile);
writeToFile(os);
}
private static String fileNameEncode(String name) {
String file;
try {
byte[] utf_byte = name.getBytes("UTF-8");
StringBuilder sb = new StringBuilder(1024);
for (byte b : utf_byte) {
int integer = b & 0xFF; // drop the minus sign
sb.append((char) integer);
}
file = sb.toString();
} catch (Exception e) {
file = name;
}
return file;
}
public void writeToFile(FileOutputStream os) {
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ostream, "GBK")));
for (int rowNum = 0; rowNum < arrayList.size(); rowNum++) {//arrayList contains data from db
ArrayList list = arrayList.get(rowNum);
for(int k = 0; k < list.size(); k++{
String[] data = new String[6];
for (int colNum = 0; colNum < 6; colNum++) {
data[colNum] = list.get(i).toString();
}
String outLine = composeLine(data, ctlInfo);
// write the line
pw.print(outLine);
pw.println();
}
}
}
private static String composeLine(String[] data, ControlInfo ctl) {
StringBuilder line = new StringBuilder();
String delim = ","
int elemCount = data.length;
for (int i = 0; i < elemCount; i++) {
if (i > 0)
line.append(delim);
if (data[i] != null && (data[i].contains("\n") || data[i].contains("\r") ||
data[i].contains("\r\n"))){
data[i] = data[i].replaceAll("(\\t|\\r?\\n)+", " ");
}
else {
line.append(data[i]);
}
}
return line.toString();
}
could you please let me know where I am wrong?
I found the issue, the code is good, the problem is in notepad++. If the character set in node pad ++ is Chinese(GB2312) then I am able to see the correct text. The note pad ++ is auto set GB2312 for two lines but for one line it is not doing auto set to GB2312.
When I convert my Java project into a Jar file, an ArrayIndexOutOfBounds exception of -2 occurs in line 3 of this section of code:
for (int i = 0; i < copy.get(copy.size() - 2).size(); i++) {
if (!copy.get(copy.size() - 2).get(i).toString().equals(" ")) {
startLocations[index] = Integer.parseInt(copy.get(copy.size() - 2).get(i).toString());
index++;
}
}
I find this very strange because the program runs perfectly fine in Eclipse, and the size of copy, a 2D ArrayList tempoarily holding the grid of a maze is 9. The code fails when I convert it to a Jar and I run it from cmd. Here is the full relevant code below. All the files are in their correct locations.
String fileName = "maze.txt";
String line = null;
ArrayList < ArrayList < Square >> grid = new ArrayList < ArrayList < Square >> ();
try {
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int row = 0;
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null) {
ArrayList < Square > lineList = new ArrayList < Square > ();
for (int i = 0; i < line.length(); i++) {
String letter = Character.toString(line.charAt(i));
if (letter.equals("L")) {
lineList.add(new LockedSquare(row, i, letter));
} else {
lineList.add(new Square(row, i, letter));
}
row++;
}
grid.add(lineList);
}
// Cut down grid to only the maze
ArrayList < ArrayList < Square >> copy = grid;
int length = grid.size();
grid = new ArrayList < ArrayList < Square >> ();
for (int i = 0; i < length - 2; i++) {
grid.add(copy.get(i));
}
// Start position
int[] startLocations = new int[2];
int index = 0;
for (int i = 0; i < copy.get(copy.size() - 2).size(); i++) {
if (!copy.get(copy.size() - 2).get(i).toString().equals(" ")) {
startLocations[index] = Integer.parseInt(copy.get(copy.size() - 2).get(i).toString());
index++;
}
}
int playerX = startLocations[0];
int playerY = startLocations[1];
}
// Exceptions
catch (FileNotFoundException e) {
System.out.println("Error: maze.txt not found");
} catch (IOException ex) {
System.out.println("Error reading maze.txt");
}
This is happening because your jar file is unable to find maze.txt .
change String fileName = "maze.txt";
to
String fileName = <absolute-path-for-maze.txt> ; and it should be through in jar
Woops. I was so stupid. My maze.txt file in the same folder as my JAR has no content in it.
I am having issues with this program. I cannot get it to read more than the first line of code in the dictionary file. The dictionary file has around 22000 words. If someone could figure this out that would be great. I then could move along with the rest of my code.
public class Program2 {
private String[] array;
private String[] array2;
public void readFile(){
File f = new File ("dictionary.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String word = input.nextLine();
String[] wordarray = word.split(" ");
array[i] = wordarray[i];
i++;
for (i = 0 ; i<array.length; i++)
System.out.println(array[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public void readFile2(){
File f = new File ("oliver.txt");
try {
Scanner input = new Scanner (f);
int i = 0;
array = new String [10];
while (i<array.length && input.hasNext()){
String book = input.nextLine();
String[] bookarray = book.split(" ");
array2[i] = bookarray[i];
i++;
for (i = 0 ; i<array2.length; i++)
System.out.println(array2[i]);
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
}
public int binarysearchrecursive(double key, int first, int last) {
int mid;
if (first > last) {
return -1;
}
mid = (first + last) / 2;
if (key == wordArray[mid]) {
return mid;
} else if (key < wordArray[mid]) {
return binarysearchrecursive(key, first, mid - 1);
} else {
return binarysearchrecursive(key, mid + 1, last);
}
}
}
Ok, as someone commented, I think the problem is in the loops :P
This is what we want to do when we read all the words:
Create an ArrayList (better than Array, because you don't know exactly how many words you have in the text file).
Then create a double loop (1 while + 1 for) which goes through the file and stores strings in that ArrayList
The loops will go through all the lines, and then add every word in the line to the ArrayList (using the split on " " like you are trying).
So:
public ArrayList<String> readFile(){
File f = new File ("dictionary.txt");
ArrayList<String> array = new ArrayList<String>();
try {
Scanner input = new Scanner (f);
while (input.hasNext()){
//Goes through all lines
String line = input.nextLine();
//Array of all words:
String[] wordArray = line.split(" ");
//Goes through all words:
for(String str : wordArray){
array.add(str);
}
}
input.close();
}//try
catch (IOException e) {
e.printStackTrace();
}
return array;
}