Im doing something wrong with the Excetpion in my code because when a String layout such as:
..b.
bbb. //<---Illegal
...
.x.
... //<---Illegal
..r
.rr //<---Illegal
.....
.y...
..y..
...y. //<---Illegal
is passed into the method (only one layout can be passed at one time), the method should throw an exception because String layouts for shapes must have at least one filled block in each of 0th row, 0th column, last row, and last column. The following String layouts are legal:
...e
..e.
e...
a...a
.....
.....
a....
My code only handles Exception when it sees the first and last charcters of the first line. Can smb please help me out with this method regarding throwing Exception? Thanks in advance!
public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
char[][] temp;
while(data.hasNextLine())
{
String line = data.nextLine();
height = line.length();
width++;
}
temp = new char[height][width];
Scanner data2 = new Scanner(layout);
while(data2.hasNextLine())
{
String line2 = data2.nextLine();
if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
throw new FitItException("Empty borders!");
else {
for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++) {
// System.out.println(line2.charAt(c));
if (temp[r][c] == '.') {
temp[r][c] = displayChar;
}
System.out.println(line2.charAt(temp[r][c]));
}
}
}
result = new CreateShape(height, width, displayChar, layout);
return result;
}
There are a couple of things not clear to me still, so I concentrated on parsing the layout into a two dimensional char array and checking for the constraints you specified. Hopefully that will let you adapt it to your exact needs:
public static char[][] parseShape(String layout, char displayChar) throws Exception {
int height = 0;
Scanner data = new Scanner(layout);
ArrayList<String> lines = new ArrayList<String>();
// parse layout into an array of lines to determine dimensions
while (data.hasNextLine()) {
String line = data.nextLine();
lines.add(line);
height = line.length();
}
int width = lines.size();
char[][] temp = new char[height][width];
Boolean row0 = false;
Boolean col0 = false;
Boolean rowLast = false;
Boolean colLast = false;
// parse array of lines in char array and check for constraints
for (int w = 0; w < width; w++) {
String line = lines.get(w);
for (int h = 0; h < height; h++) {
char c = line.charAt(h);
if (c == displayChar) {
// we are looking at the display characters,
// check if we're in any of rows of columns that matter
if (h == 0)
row0 = true;
if (w == 0)
col0 = true;
if (h == height - 1)
rowLast = true;
if (w == width - 1)
colLast = true;
}
temp[h][w] = c;
}
}
// if any of the constraints are not true, the layout is invalid
if(!row0) {
throw new Exception("no block in Oth row");
}
if(!col0) {
throw new Exception("no block in Oth column");
}
if(!rowLast) {
throw new Exception("no block in last row");
}
if(!colLast) {
throw new Exception("no block in last column");
}
return temp;
}
Basically we have to parse the entire layout and accumulate the constraints that are satisfied rather than checking for non-satisfaction. Only at the end will we know if they are not all satisfied.
A simpler approach might be to use regular expressions.
Your requirements can be expressed as:
at least one line must start with a non-.
at least one line must end with a non-.
the first line must contain at least one non-.
the last line must contain at least one non-.
The patterns for these can be written as:
private static final LINE_STARTS_WITH_NON_DOT =
Pattern.compile("^[^.]", Pattern.MULTILINE);
private static final LINE_ENDS_WITH_NON_DOT =
Pattern.compile("[^.]$", Pattern.MULTILINE);
private static final FIRST_LINE_CONTAINS_NON_DOT =
Pattern.compile("^\\.*[^.]");
private static final LAST_LINE_CONTAINS_NON_DOT =
Pattern.compile("[^.]\\.*$");
To ensure that each pattern matches layout, you can write:
if (!LINE_STARTS_WITH_NON_DOT.matcher(layout).find()
|| !LINE_ENDS_WITH_NON_DOT.matcher(layout).find()
|| !FIRST_LINE_CONTAINS_NON_DOT.matcher(layout).find()
|| !LAST_LINE_CONTAINS_NON_DOT.matcher(layout).find()) {
throw new FitItException("Empty borders!");
}
(Note: the above assumes that layout does not end with a newline. If it does end with a newline, then you'll need to change LINE_ENDS_WITH_NON_DOT to Pattern.compile("[^.]\n") and LAST_LINE_CONTAINS_NON_DOT to Pattern.compile("[^.]\\.*\n$").)
Related
This program is about maze recursion and I'm struggling finding out how to read the maze file and print the solved maze since I'm new in Java. Could anyone explain it to me how to call the print method from main method? Thank you in advance!
public class Maze {
private static char[][] maze;
private static int rows = 0;
private static int columns = 0;
public Maze(char[][] mazeIn) {
maze = mazeIn;
}
private static boolean valid (int r, int c) {
boolean result = false;
// check if cell is in the bounds of the matrix
if (r >= 0 && r < maze.length &&
c >= 0 && c < maze[0].length)
// check if cell is not blocked and not previously tried
if (maze[r][c] == '1')
result = true;
return result;
} // method valid
public static boolean solve (int r, int c) {
boolean done = false;
if (valid (r, c)) {
maze[r][c] = '7'; // cell has been tried
if (r == maze.length-1 && c == maze[0].length-1)
done = true; // maze is solved
else {
done = solve (r+1, c); // down
if (!done)
done = solve (r, c+1); // right
if (!done)
done = solve (r-1, c); // up
if (!done)
done = solve (r, c-1); // left
}
if (done) // part of the final path
maze[r][c] = '8';
}
return done;
} // method solve
public static void print () {
System.out.println();
for (int r=0; r < maze.length; r++) {
for (int c=0; c < maze[r].length; c++)
System.out.print (maze[r][c]);
System.out.println();
}
System.out.println();
} // method print_maze
public static void main(String[] args) throws IOException {
String fileName = "Maze.txt";
try {
String readline;
FileReader fileReader =
new FileReader(fileName);
BufferedReader br =
new BufferedReader(fileReader);
int line = 0;
while((readline = br.readLine()) != null) {
System.out.println(readline); //loads the maze
char[] charArr = readline.toCharArray();
maze[line] = charArr; // error here
line++;
}
br.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}
}
the maze.txt file looks like this
000100000000000
000100001000010
000111111111000
000100000001000
000111110001000
000000010001000
000011110001000
000010010001010
000010010000000
000010000000000
000011111110000
000000000010000
000000000010000
000001000011110
000000000010000
There are a few things I would do differently, but the important part is that you're not populating the char array with any data. While you're reading in the data, you need to populate it into the char array. Something like this would work:
int line = 0;
while((readline = br.readLine()) != null) {
System.out.println(readline); //loads the maze
char[] charArr = readline.toCharArray();
maze[line] = charArr;
line++;
}
Additionally, the maze array is never actually instantiated, and the main method is never calling "solve()" or "print()". These are things you can handle in your main method.
Finally, if you're going to call "solve()," you have to decide whether you want to instantiate an instance of the Maze class and call solve on that (which would involve quite a bit of code changes, but is the right approach), or else "solve()" should be a static method as well, which means "valid()" also has to be static.
P.S.: you have an error in your for-loop
for (int c=0; columns < maze[r].length; c++)
You should just change "columns" to "c".
P.P.S., in your solve method you're assigning ints to a char array. Put 7 and 8 in single-quotes to indicate that they're chars, not ints.
maze[r][c] = '7'; // cell has been tried
This is especially important in your valid() method, because you're testing if the maze[r][c]==1, but you should be testing if maze[r][c]=='1'.
I made all these changes myself and got this as output
000700000000000
000700007000010
000777777777000
000700000007000
000777770007000
000000070007000
000077770007000
000070070007010
000070070000000
000070000000000
000077777770000
000000000070000
000000000070000
000001000077770
000000000070000
This may be a very stupid question but I am trying to modify provided code from Sedgewick's "Algorithms" textbook for a class project. For debugging purposes I just want to print out some information to terminal at various points. Not matter where I insert System.out.println("testing") for example, I recieve no errors and the program runs to completion but nothing was ever printed out. Is it possible that the target destination for printing is not terminal for some reason?
public class LZW {
private static final int R = 256; // number of input chars
private static final int L = 4096; // number of codewords = 2^W
private static final int W = 12; // codeword width
public static void compress() {
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
while (input.length() > 0) {
String s = st.longestPrefixOf(input); // Find max prefix match s.
BinaryStdOut.write(st.get(s), W); // Print s's encoding.
int t = s.length();
if (t < input.length() && code < L) // Add s to symbol table.
st.put(input.substring(0, t + 1), code++);
input = input.substring(t); // Scan past s in input.
}
BinaryStdOut.write(R, W);
BinaryStdOut.close();
}
public static void expand() {
String[] st = new String[L];
int i; // next available codeword value
// initialize symbol table with all 1-character strings
for (i = 0; i < R; i++)
st[i] = "" + (char) i;
st[i++] = ""; // (unused) lookahead for EOF
int codeword = BinaryStdIn.readInt(W);
if (codeword == R) return; // expanded message is empty string
String val = st[codeword];
while (true) {
BinaryStdOut.write(val);
codeword = BinaryStdIn.readInt(W);
if (codeword == R) break;
String s = st[codeword];
if (i == codeword) s = val + val.charAt(0); // special case hack
if (i < L) st[i++] = val + s.charAt(0);
val = s;
}
BinaryStdOut.close();
}
public static void main(String[] args) {
System.out.println("Testing123");
if (args[0].equals("-")) compress();
else if (args[0].equals("+")) expand();
else throw new IllegalArgumentException("Illegal command line argument");
}
}
What am I doing wrong in the code by reading String.
Suppose the following String is passed as a layout:
String m = "..z\n"+
"...\n"+
"...\n"+
"...\n"+
"z..\n"+
"";
My method should return the same result but it's not returning me anything, it does not pring anything. Please do not suggest using StringBuilder or smth similar. Can smb please help me out with this?
public static Shape makeShape(String layout,char displayChar)
{
Shape result;
int height = 0;
int width = 0;
Scanner data = new Scanner(layout);
char[][] temp;
while(data.hasNextLine())
{
String line = data.nextLine();
height = line.length();
width++;
}
temp = new char[height][width];
Scanner data2 = new Scanner(layout);
while(data.hasNextLine())
{
String line2 = data.nextLine();
if(line2.charAt(0) == '.' && line2.charAt(width) == '.')
throw new FitItException("Empty borders!");
else {
for (int r = 0; r < height; r++)
for (int c = 0; c < width; c++) {
//System.out.println(line2.charAt(c));
if (temp[r][c] == '.') {
temp[r][c] = displayChar;
}
System.out.println(line2.charAt(temp[r][c]));
}
}
}
result = new CreateShape(height, width, displayChar);
return result;
}
Hint: look carefully at these two lines:
Scanner data2 = new Scanner(layout);
while(data.hasNextLine())
Do you see something wrong with ... the ... variable ... names ... ?
Given the code and string above width would be 5 or 6. No line is more than 3 so line2.charAt(width) would throw an exception?
I am trying to use the LZW code provided by Princeton and modify it to vary the size of codeword from 9 to 16 bits. I am unsure of how to do this, but was thinking of maybe using a loop since the size needs to be increased when all codewords of the size before were used. I am just looking for a useful direction to go in, since this is an assignment that I am having trouble starting.
public class LZW {
private static final int R = 256; // number of input chars
private static final int L = 4096; // number of codewords = 2^W
private static final int W = 12; // codeword width
public static void compress() {
String input = BinaryStdIn.readString();
TST<Integer> st = new TST<Integer>();
for (int i = 0; i < R; i++)
st.put("" + (char) i, i);
int code = R+1; // R is codeword for EOF
while (input.length() > 0) {
String s = st.longestPrefixOf(input); // Find max prefix match s.
BinaryStdOut.write(st.get(s), W); // Print s's encoding.
int t = s.length();
if (t < input.length() && code < L) // Add s to symbol table.
st.put(input.substring(0, t + 1), code++);
input = input.substring(t); // Scan past s in input.
}
BinaryStdOut.write(R, W);
BinaryStdOut.close();
}
public static void expand() {
String[] st = new String[L];
int i; // next available codeword value
// initialize symbol table with all 1-character strings
for (i = 0; i < R; i++)
st[i] = "" + (char) i;
st[i++] = ""; // (unused) lookahead for EOF
int codeword = BinaryStdIn.readInt(W);
if (codeword == R) return; // expanded message is empty string
String val = st[codeword];
while (true) {
BinaryStdOut.write(val);
codeword = BinaryStdIn.readInt(W);
if (codeword == R) break;
String s = st[codeword];
if (i == codeword) s = val + val.charAt(0); // special case hack
if (i < L) st[i++] = val + s.charAt(0);
val = s;
}
BinaryStdOut.close();
}
public static void main(String[] args) {
if (args[0].equals("-")) compress();
else if (args[0].equals("+")) expand();
else throw new IllegalArgumentException("Illegal command line argument");
}
}
I'm writing a method that checks to see if the text file being passed into the constructor of my instantiable class contains non-numeric data. Specifically, it matters if the data cannot be represented as a double. That is, chars are not okay, and integers are.
What I have so far is:
private boolean nonNumeric(double[][] grid) throws Exception {
boolean isNonNumeric = false;
for (int i = 0; i < grid.length; i++)
for (int j = 0; j < grid[i].length; j++) {
if (grid[i][j] != ) {
isNonNumeric = true;
throw new ParseException(null, 0);
} else {
isNonNumeric = false;
}
}
return isNonNumeric;
}
I cannot seem to find what I should be checking the current index of grid[i][j] against. As I understand it, typeOf only works on objects.
Any thoughts? Thank you.
Edit: Here is the code used to create the double[][] grid:
// Create a 2D array with the numbers found from first line of text
// file.
grid = new double[(int) row][(int) col]; // Casting to integers since
// the dimensions of the
// grid must be whole
// numbers.
// Use nested for loops to populate the 2D array
for (int i = 0; i < row; i++)
for (int j = 0; j < col; j++) {
if (scan.hasNext()) {
grid[i][j] = scan.nextDouble();
count++;
}
}
// Check and see if the rows and columns multiply to total values
if (row * col != count) {
throw new DataFormatException();
}
I come up with this sample for you, hope it helps.
It helps you to narrow down your entries types to any type that you are looking for.
My entry.txt include :
. ... 1.7 i am book 1.1 2.21 2 3222 2.9999 yellow 1-1 izak. izak, izak? .. -1.9
My code:
public class ReadingJustDouble {
public static void main(String[] args) {
File f = new File("C:\\Users\\Izak\\Documents\\NetBeansProjects"
+ "\\ReadingJustString\\src\\readingjuststring\\entry.txt");
try (Scanner input = new Scanner(f);) {
while (input.hasNext()) {
String s = input.next();
if (isDouble(s) && s.contains(".")) {
System.out.println(Double.parseDouble(s));
} else {
}
}
} catch (Exception e) {
}
}
public static boolean isDouble(String str) {
double d = 0.0;
try {
d = Double.parseDouble(str);
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
}
Output:
1.7
1.1
2.21
2.9999
-1.9
Note: my sources are as follows
1.http://www.tutorialspoint.com/java/lang/string_contains.htm
2.How to check if a String is numeric in Java