Boolean 2d array text file - java

I need to read a series of # and blank spaces from a text file and print it as a maze.
public static void readMaze() throws FileNotFoundException{
String fileName = "path/maze.txt";
Scanner input = new Scanner(new File(fileName));
int x = 0;
String columns = "";
while (input.hasNextLine()){
x++;
columns = input.nextLine();
}
int col = columns.length();
boolean maze[][] = new boolean[x][col];
}
So I have got the number of rows(x) and the number of columns which the maze will have.
Next step is to create a boolean array with a true value for each "#" and false for each blank space in the file and I am not sure how to do this.
while (input.hasNextLine()){
columns = input.nextLine();
for (int c = 0; c < columns.length();c++){
if (c == '#'){
add true;
}
else{
add false;
}
}
}
So that is the next part, but I am not sure wht I need to put in the for loop, guidance would be appreciated.

The only missing part of your puzzle is this
int row = 0;
while (input.hasNextLine()){
columns = input.nextLine();
for (int c = 0; c < columns.length();c++){
c = columns.charAt(c);
if (c == '#'){
result[row, c] = true;
}
else{
result[row, c] = false; // not even needed, false is the default value ;)
}
row ++;
}

Should be better with something like :
ArrayList<Boolean> returnArray = new ArrayList<Boolean>()
for (int c = 0; c < columns.length();c++){
if (columns[c].equals("#")){
returnArray.add(true);
}
else{
returnArray.add(false);
}
}
return returnArray.hasArray();

int i = 0;
while(input.hasNextLine())
{
row = input.nextLine();
String[] row_temp = row.split("(?!^)");
int row_length = row_temp.length();
for(int j=0; j<row_length; j++){
if(row_temp[j].matches("#")){
maze[i][j] = true;
}
else{
maze[i][j] = false;
}
}
i++;
}

Related

How do I get rid of java.lang.NumberFormatException error

This code takes two txt files, reads them puts them in 2d arrays and should check if the numbers in the files are magic squares but it keeps returning NumberFormatException error. I'm new to java so if anyone could help me that would be great. I'm pretty sure the problem come from the txt file being string and the 2d array needing to be in int form. But how and where do I make that conversion on my code?
this is what i have:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class ms {
public static void main(String[] args) throws FileNotFoundException {
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
int nos[][] = null;
nos = getArray(filename1);
boolean b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
System.out.println("\n");
nos = getArray(filename2);
b = isMagicSquare(nos);
printArray(nos);
if (b) {
System.out.println("It is a magic Square");
} else {
System.out.println("It is not a magic Square");
}
}
private static int[][] getArray(String filename) throws FileNotFoundException {
String line;
int nos[][] = null;
int size = 0, rows = 0;
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
if (!sc.nextLine().isEmpty())
size++;
}
sc.close();
nos = new int[size][size];
sc = new Scanner(new File(filename));
while (sc.hasNext()) {
line = sc.nextLine();
if (!line.isEmpty()) {
String arr[] = line.split("\t");
for (int i = 0; i < arr.length; i++) {
nos[rows][i] = Integer.valueOf(arr[i]);
}
rows++;
}
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println(e);
}
return nos;
}
private static void printArray(int[][] nos){
for(int i = 0; i<nos[0].length;i++) {
for (int j = 0; j < nos[0].length; j++){
System.out.printf("%-3d",nos[i][j]);
}
System.out.println();
}
}
private static boolean isMagicSquare(int[][] square) {
boolean bool = true;
int order = square.length;
int[] sumRow = new int[order];
int[] sumCol = new int[order];
int[] sumDiag = new int[2];
Arrays.fill(sumRow, 0);
Arrays.fill(sumCol, 0);
Arrays.fill(sumDiag, 0);
for (int row = 0; row < order; row++){
for (int col = 0; col < order; col++) {
sumRow[row] += square[row][col];
}
}
for (int col = 0; col < order; col++) {
for (int row = 0; row < order; row++) {
sumCol[col] += square[row][col];
}
}
for (int row = 0; row < order; row++) {
sumDiag[0] += square[row][row];
}
for (int row = 0; row < order; row++) {
sumDiag[1] += square[row][order - 1 - row];
}
bool = true;
int sum = sumRow[0];
for (int i = 1; i < order; i++) {
bool = bool && (sum == sumRow[i]);
}
for (int i = 0; i < order; i++) {
bool = bool && (sum == sumCol[i]);
}
for (int i = 0; i < 2; i++) {
bool = bool && (sum == sumDiag[i]);
}
return bool;
}
}
SUGGESTION:
Substitute nos[rows][i] = Integer.valueOf(arr[i]); for a custom method that will tell you WHERE the error is occurring.
EXAMPLE:
public static Integer tryParse(String text, int row, int i) {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
System.out.println("ERROR: row=" + row + ", i=" + i + ", text=" + text);
return null;
}
}
CAVEAT: This is for helping you troubleshoot ONLY. You definitely wouldn't want to release this in "production code" ;)
What is the NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
Offtopic:
A thing that i can notice is that both filesnames have the same name. So you will verify the same file 2 times.
String filename1 = "magicSquaresData.txt", filename2 = "magicSquaresData.txt";
I checked your program and you error appears when you put like this on a file:
1. 5 5
2. 5 5
So the error shows beacause you are trying to parse to int the String "5 5". So your code pick the all line and tries to convert to int and " " it's not an int. And there lives the NumberFormatException error.
How do to solve it?
The function that we will work on is the one that you pass from file to an array in
private static int[][] getArray(String filename) throws FileNotFoundException{
The of the function is after we read the file.
As you said, you are leading with a 2d array so to insert all the numbers we need to have loops for each dimension on the array.
So we will start from there.
I will use a while beacause we are dealing with a string and it's easier to verify the text that its left on the line. Will add a new int variable that starts in 0 to pass in every column of a line to use with the while loop. And with this we got this:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
whileIterator++;
}
whileIterator = 0;
}
Next setep, we will divide in 2 behaviors because we will substring the String that has in the line, and will work differently when it's the last number that we are verifying:
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need in a line
}else{//All other iterations
whileIterator++;
}
whileIterator = 0;}
To finalize let's add the new logic to insert in nos array. So lets pick all line for example 2 7 6 and we want to add the number 2, so lets do that. You just need to substring(int startIndex, int finalIndex) the line and add to the nos array. After that let remove the number and the space ("2 ") from the line that we are veryfying.
for (int i = 0; i < lines.length; i++) {
while(!"".equals(line)){
if(whileIterator + 1 == size){//If its the last iteration that we need
nos[rows][whileIterator] = Integer.parseInt(line.substring(0));//Add to array
line = "";//To not pass the while verification
}else{//All other iterations
nos[rows][whileIterator] = Integer.parseInt(line.substring(0, line.indexOf(" ")));//Add to array
line = line.substring(line.indexOf(" ") + 1);//remove the number we added behind
}
whileIterator++;
}
whileIterator = 0;}
And here you go, that how you add the numbers to an array and don't get the error.
If you need some further explanation just ask. Hope it helps :)

Making a big array out of other arrays and IF FALSE making it smaller

I've been working on this program that creates a password, it has 4 char arrays where i have all the characters i can use for the password, and a method that evaluates if the user wants to use them or not, the problem is that it only works when all the arrays are "true"(they are used), because the last array is composed of 73 spaces that are filled with the other arrays.
The problem is that if the user doesnt want to use one of them, when the for loop cycles through the array it will mostly fall on an index number that is empty breaking the code, i cant think of a way of getting over that
package javaapplication19;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
public class JavaApplication19 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
char [] leterSmall = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','ñ','o','p','q','r','s','t','u','v','w','x','y','z'};
char[] leterBig = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','Ñ','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
char[] numbers = {'0','1','2','3','4','5','6','7','8','9'};
char [] charsRandom = {'?','¿','.',';','+','-','*','/','|'};
char [] arrayFinal = new char[73];
boolean smallOption = false;
boolean bigOption= false;
boolean numbersOption= false;
boolean charactersOption= false;
System.out.println("Do you want to use small leters?");
String answer1 = sc.next();
if( opcionmenu(answer1)==true){
smallOption = true;
for(int i=0;i<27;i++){
arrayFinal[i]=leterSmall[i];
}
}
System.out.println("Do you want to use big leters?");
String answer2 = sc.next();
if( opcionmenu(answer2)==true){
bigOption = true;
for(int i=27;i<54;i++){
arrayFinal[i]=leterBig[i-27];
}
}
System.out.println("Do you want to use numbers?");
String answer3 = sc.next();
if( opcionmenu(answer3)==true){
numbersOption = true;
for(int i=54;i<64;i++){
arrayFinal[i]=numbers[i-54];
}
}
System.out.println("Do you want to use symbols?");
String answer4 = sc.next();
if( opcionmenu(answer4)==true){
charactersOption = true;
for(int i=64;i<73;i++){
arrayFinal[i]=charsRandom[i-64];
}
}
for(int i=0;i<16;i++){
int y = ThreadLocalRandom.current().nextInt(0,73 + 0 );
System.out.print(arrayFinal[y]);
}
}
static boolean opcionmenu(String stra){
if(stra.equals("Yes")) {
return true;
}
else{
return false;
}
}
}
When building arrayFinal, keep track of how many values you've added, and only add a value right after a previous value.
Like this, where len is the number of characters added to arrayFinal:
int len = 0;
if (smallOption) {
for (char c : leterSmall) {
arrayFinal[len++] = c;
}
}
if (bigOption) {
for (char c : leterBig) {
arrayFinal[len++] = c;
}
}
if (numbersOption) {
for (char c : numbers) {
arrayFinal[len++] = c;
}
}
if (charactersOption) {
for (char c : charsRandom) {
arrayFinal[len++] = c;
}
}
ThreadLocalRandom rnd = ThreadLocalRandom.current();
for (int i = 0; i < 16; i++) {
System.out.print(arrayFinal[rnd.nextInt(len)]);
}
You can use System.arraycopy() method to . avoid this problem .
such as
int length = 0 ;
if( opcionmenu(answer2)==true){
System.arraycopy(leterBig ,0 ,arrayFinal,length,leterBig.length);
length = length + leterBig.length ;
}
// and so on
for(int i=0;i<16;i++){
int y = ThreadLocalRandom.current().nextInt(0,length );
System.out.print(arrayFinal[y]);
}

How to read a textfile in java?

How to select numbers from a line by line text file that has both text and numbers?
For example:
[10] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou
I want to only have 0 1 2 25 21 35 printed out without the [10]. But I keep getting 10012252135.
This is my code
try {
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String i = scan.nextLine();
String final_string = "";
for (int j = 0; j < i.length(); j++) {
char myChar = i.charAt(j);
if (Character.isDigit(myChar)) {
final_string = final_string.concat(Character.toString(myChar));
}
}
System.out.println(final_string);
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String tt = "[10] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
tt = tt.replaceAll("\\[.*\\]",""); // IT get rid of any [AnyNumber]
tt = tt.replaceAll("\\D+",""); // It get rid of any char that is not a letter
System.out.println(tt);
I made a regex I can't make it one line but the output is the disered.
OutPut
012252135
I like the answer from Reaz Murshed,
but just in case you have multiple occurenses of number enclosed in "[]" you might filter those by remembering if you are currently in just an enclosed scope or not:
char NON_NUMERIC_SCOPE_START = '[';
char NON_NUMERIC_SCOPE_END = ']';
try {
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String i = scan.nextLine();
String final_string = "";
boolean possibleNumericScope = true;
for (int j = 0; j < i.length(); j++) {
char myChar = i.charAt(j);
if (myChar == NON_NUMERIC_SCOPE_START) {
possibleNumericScope = false;
} else if (myChar == NON_NUMERIC_SCOPE_END && !possibleNumericScope) {
possibleNumericScope = true;
} else if (Character.isDigit(myChar) && possibleNumericScope) {
final_string = final_string.concat(Character.toString(myChar));
}
}
System.out.println(final_string);
}
scan.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
I think the first portion is the line number which can be easily ommited by splitting your String by space. Please try the following code.
String i = "[10] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
String final_string = "";
// Split the String with space to remove the first portion which
// might be indicating the line number or something like that.
String[] splittedArray = i.split(" ");
// Then just run the loop in the second item of the split
// `String` array.
int contCount = 0;
for (int j = 0; j < splittedArray[1].length(); j++) {
char myChar = splittedArray[1].charAt(j);
if (Character.isDigit(myChar)) {
contCount = 0;
final_string = final_string.concat(Character.toString(myChar));
} else {
if (contCount == 0)
final_string = final_string + " ";
contCount++;
}
}
System.out.println(final_string);
I added a line to get rid of [line-number] before the loop:
i = i.substring(i.indexOf("]")+1);
for (int j = 0; j < i.length(); j++) {
This should do the trick.
If you always have the [10], then you can just edit your final_string to be everything but the first two numbers. Change System.out.println(final_string) to System.out.println(final_string.substring(2)). Then, if you need spaces, type final_string += " "; in your if statement of the for loop.
Try this:
String y = "[133] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
String result = y.replaceAll("\\[[0-9]*\\]|[a-zA-Z-]*", "");
Or
String y = "[133] begin0-1-selp-2-yelp-25-jelp-21-hi-35-ou";
String result = y.replaceAll("\\[[\\d]*\\]|[^\\d]", "");
Many ways to do this :)

Filling a 2d character array from a file in java

I'm a beginner in java and I am trying to fill a 2d character array from an input file. To do this I constructed a method which takes in a 2d character array as a parameter variable, then reads the file and stores it as a character array. So far I have done everything except fill the array, as when I run the code the program throws a NoSuchElement exception. If anyone could help me with this I would greatly appreciate it.
public static char [][] MakeWordArray (char [][] givenArray)
{
try
{
File wordFile= new File ("words.txt");
Scanner in= new Scanner (wordFile);
int rows =0;
int col=0;
while (in.hasNextLine())
{
rows = rows + 1;
col = col + 1;
in.next();
}
char [][] words = new char [rows][col];
File wordFile2= new File ("words.txt");
Scanner in2= new Scanner(wordFile2);
for ( int i = 0; i < rows; i++)
{
for (int j = 0; j < col; j++)
{
String wordly = in2.nextLine();
words [i][j] = wordly.charAt(i);
}
}
return words;
}
catch (FileNotFoundException e)
{
System.out.println("File Does Not Exist");
}
return null;
}
I think your counting methods have some problems.
If you want to count how many lines your .txt have:
int counter = 0;
while (in.hasNextLine())
{
counter++;
in.nextLine();
}
If you want to count how many char your .txt have:
int counterWithoutSpace = 0, counterWithSpace = 0;
while (in.hasNextLine())
{
String line = in.nextLine();
Scanner inLine = new Scanner(line);
while (inLine.hasNext())
{
String nextWord = inLine.next();
counterWithoutSpace += nextWord.length();
counterWithSpace += nextWord.length() + 1;
}
counterWithSpace--;
}
If you want to count how many char you have on each line, I recommend ArrayList. Because the size of your array is dynamic.
Note that you can also you can use the char counter logic above with List too.See as follows:
List<Integer> arr = new ArrayList<Integer>();
while (in.hasNextLine())
{
arr.add(in.nextLine().length());
}
And if you realy needs the static array, you can use:
Integer[] intArr = arr.toArray(new Integer[0]);
You can transform its entire function as below to get a list of every Character of the .txt:
List<Character> arr = new ArrayList<Character>();
while (in.hasNextLine())
{
String line = in.nextLine();
for (char c : line.toCharArray())
{
arr.add(c);
}
}
Try using a do while loop instead of the while
do
{
rows=rows+1;
col=lol+1;
in.next();
}
while(in.hasNext());
There are multiple questions here.
1) Why did you provide a char[][] parameter when you are not even using it?
2) Why are you using two files when all you need to do is read from a file and convert it in 2d Array?
3) The method name should follow camel casing convention.
From what i understood from your question, This is a code i've tried.
NOTE- because the requirement is of an Array and not dynamic datatypes like List ArrayList etc., the data entered into char array might be lost
Saying that here is what works.
public class StackOverflow{
public static char [][] makeWordArray ()
{
try{
File f = new File("C:\\docs\\mytextfile.txt");
Scanner scan = new Scanner(f);
int row = 0, col = 0;
String readData = "";
while(scan.hasNextLine()){
readData += scan.nextLine();
row++;
}
double range = (readData.length()/row);
col = (int)Math.ceil(range);
char[][] arr = new char[row][col];
int count = 0;
for (int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
arr[i][j] = readData.charAt(count++);
System.out.println("Pos: ["+ i +"][" + j + "]" + arr[i][j]);
}
}
return arr;
}
catch(FileNotFoundException fe){
System.err.println(fe.getMessage());
return null;
}
}
public static void main(String[] arg){
char[][] myarr = StackOverflow.makeWordArray();
//print your array
}
}

Why is there StringOutofBoundException?

My code needs to read information from the textfile. And the textfile looks like this:
X...................
....................
....................
....................
....................
....................
....................
....................
....................
..X.................
Yes, I need to get # of rows and columns and also identify the number and location of 'X's. I'm almost done except my second constructor is giving me a StringOutOfBoundException in the line:
treasureLocations[location] = new Coord(i, j);
I need help only with the second constructor. Could smb please help me with that?
import java.util.Scanner; // Required to get input
import java.io.File; // Required to get input from files
// A 2D treasure map which stores locations of treasures in an array
// of coordinates
public class TreasureMap{
int rows, cols; // How big is the treasure map
Coord [] treasureLocations; // The locations of treasures
Scanner kbd = new Scanner(System.in);
// Prompt the user for info on the treasure map and then create it
// COMPLETE THIS METHOD
public TreasureMap(){
int numberOfTreasures = 0;
System.out.println("Enter map size (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
System.out.println("Enter number of treasures (1 int): ");
numberOfTreasures = kbd.nextInt();
treasureLocations = new Coord[numberOfTreasures];
for (int i = 0; i < numberOfTreasures; i++)
{
System.out.println("Enter treasure " + i + " location (2 ints): ");
rows = kbd.nextInt(); cols = kbd.nextInt();
treasureLocations[i] = new Coord(rows, cols);
}
}
// Read the string representation of a map from a file
// COMPLETE THIS METHOD
public TreasureMap(String fileName) throws Exception{
rows = 0;
cols = 0;
int treasures = 0;
char x = 'X';
Scanner data = new Scanner(new File(fileName));
while(data.hasNextLine())
{
String line = data.nextLine();
for (int i = 0; i < line.length(); i++)
{
if(x == line.charAt(i))
{
treasures++;
}
}
cols = line.length();
rows++;
}
int location = 0;
treasureLocations = new Coord[treasures];
Scanner temp = new Scanner (new File(fileName));
while(temp.hasNextLine())
{
String line = temp.nextLine();
for(int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
}
}
// true if there is treasure at the given (r,c) coordinates, false
// otherwise
// This method does not require modification
public boolean treasureAt(int r, int c){
for(int i=0; i<treasureLocations.length; i++){
Coord coord = treasureLocations[i];
if(coord.row == r && coord.col == c){
return true;
}
}
return false;
}
// Create a string representation of the treasure map
// This method does not require modification
public String toString(){
String [][] map = new String[this.rows][this.cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
map[i][j] = ".";
}
}
for(int i=0; i<treasureLocations.length; i++){
Coord c = treasureLocations[i];
map[c.row][c.col] = "X";
}
StringBuilder sb = new StringBuilder();
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
sb.append(map[i][j]);
}
sb.append("\n");
}
return sb.toString();
}
}
You should not use the for i as you do. Your i means the current row, doesn't it? So every time you input a line(temp.nextLine()), your i must be added one.
int i=0;
while(temp.hasNextLine())
{
String line = temp.nextLine();
for (int j = 0; j < cols; j++)
{
if(x == line.charAt(j))
{
treasureLocations[location] = new Coord(i, j);
location++;
}
}
}
++i;
}

Categories

Resources