NullPointerException, Reservation Seat using Array [duplicate] - java

This question already has answers here:
java multi-dimensional array fails with a nullpointerexception
(3 answers)
Closed 3 years ago.
can someone look into this code? I have been receiving this error
Exception in thread "main" java.lang.NullPointerException
at project.Project.IsOccupied(Project.java:80)
at project.Project.ReserveSeat(Project.java:51)
at project.Project.main(Project.java:142)
I don't know what's wrong I've done. I have been doing a reservation seat using an array. I'm trying to reserve a seat and check if the seat number entered is occupied or if all the seats are occupied.
package project;
import java.util.*;
import java.io.*;
public class Project {
static String MSR[][] = new String [10][3], Name, SeatNo, Reserved;
static Scanner user = new Scanner(System.in);
static boolean IsEmpty(){
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if (MSR[i][1] != null) {
return false;
}
}
}
return true;
}
static boolean IsFull(){
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if ((MSR[i][2]) == null) {
return false;
}
}
}
return true;
}
static void ReserveSeat()throws IOException{
PrintWriter save = new PrintWriter("MovieSeats.txt");
if(IsFull()){
System.out.println("All seats are occupied");
}
else {
System.out.print("Enter seat number to reserved: ");
SeatNo = user.next();
if (IsOccupied(SeatNo)) {
int RSeatNo = Integer.parseInt(SeatNo);
MSR[RSeatNo][1]=SeatNo;
save.print(SeatNo);
System.out.print("Enter name: ");
Name=user.next();
MSR[RSeatNo][0]=Name;
save.print(Name);
Reserved="X";
MSR[RSeatNo][2]=Reserved;
save.print(Reserved);
}
else {
System.out.println("Seat is occupied");
}
}
}
static boolean IsOccupied(String Seat) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if (MSR[i][1].equals(Seat)) {
MSR[i][2]="X";
return true;
}
}
}
return false;
}
static void displayList(){
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader("MovieSeats.txt");
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException e)
{
System.out.println("Error reading file name");
}
}
public static void main (String[]args) throws IOException {
String yn;
do{
System.out.println("\t\tMOVIE SEAT RESERVATION");
System.out.println("===========================================================");
System.out.println("\t\tA. Reserve Seat");
System.out.println("\t\tB. Cancel Reserve Seat");
System.out.println("\t\tD. Display List of Reserved Seat ");
System.out.println("\t\tE. Clear Seats");
System.out.println("\t\tF. Quit");
System.out.println("===========================================================");
System.out.println();//SPACE
System.out.print("Enter a valid input: ");
String choice = user.next();
switch(choice.toUpperCase()){
case "A":
ReserveSeat();
break;
case "B":
break;
case "C":
break;
case "D":
displayList();
break;
case "E":
break;
case "F":
System.exit(0);
break;
default:
System.err.println("Invalid Input, Please try again.");
break;
}
System.out.print("Do you want to try again? ");
yn= user.next();
}
while(yn.equalsIgnoreCase("Y"));
}
}

The following line of code if (MSR[i][1].equals(Seat)) in the IsOcupied method throws the NullPointerException. You are calling .equals method on MSR[i][1] which contains null.
You have to assign a value to that element before calling .equals on it. You could check whether the element is null, and if it is, return false (=the seat is not occupied yet).
static boolean IsOccupied(String Seat) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 3; j++) {
if (MSR[i][1] != null && MSR[i][1].equals(Seat)) {
MSR[i][2]="X";
return true;
}
}
}
return false;
}
The null check will be evaluated first, so if MSR[i][1] != null returns false, then the right hand operand of the AND (&&) operator won't be evaluated. That means you won't be checking .equals on a null anymore.

in if block in IsOccupied method use Seat.equals(MSR[i][1]) instead of using MSR[i][1].equals(Seat). array elements are initially null which produces NullPointerException at this line when trying to execute equalsmethod.

Related

My Remove Method isn't Working

Create a program that keeps track of the following information input by the user:
First Name, Last Name, Phone Number, Age
Now - let's store this in a multidimensional array that will hold 10 of these contacts.
So our multidimensional array will need to be 10 rows and 4 columns.
You should be able to add, display and remove contacts in the array.
*/
import java.util.Scanner;
public class compLab2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[][] contacts = new String [10][4];
System.out.println("Select your options: \n");
while(true){
// Give the user a list of their options
System.out.println("1: Add a new contact to list.");
System.out.println("2: Remove a contact from the list.");
System.out.println("3: Display contacts.");
System.out.println("0: Exit the list.");
// Get the user input
int userChoice = input.nextInt();
switch(userChoice){
case 1:
addContacts(contacts);
break;
case 2:
removeContacts(contacts);
break;
case 3:
displayContacts(contacts);
break;
case 0:
System.out.println("Goodbye!");
System.exit(0);
}
}
}
private static void addContacts (String [][] contacts) {
Scanner input = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
if (contacts[i][0] == null || contacts[i][0].equals(null)) {
contacts[i][0] = input.nextLine();
contacts[i][1] = input.nextLine();
contacts[i][2] = input.nextLine();
contacts[i][3] = input.nextLine();
boolean Inserted = true;
break;
}
}
}
private static void removeContacts(String [][] contacts) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the name of the contact you want to remove: ");
String removeContact = input.nextLine();
for(int i=0; i<contacts.length; i++){
for(int j = 0; j <contacts[i].length; j++){
if(contacts[i][j].equals(removeContact)) {
contacts[i][0]=" ";
contacts[i][1]=" ";
contacts[i][2]=" ";
contacts[i][3]=" ";
}
}
break;
}
}
private static void displayContacts(String [][] contacts) {
for (int i = 0; i< contacts.length; i++) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
You have to move your break inside the if condition(once element is remove break the loop) otherwise your first for loop will break in i=0 condition.
In if condition you have to check removeContact with contacts[i][j] because contacts[i][j] can be null.
Below you can find the code
if (removeContact != null) { //removeContact should not be null
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) { //removeContact is not null so check removeContact with contacts[i][j]
contacts[i][0] = " ";
contacts[i][1] = " ";
contacts[i][2] = " ";
contacts[i][3] = " ";
break; //break the loop once you remove
}
}
}
}
You should set null insteam of white space(" ")
if (removeContact != null) {
for (int i = 0; i < contacts.length; i++) {
for (int j = 0; j < contacts[i].length; j++) {
if (removeContact.equals(contacts[i][j])) {
contacts[i][0] = null;
contacts[i][1] = null;
contacts[i][2] = null;
contacts[i][3] = null;
break;
}
}
}
}
Because you are checking null while adding a contact. So setting null will free a space in your array and will allow you to add a new contact to that space.
Also you should check null entry during displaying contacts
private static void displayContacts(String [][] contacts) {
for (int i = 0; i < contacts.length; i++) {
if (contacts[i][0] != null) {
for (int j= 0; j < contacts[i].length; j++) {
System.out.print(contacts[i][j] + " ");
}
System.out.println();
}
}
}
An ArrayList with a custom class can solve this problem easily.

Matching array values with variables

In this code I have an array with 5 elements and each element contains a value. Below in the while loop, I'm trying to give the user 3 attempts to guess what number is contained in the array (the user enters their guesses). My problem is that I don't know how to make match the user's guess (stored in a variable choose) with the array values caja[i] to print whether the user won or lost depending on a correct or incorrect guess respectively.
public static void main(String[] args)
{
int[] caja = new int [5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++)
{
System.out.println(caja[i]);
}
System.out.println();
int electionGame = 3;
int o = 0;
while(electionGame > 0)
{
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length; i++)
{
o = o + 1;
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
}
electionGame--;
}
}
}
Your problem is that you break out of your loop in every case:
if(choose == caja[i])
{
System.out.println("Ganastes");
break;
}
else
{
System.out.println("Perdiestes");
break;
}
Instead of doing this (and printing the result after only the first comparison), you should have a Boolean indicating whether the number was found in the array:
int electionGame = 3;
boolean found = false; //indicates whether user has found right number
while (electionGame > 0 && !found) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
for (int i = 0; i < caja.length && !found; i++) {
if (choose == caja[i]) {
found = true;
}
}
electionGame--;
if (found) {
System.out.println("you won");
} else {
System.out.println("nope");
}
}
This way, you can check the variable and tell the user whether he won or lost.
Here are some additional suggestions. The answer by Alex (https://stackoverflow.com/a/36133864/6077352) is good. Please note the comments in the code.
import java.util.Scanner;
/** https://stackoverflow.com/q/36133524/6077352 */
public class GuessNumber {
public static void main(String[] args) {
int[] caja = new int[5];
caja[0] = 1;
caja[1] = 3;
caja[2] = 5;
caja[3] = 7;
caja[4] = 9;
System.out.println("Mostrando todos los numeros del arreglo");
for (int i = 0; i < caja.length; i++) {
System.out.println(caja[i]);
}
System.out.println();
int tries = 3;
Scanner sc = new Scanner(System.in);// no need to create scanners in loop
while (tries-- > 0) {// count down tries
System.out.print("Please guess a number... ");
int guess = sc.nextInt();
boolean win = false;// flag to determine if won
for (int i : caja) {// iterate through array and check if guess is inside
win |= (i == guess);// when inside: win=true
}
System.out.println("Answer right? " + win);
System.out.println();
}
}
}
So if the user can attempt to get any of the values of the array you might to change your while loop to this one:
while (electionGame > 0) {
Scanner sc = new Scanner(System.in);
int choose = sc.nextInt();
boolean ganaste = false;
for (int i = 0; i < caja.length; i++) {
o = o + 1;
if (choose == caja[i]) {
ganaste = true;
break;
}
}
if (ganaste)
System.out.println("Ganastes");
else
System.out.println("Perdiestes");
electionGame--;
}

Adding Binary Numbers in JAVA. NumberFormatException

The problem is when I enter a decimal input. For example 10001.10.
It says NumberFormatException. But when I input just a number without decimal like "1001110" its works fine.
import java.util.*;
import java.util.Arrays;
public class Binary {
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
String[] Condition = { "0", "1", "." };
//Accept First Input
String numInp1="";
System.out.print("Enter First Binary Number: ");
numInp1 = in.nextLine();
//Accept Second Input
String numInp2="";
System.out.print("Enter Second Binary Number: ");
numInp2 = in.nextLine();
//numInp1
String _Array1 []=new String[numInp1.length()];
//numInp2
String _Array2 []=new String[numInp2.length()];
//Catch error in numInp1/_Array1
boolean flag1 = false;
for(int i = 0; i < _Array1.length; i++)
{
_Array1[i] = String.valueOf(numInp1.charAt(i));
int cnt = 0;
for (int j = 0; j < Condition.length; j++)
{
if (!_Array1[i].equals(Condition[j]))
{
cnt++;
}
else
{
break;
}
if (cnt == 3)
{
flag1 = true;
}
}
}
//Catch error in numInp2//_Array2
boolean flag2 = false;
for(int i = 0; i < _Array2.length; i++)
{
_Array2[i] = String.valueOf(numInp2.charAt(i));
int cnt = 0;
for (int j = 0; j < Condition.length; j++)
{
if (!_Array2[i].equals(Condition[j]))
{
cnt++;
}
else
{
break;
}
if (cnt == 3)
{
flag2 = true;
}
}
}
//Getting which of the Array has Higher Input
if(flag2 == false && flag1 == false)
{
int HigherLength = 0;
if(_Array1.length >= _Array2.length)
{
HigherLength = _Array1.length + _Array2.length;
}
else
{
HigherLength = _Array2.length + _Array1.length;
}
//Declaring the size of higher length as the size of Equals[] Array
int Equals[] = new int[HigherLength];
int _Array1Int[] = new int[_Array1.length];
int _Array2Int[] = new int[_Array2.length];
for(int i = 0;i<_Array1.length;i++)
{
if(_Array1[i].equals("."))
{
_Array1[i] = "6";
}
_Array1Int[i] = Integer.parseInt(_Array1[i]);
}
for(int i = 0;i<_Array2.length;i++)
{
if(_Array2[i].equals("."))
{
_Array2[i] = "6";
}
_Array2Int[i] = Integer.parseInt(_Array2[i]);
}
//_________________________
int numInp1int = Integer.parseInt(numInp1);
int numInp2int = Integer.parseInt(numInp2);
int i,m,n,sum,carry=0;
for(i=Equals.length-1;i>=0;i--)
{
m=numInp1int%10;
n=numInp2int%10;
numInp1int=numInp1int/10;
numInp2int=numInp2int/10;
sum=m+n+carry;
if(sum==1)
{
Equals[i]=1;
carry=0;
}
else if(sum==2)
{
Equals[i]=0;
carry=1;
}
else if(sum==3)
{
Equals[i]=1;
carry=1;
}
else
{
Equals[i]=m+n+carry;
}
}
String Equals1[] = new String[Equals.length];
for(i=0;i<Equals.length;i++)
{
try{
Equals1[i] = String.valueOf(Equals[i]);
}
catch (NumberFormatException nfe)
{
nfe.printStackTrace();
}
if (Equals1[i].equals("6"))
{
Equals1[i] = ".";
}
System.out.print(Equals1[i]);
}
}
}
}
Do below changes in your code
Remove below 2 lines-
int numInp1int = Integer.parseInt(numInp1);
int numInp2int = Integer.parseInt(numInp2);
Replace with below code -
StringBuilder strNum1 = new StringBuilder();
for (int num : _Array1Int)
{
strNum1.append(num);
}
int numInp1int = Integer.parseInt(strNum1.toString());
StringBuilder strNum2 = new StringBuilder();
for (int num : _Array2Int)
{
strNum2.append(num);
}
int numInp2int = Integer.parseInt(strNum2.toString());
Updating _Array1 and _Array2 does not change numInp1int and numInp2int which you are trying to parse as Integer.
You should learn to interpret error messages in the stack trace. Here you can clearly see where the problem is:
Exception in thread "main" java.lang.NumberFormatException: For input string: "10001.1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
at java.lang.Integer.parseInt(Integer.java:615)
at q35640801.Binary.main(Binary.java:120)
It's in the call parseInt() of class Integer. It cannot parse decimal numbers like 10001.10

Simple Java TextEditor program not working

So for I was suppose to create a text-editor program where editing is done via a command which, in turn, is executed by the corresponding method. I was suppose to utilize this text-editor program with two files a) A novel .txt file such as tale of two cities and b) a file that contains a list of properly spelled words as for reference for the spellcheck methods
I was to utilized the following:
boolean Find (String x) // Looks for a word "x" in the file and returns true if found or false otherwise.
boolean FindReplace (String x, String y) // looks for the first occurrence of word "x" in the file and replaces it with word "y" if found returning true, false otherwise.
boolean FindInsert (String x, String y) // looks for the first occurrence of word "x" in the file and then insert "y" right after "x", if x is found, returning true, false otherwise.
boolean Delete (String x) // looks for the first occurrence of word "x" in the file and deletes it from the file, returning true if x is found, returning false otherwise.
String spellCheck () // finds the first occurrence of spelling error and returns the misspelled word. If no word is misspelled returns "Spell Check Passed".
void spellCheckAll() // find all misspelled words and output them to the screen.
void save() // saves file with the changes made.
void print() // saves file with the changes and outputs the contents of the file to the screen.
void quit() should save() the file and exit.
10. boolean FindReplaceAll (String x, String y) // looks for all occurrences of word "x" in the file and replace each with word "y" if found returning true, false otherwise.
This is the code I have so far. It compiles. However, when I try to object test any of methods they won't work. For example, my method to find the occurrence of a string within a .txt file will always return false I'm assuming there are some issues either a) my boolean method loops b) there's some issues with the creation of my linked list that I used for my file that's being read in and/or my hash map that I used for my dictionary/reference file. I'm stumped.
package FileEditor;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Scanner;
import java.util.Set;
public class FileEditor {
static LinkedList<String> list = new LinkedList<String>();
public FileEditor() {
super();
}
public static void readNovelFile() {
String content = new String();
File file = new File("2city10.txt");
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()) {
content = sc.nextLine();
list.add(content);
}
sc.close();
} catch (FileNotFoundException fnf) {
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
}
public static boolean findText(String x) {
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
return true;
} else {
return false;
}
}
return false;
}
public static void findAndReplace(String x, String y) {
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
text = text.replaceAll(x, y);
list.remove(i);
list.add(i, text);
}
}
}
public static void findAndInsert(String x, String y) {
boolean flag = false;
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
if (flag == false)
text = text.replace(x, x + " " + y);
list.remove(i);
list.add(i, text);
}
flag = true;
}
}
public static void delete(String x) {
boolean flag = false;
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x) || text.equals(x)) {
if (flag == false)
text = text.replace(x, "");
list.remove(i);
list.add(i, text);
}
flag = true;
}
}
public static HashSet<String> readWords(String filename) throws FileNotFoundException {
HashSet<String> words = new HashSet<String>();
Scanner in = new Scanner(new File(filename));
// Use any characters other than a-z or A-Z as delimiters
in.useDelimiter("[^a-zA-Z]+");
while (in.hasNext()) {
words.add(in.next().toLowerCase());
}
return words;
}
public static void spellCheck() {
// Read the dictionary and the document
Set<String> dictionaryWords = null;
Set<String> documentWords = null;
boolean flag = false;
try {
dictionaryWords = readWords("EnglishWordList.txt");
documentWords = readWords("2city10.txt");
} catch (FileNotFoundException e) {
}
// Print all words that are in the document but not the dictionary
for (String word : documentWords) {
if (!dictionaryWords.contains(word) && flag == false) {
System.out.println(word);
flag = true;
}
}
}
public static void spellCheckAll() {
// Read the dictionary and the document
Set<String> dictionaryWords = null;
Set<String> documentWords = null;
try {
dictionaryWords = readWords("EnglishWordList.txt");
documentWords = readWords("2city10.txt");
} catch (FileNotFoundException e) {
}
// Print all words that are in the document but not the dictionary
for (String word : documentWords) {
if (!dictionaryWords.contains(word)) {
System.out.println("Misspelled words :" + word);
}
}
}
public static void saveFile() {
BufferedWriter out;
try {
out = new BufferedWriter(new FileWriter("2city10.txt"));
for (int i = 0; i < list.size(); i++) {
out.write(list.get(i).toString());
out.write('\n'); // add a new line
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void printFile() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i).toString());
//out.write('\n'); // add a new line
}
}
public static void menuList() {
System.out.println("\n Enter the Choice ...");
System.out.println("\n Enter 1 to Find ");
System.out.println("\n Enter 2 to FindReplace ");
System.out.println("\n Enter 3 to FindInsert ");
System.out.println("\n Enter 4 to Delete ");
System.out.println("\n Enter 5 to spellCheck ");
System.out.println("\n Enter 6 to spellCheckAll ");
System.out.println("\n Enter 7 to save ");
System.out.println("\n Enter 8 to print ");
System.out.println("\n Enter 9 to quit ");
}
public static void main(String[] args) throws IOException {
readNovelFile();
int choice = 0;
menuList();
Scanner scanner = new Scanner(System.in);
choice = scanner.nextInt();
while (true) {
switch (choice) {
case 1:
{
String input = "";
System.out.println("\nEnter the string to Find ...");
Scanner textscan = new Scanner(System.in);
input = textscan.nextLine();
System.out.println("The String entered exists :" +
findText(input));
menuList();
choice = scanner.nextInt();
break;
}
case 2:
String find = "";
String replace = "";
System.out.println("\nEnter the string to Find ...");
Scanner findScan = new Scanner(System.in);
find = findScan.nextLine();
System.out.println("\nEnter the string to Replace ...");
Scanner replaceScan = new Scanner(System.in);
replace = replaceScan.nextLine();
findAndReplace(find, replace);
menuList();
choice = scanner.nextInt();
break;
case 3:
String findStr = "";
String insStr = "";
System.out.println("\nEnter the string to Find ...");
Scanner findStrScan = new Scanner(System.in);
findStr = findStrScan.nextLine();
System.out.println("\nEnter the string to Insert ...");
Scanner InsertStrScan = new Scanner(System.in);
insStr = InsertStrScan.nextLine();
findAndInsert(findStr, insStr);
menuList();
choice = scanner.nextInt();
break;
case 4:
String delete = "";
System.out.println("\nEnter the string to Delete ...");
Scanner deleteScan = new Scanner(System.in);
delete = deleteScan.nextLine();
delete(delete);
menuList();
choice = scanner.nextInt();
break;
case 5:
System.out.println("\nSpell checking for first occurence ....");
spellCheck();
menuList();
choice = scanner.nextInt();
break;
case 6:
System.out.println("\nSpell checking for All occurences ....");
spellCheckAll();
menuList();
choice = scanner.nextInt();
break;
case 7:
System.out.println("\nSaving the File ....");
saveFile();
menuList();
choice = scanner.nextInt();
break;
case 8:
System.out.println("\nSaving and Printing the File ....");
saveFile();
printFile();
menuList();
choice = scanner.nextInt();
break;
case 9:
System.out.println("\nEXIT MENU ....");
System.exit(0);
break;
}
}
}
}
For your findText always returning false....
public static boolean findText(String x) {
boolean found;
for (int i = 0; i < list.size(); i++) {
String text = list.get(i);
if (text.contains(x)) { // You also dont need that "equals()" here
found=true;
break; // Break loop if text found
} else {
found=false;
}
}
return found;
}
But as mentioned in comments, better way is this:
public static boolean findText(String x) {
boolean found;
for (int i = 0; i < list.size(); i++) {
if(list.get(i).indexOf(x) >= 0){
found = true;
break;
}
else
found = false
}
return found;
}
Another way to do this without manually involving loops is:
public static boolean findText(String x) {
int index = Collections.binarySearch(list, x);
if(index >= 0)
return true;
return false;
}

I am unable to display the path taken inside my maze from start to finish

I am reading the maze outline in from an input file and storing the values in a 2D array. I am able to find the exit in my findPath() method, but i am unsure how to trace the actual path from start to finish.
I want to change the char value in the "Room" to a '.' if it is on the actual path. Please advise how i can accomplish this. Any help is greatly appreciated. Thanks.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.*;
import javax.swing.JOptionPane;
public class Maze {
String inFile, // Name of file to be used as input
outFile, // Name of file to output completed maze to
line; // Current line being read by scanner
Room [][] rooms; // Holds the values that create maze
Room [] theStack;
Room goal;
Room current = new Room();
int rows, columns;
int tos = 0;
char [][] mazeC;
public static void main(String []args) throws Exception {
Maze m = new Maze();
}
public Maze() throws FileNotFoundException {
// Prompts user for the name of the file they wish to use as the input file.
inFile = JOptionPane.showInputDialog(null, "Please enter the name of the file you wish to read, including " + "the file path:");
if(inFile.equals("")) inFile = "C:/java/javaFiles/maze1.txt";
// Prompts user to enter the name they wish to save the file under.
outFile = JOptionPane.showInputDialog(null, "Please enter the filename you wish to save the data to:");
if(outFile.equals("")) outFile = "C:/java/javaFiles/mazeoutput1.txt";
// Creates a scanner object to read in the input file.
Scanner readFile = new Scanner(new FileReader(inFile));
PrintWriter output = new PrintWriter(outFile);
rows = readFile.nextInt();
columns = readFile.nextInt();
readFile.nextLine();
theStack = new Room[1000];
rooms = new Room [rows][columns];
for(int i = 0; i < rows; i++) {
line = readFile.nextLine();
for(int j = 0; j< line.length(); j++) {
Room r = new Room();
r.setValue(line.charAt(j));
if(r.getValue() == '$')
r.setGoal(true);
r.setBlocked(false);
if (r.getValue() == '*') {
r.setBlocked(true);
r.setGoal(false);
} else {
r.setGoal(false);
r.setBlocked(false);
}
r.setCord(i, j);
rooms[i][j] = r;
//mazeContent[i][j] = line.charAt(j);
}
}
createRooms();
findPath();
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
System.out.print(rooms[i][j].getValue());
}
System.out.println();
}
}
public void createRooms() {
for(int i = 1; i < rows - 1; i++) {
for(int j = 1; j < columns -1; j++) {
rooms[i][j].setCord(i,j);
rooms[i][j].setValue(rooms[i][j].getValue());
rooms[i][j].setUp(rooms, i, j);
rooms[i][j].setDown(rooms, i, j);
rooms[i][j].setRight(rooms, i, j);
rooms[i][j].setLeft(rooms, i, j);
if(rooms[i][j].getValue() == '*')
rooms[i][j].setBlocked(true);
else
rooms[i][j].setBlocked(false);
//System.out.println(rooms[i][j].getValue());
}
}
}
public void findPath() {
for(int i = 0; i < rows ; i++) {
for(int j = 0; j < columns ; j++) {
System.out.print(rooms[i][j].getValue());
}
System.out.println();
}
Room start = rooms[1][1];
push(start);
while(!isEmpty()) {
current = pop();
System.out.println("The value stored in current is" + current.getValue()+ "");
if (current == null)
System.out.println("current is null");
else if(current.getValue() == '$') {
System.out.println("Success");
current.setValue('f');
/*for (int i = 0; i < tos; i++) {
}*/
}
//System.out.println("The value is " + current.getValue());
else if(current.getBlocked() == false && current.getVisited() == false) {
System.out.println("pushing currents neighbors left, right....etc" +
"current is at" + current.getCord());
current.setVisited(true);
//
if(current.getRight() != null){
push(current.getRight()); System.out.println("Inside push 1" +current.getRight().getCord());}
else System.out.println("Inside push right is null");
if(current.getLeft() != null){
push(current.getLeft()); System.out.println("Inside push 2 " + current.getLeft().getCord());}
else System.out.println("Inside push left is null");
if(current.getUp() != null) {
push(current.getUp()); System.out.println("Inside push 3" + current.getUp().getCord());}
else System.out.println("Inside push up is null");
if(current.getDown() != null) {
push(current.getDown()); System.out.println("inside push 4" + current.getDown().getCord());}
else System.out.println("Inside push down is null");
}
}
}
public Room pop() {
// TODO Auto-generated method stub
System.out.println("I have Popped");
return theStack[--tos];
}
public boolean isEmpty() {
// TODO Auto-generated method stub
return tos == 0;
}
public void push(Room item) {
System.out.println("I have pushed");
if (isFull()) {
System.out.println("The stack is full!");
}
else if(item == null){
System.out.println("you are pushing a null object");
}
else
System.out.println("stuff added");
theStack[tos++] = item;
}
public boolean isFull() {
return tos == theStack.length-1;
}
}
I haven't really gone through your code line by line but here's a solution: (I wrote a similar program for finding Djikstra's shortest path in a graph)
Make an attribute called PREVIOUS in your room object.
Every time you go to a 'next room', make sure you change your next room's PREVIOUS attribute to the room you came from.
When you reach your destination: Start with your destination's PREVIOUS and traverse back through the rooms until you hit a room with no PREVIOUS, which will be your source (start) room. i.e. go to the PREVIOUS room, add it to the stack, go to its PREVIOUS and repeat the process until you hit your starting room.
This should work because: If you go through a path of rooms and you hit a dead-end you will back track and start going through a new path. Eventually you will recursively over-write the PREVIOUS attribute for each room in your new path (every time). When you hit your destination, you will have the most updated (correct) PREVIOUS attribute in every room in your current (correct) path. So traverse back and add the PREVIOUS of each room to a stack or a queue or (whatever you want) as you go. This should give you your path.

Categories

Resources