My code is as follows:
package examen2;
import java.io.*;
import java.util.*;
public class Examen2 {
public static void main(String[] args) throws Exception {
FileInputStream fis = new FileInputStream("dataIn.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
TreeSet<Punct> set = new TreeSet();
String line;
//problem in the while statement
while (((line = br.readLine()).length() != 0)) {
String[] splited = line.split("([^0-9\\n\\r\\-][^0-9\\n\\r\\-]*)");
int[] number = new int[splited.length];
for (int i=0, j=0; i<splited.length; i++) {
number[j] = Integer.parseInt(splited[i]);
j++;
}
set.add(new Punct(number[0], number[1]));
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.print(it.next());
}
System.out.println();
}
br.close();
br = null;
fis = null;
}
static class Punct implements Comparable {
int x;
int y;
Punct() {
x = 0;
y = 0;
}
Punct(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return "(" + this.x + ":" + this.y + ")";
}
#Override
public boolean equals(Object o) {
try {
Punct other = (Punct)o;
return (this.x==other.x && this.y==other.y);
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
return false;
}
#Override
public int compareTo(Object t) {
Punct other = (Punct)t;
if (this.x == other.x && this.y == other.y) {
return 0;
} else if (Math.sqrt(Math.pow(this.x, 2)+Math.pow(this.y, 2))-Math.sqrt(Math.pow(other.x, 2)+Math.pow(other.y, 2))>0) {
return 1;
} else {
return -1;
}
}
#Override
public int hashCode() {
return super.hashCode(); //To change body of generated methods, choose Tools | Templates.
}
#Override
protected void finalize() throws Throwable {
super.finalize(); //To change body of generated methods, choose Tools | Templates.
}
#Override
protected Object clone() throws CloneNotSupportedException {
return super.clone(); //To change body of generated methods, choose Tools | Templates.
}
}
}
dataIn.txt content:
1 2
3 assfas 4
5 asfl;a 8
1 1
3 4
And it writes out this to the console:
(1:2)
(1:2)(3:4)
(1:2)(3:4)(5:8)
(1:1)(1:2)(3:4)(5:8)
(1:1)(1:2)(3:4)(5:8)
Exception in thread "main" java.lang.NullPointerException
at examen2.Examen2.main(Examen2.java:15)
Java Result: 1 BUILD SUCCESSFUL (total time: 0 seconds)
This is an example for what kind of problems will be at the exam tomorrow.
I have to read the pair of numbers from every row of the input file. I think the problem is not with the regex, but with the interpretation of the result, but I couldn't find the solution.
Where did you pick up this line of code?
while (((line = br.readLine()).length() != 0)) {
It's not good as you'll eventually be calling length() on a null object.
Instead check that line isn't null, and use that in your while condition.
while((line=br.readLine())!=null) {
//....
}
The NullPointerException comes from this line:
while (((line = br.readLine()).length() != 0)) {
When the BufferedReader's readLine() method reaches the end of the stream, it returns null, not an empty string.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
Try
while ((line = br.readLine() != null) {
Related
I use this library for exporting to CSV file
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.3</version>
</dependency>
I created Builder:
writer = new StatefulBeanToCsvBuilder<T>(printWriter)
.withQuotechar(CSVWriter.DEFAULT_QUOTE_CHARACTER)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withOrderedResults(false)
.withMappingStrategy(mappingStrategy)
.build();
It Is my POJO:
#Data
public class ReportCsvDto {
#CsvBindByName(column = "NAME")
#CsvBindByPosition(position = 0)
private String name;
#CsvBindByName(column = "ID")
#CsvBindByPosition(position = 1)
private String id;
#CsvBindByName(column = "GENDER")
#CsvBindByPosition(position = 3)
private String gender;
}
How can I remove quotations from empty values?
I have this: "Bill","","male"
I want this: "Bill",,"male"
I want to remove quotations only from empty values
I have looked through the code of opencsv library. And most simple decision which I can come up with now it is just override transmuteBean method in MappingStrategy and passing this new stategy to the builder. For example for ColumnPositionMappingStrategy:
public class CustomColumnPositionMappingStrategy<T> extends ColumnPositionMappingStrategy<T> {
#Override
public String[] transmuteBean(T bean) throws CsvFieldAssignmentException, CsvChainedException {
int numColumns = headerIndex.findMaxIndex()+1;
BeanField<T, Integer> firstBeanField, subsequentBeanField;
Integer firstIndex, subsequentIndex;
List<String> contents = new ArrayList<>(Math.max(numColumns, 0));
// Create a map of types to instances of subordinate beans
Map<Class<?>, Object> instanceMap;
try {
instanceMap = indexBean(bean);
}
catch(IllegalAccessException | InvocationTargetException e) {
// Our testing indicates these exceptions probably can't be thrown,
// but they're declared, so we have to deal with them. It's an
// alibi catch block.
CsvBeanIntrospectionException csve = new CsvBeanIntrospectionException(
ResourceBundle.getBundle(
ICSVParser.DEFAULT_BUNDLE_NAME, errorLocale)
.getString("error.introspecting.beans"));
csve.initCause(e);
throw csve;
}
CsvChainedException chainedException = null;
for(int i = 0; i < numColumns;) {
// Determine the first value
firstBeanField = findField(i);
firstIndex = chooseMultivaluedFieldIndexFromHeaderIndex(i);
String[] fields = ArrayUtils.EMPTY_STRING_ARRAY;
if(firstBeanField != null) {
try {
fields = firstBeanField.write(instanceMap.get(firstBeanField.getType()), firstIndex);
}
catch(CsvDataTypeMismatchException | CsvRequiredFieldEmptyException e) {
if(chainedException != null) {
chainedException.add(e);
}
else {
chainedException = new CsvChainedException(e);
}
}
}
if(fields.length == 0) {
// Write the only value
contents.add(null);
i++; // Advance the index
}
else {
// Multiple values. Write the first.
contents.add(fields[0]);
// Now write the rest.
// We must make certain that we don't write more fields
// than we have columns of the correct type to cover them.
int j = 1;
int displacedIndex = i+j;
subsequentBeanField = findField(displacedIndex);
subsequentIndex = chooseMultivaluedFieldIndexFromHeaderIndex(displacedIndex);
while(j < fields.length
&& displacedIndex < numColumns
&& Objects.equals(firstBeanField, subsequentBeanField)
&& Objects.equals(firstIndex, subsequentIndex)) {
// This field still has a header, so add it
contents.add(fields[j]);
// Prepare for the next loop through
displacedIndex = i + (++j);
subsequentBeanField = findField(displacedIndex);
subsequentIndex = chooseMultivaluedFieldIndexFromHeaderIndex(displacedIndex);
}
i = displacedIndex; // Advance the index
// And here's where we fill in any fields that are missing to
// cover the number of columns of the same type
if(i < numColumns) {
subsequentBeanField = findField(i);
subsequentIndex = chooseMultivaluedFieldIndexFromHeaderIndex(i);
while(Objects.equals(firstBeanField, subsequentBeanField)
&& Objects.equals(firstIndex, subsequentIndex)
&& i < numColumns) {
contents.add(null);
subsequentBeanField = findField(++i);
subsequentIndex = chooseMultivaluedFieldIndexFromHeaderIndex(i);
}
}
}
}
// If there were exceptions, throw them
if(chainedException != null) {
if (chainedException.hasOnlyOneException()) {
throw chainedException.getFirstException();
}
throw chainedException;
}
return contents.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
}
}
And for your example it will produce the following output:
"Bill",,"male"
This overridden method is a simple copy of the original method. But instead of writing empty string on null value it writes null value. And CSVWriter.writeNext method then skips the output of the quotes for null value. This decision can be extended to handle blank lines in the original data too.
As an option you can implement MappingStrategy entirely of course. But I think this is not what you need.
Or you can just implement ICSVWriter for your case or redefine writeNext method for existing subclass. And then you need to pass this CSVWriter to builder. For example CSVWriter.writeNext:
public class CustomCSVWriter extends CSVWriter {
public CustomCSVWriter(Writer writer) {
super(writer);
}
public CustomCSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
super(writer, separator, quotechar, escapechar, lineEnd);
}
#Override
protected void writeNext(String[] nextLine, boolean applyQuotesToAll, Appendable appendable) throws IOException {
if (nextLine == null) {
return;
}
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
appendable.append(separator);
}
String nextElement = nextLine[i];
if (StringUtils.isEmpty(nextElement)) {
continue;
}
Boolean stringContainsSpecialCharacters = stringContainsSpecialCharacters(nextElement);
appendQuoteCharacterIfNeeded(applyQuotesToAll, appendable, stringContainsSpecialCharacters);
if (stringContainsSpecialCharacters) {
processLine(nextElement, appendable);
} else {
appendable.append(nextElement);
}
appendQuoteCharacterIfNeeded(applyQuotesToAll, appendable, stringContainsSpecialCharacters);
}
appendable.append(lineEnd);
writer.write(appendable.toString());
}
private void appendQuoteCharacterIfNeeded(boolean applyQuotesToAll, Appendable appendable, Boolean stringContainsSpecialCharacters) throws IOException {
if ((applyQuotesToAll || stringContainsSpecialCharacters) && quotechar != NO_QUOTE_CHARACTER) {
appendable.append(quotechar);
}
}
}
Overridden method is a simple copy of the original method again. But it skips processing of empty strings (StringUtils.isEmpty(nextElement) check instead of checking for null).
And, of course, you can redefine this behavior in the following way:
public class CustomCSVWriter extends CSVWriter {
public CustomCSVWriter(Writer writer) {
super(writer);
}
public CustomCSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
super(writer, separator, quotechar, escapechar, lineEnd);
}
#Override
protected void writeNext(String[] nextLine, boolean applyQuotesToAll, Appendable appendable) throws IOException {
if (nextLine != null) {
for (int i = 0; i < nextLine.length; i++) {
if (StringUtils.isEmpty(nextLine[i])) {
nextLine[i] = null;
}
}
}
super.writeNext(nextLine, applyQuotesToAll, appendable);
}
}
Here empty strings are simply replaced with null values. And for me, this method would be more preferable if you do not need to separate empty strings and null values from the original data. Otherwise, the first option (with redefining MappingStrategy) is the only one possible.
I'm having trouble figuring out what's wrong with my java code. I am creating a Trivia Game that reads in the question ID, question, answer, and answer point value from a dat file.
I've tried all sorts of things, but am getting the same NumberFormatException.
Below is an example of how the dat file is setup: 10 questions total
1: 01
2: What is light as a feather, but even the strongest man cannot hold it more
than a few minutes?
3: His breath
4: 3
Game.java
import java.util.*;
import java.io.*;
public class Game {
// Instance Variables
private QuestionBank[] questions;
private int numQuestions;
private int questionNumber;
private int playerScore;
// Constructor
public Game()
{
QuestionBank[] questions = new QuestionBank[10];
numQuestions = 0;
questionNumber = 0;
playerScore = 0;
}
public Game(FileInputStream questionsFile)
{
BufferedReader br = new BufferedReader(new InputStreamReader(questionsFile));
String stringLine = null;
int i = 0;
try
{
while((stringLine = br.readLine()) != null)
{
QuestionBank quest = new QuestionBank();
quest.setQuestionID(Integer.valueOf(br.readLine())); //ERROR OCCURS HERE
quest.setQuestion(br.readLine());
quest.setAnswer(br.readLine());
quest.setPointValue(Integer.valueOf(br.readLine()));
questions[i] = quest;
i++;
stringLine = null;
}
br.close();
}
catch (IOException e)
{
System.out.println("Uh oh. Exception caught.");
}
this.questionNumber = 0;
/*Scanner questionsFileScanner = new Scanner(questionsFile);
questions = new QuestionBank[5];
while(questionsFileScanner.hasNextLine())
{
for(int i = 0; i < 4; ++i)
{
questions[i] = new QuestionBank();
questions[i].setQuestion(questionsFileScanner.nextLine());
}
}*/
}
//Accessors and Mutators
public int getNumQuestions()
{
return numQuestions;
}
public int getQuestionNumber()
{
return questionNumber;
}
public int getPlayerSocre()
{
return playerScore;
}
public boolean checkAnswer(String answer)
{
if(answer.contentEquals(questions[questionNumber].getAnswer()) == true)
{
playerScore += questions[questionNumber].getPointValue();
++questionNumber;
return true;
}
else
{
return false;
}
}
public String getNextQuestion()
{
return questions[questionNumber].getQuestion();
}
public String toString()
{
String outputString = "";
for (int i = 0; i < questionNumber; ++i)
{
outputString = questions[i].toString();
}
return outputString;
}
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "What is light as a feather, but even the strongest man cannot hold it more than a few minutes?"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.valueOf(Integer.java:983)
at project7.Game.<init>(Game.java:41)
at project7.RunGame.main(RunGame.java:41)
In addition to what I mentioned above you can use StringUtils.isNumeric method to see if stringLine only contains numeric values.
You can find that method with Apache Commons Lang dependency.
if you're using maven here's the link to download it to your project https://mvnrepository.com/artifact/org.apache.commons/commons-lang3/3.5
If you're not using maven you should be able to download the jar from that link (or from https://jar-download.com/artifacts/org.apache.commons/commons-lang3/3.5/source-code) and then include the jar as a library in your project.
It's my second time asking here and straight to the point. I can't seem to find a solution and I know it's not impossible. I wrote a java program that can generate a set of combination of any length, when I stop the program I don't want to start from the beginning how can I pick up from where I stopped?
Thanks.
Example (for length 3):
If I start from aaa ==> 9zI and I stop the program here, I don't want to start from aaa all over but start from 9zI and continue to 999. I just want to continue from where I left off.
public class Main {
public static void main(String[] args) {
S_Permutation sp = new S_Permutation();
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
FileClass.fileExist("new.txt", true);
System.out.println("");
sp.permutation(text, "", 7, "sha256.txt","Kaaaaaa");
}
}
=====================================================================
public class S_Permutation {
private List<String> permutation;
public S_Permutation() {
permutation = new ArrayList<>();
}
public boolean saveThis(String words, char a, int limit) {
int count = 0;
limit++;
for (char character : words.toCharArray()) {
if (count == limit) {
return false;
}
if (character == a) {
count++;
} else {
count = 0;
}
}
return count < limit;
}
private int counter = 0;
private boolean seen = false;
public void permutation(String str, String prefix, int lengthOfPermutationString, String filename, String startPoint) {
if (prefix.equalsIgnoreCase(startPoint))
{
seen = true;
}
if (counter == 0) {
if (startPoint.length() != lengthOfPermutationString) {
for (int i = startPoint.length(); i < lengthOfPermutationString; i++) {
startPoint += str.charAt(0);
}
}
counter = -45;
}
if (prefix.length() == lengthOfPermutationString) {
boolean savethis = true;
for (int i = 0; i < prefix.length(); i++) {
savethis = this.saveThis(prefix, prefix.charAt(i), 13);
if (!savethis) {
break;
}
}
if (savethis && seen) {
System.out.println(prefix);
//permutation.add(prefix);
}
} else {
for (int i = 0; i < str.length(); i++) {
if (permutation.size() == 1000) {
FileClass.WriteFile("new.txt", permutation);
permutation.clear();
}
permutation(str, prefix + str.charAt(i), lengthOfPermutationString, filename, startPoint);
}
FileClass.WriteFile("new.txt", permutation);
permutation.clear();
}
}
}
=========================================================================
public class FileClass {
public static boolean WriteFile(String filename, List<String> doc) {
try {
if (!filename.contains(".txt")) {
filename += ".txt";
}
RandomAccessFile raf = new RandomAccessFile(filename, "rw");
String writer = "";
writer = doc.stream().map((string) -> string + "\n").reduce(writer, String::concat);
raf.seek(raf.length());
raf.writeBytes(writer);
raf.close();
} catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("Error");
new Scanner(System.in).nextLine();
return false;
}
return true;
}
static RandomAccessFile raf;
public static boolean fileExist(String filename, boolean delete){
File file = new File(filename);
if (file.exists() && delete)
{
return file.delete();
}
return file.exists();
}
public static void WriteFile(String filename, String text) {
try {
if (!filename.contains(".txt")) {
filename += ".txt";
}
raf = new RandomAccessFile(filename, "rw");
long length = raf.length();
raf.setLength(length + 1);
raf.seek(raf.length());
raf.writeBytes(text + "\n");
} catch (Exception e) {
}
}
private static void write(List<String> records, Writer writer) throws IOException {
for (String record : records) {
writer.write(record);
}
writer.flush();
writer.close();
}
public static void stringWriter(List<String> records, String filename) {
try {
File file = new File(filename);
FileWriter writer = new FileWriter(file, true);
write(records, writer);
} catch (Exception ex) {
System.out.println(ex.getMessage());
new Scanner(System.in).nextLine();
}
}
public static boolean CloseFile() {
try {
raf.close();
return true;
} catch (Exception e) {
return false;
}
}
}
In order to add a "Resume" mechanism, you need to make your program idempotent. One way to do it, is instead of saving the permutations - save to file the parameters that are sent to permutation on each iteration:
now each time that the program starts, it will check what were the last parameters that permutation was called with (the last line in the file), and start from there (when the program starts on the first time, nothing will be written in the file - so it will start from the beginning).
After that the recursion finished, we can call another method that will go over the lines of the file, and read only the permutations (ignoring the other parameters) and write them into a cleaner "final_result.txt" file.
Needless to say that this implementation is more costly (all the additional reads and write from disc) but that's the tradeoff for having it support "resume" operation.
To save/restore process in the middle of its work, you need something we can call a "state" and implement generating combinations in iterative way.
In my implementation the "state" is pos object (I assume set and k will not change on "resume").
My implementation of the problem would be following:
public class RepeatComb {
private int[] pos;
private String set;
public RepeatComb(String set, int k) {
this.set = set;
pos = new int[k];
}
public int[] getState() {return Arrays.copyOf(pos, pos.length);}
public void resume(int[] a) {pos = Arrays.copyOf(a,a.length);}
public boolean next() {
int i = pos.length-1;
for (int maxpos = set.length()-1; pos[i] >= maxpos; ) {
if (i==0) return false;
--i;
}
++pos[i];
while (++i < pos.length) pos[i]=0;
return true;
}
public String getCur() {
StringBuilder s = new StringBuilder(pos.length);
for (int i=0; i < pos.length; ++i)
s.append(set.charAt(pos[i]));
return s.toString();
}
public static void main(String[] args) {
int[] state;
String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
RepeatComb comb = new RepeatComb(text, 3);
int stop = 10; //break after 10
do {
if (stop-- == 0) break;
System.out.println(comb.getCur());
} while (comb.next());
//save state
state = comb.getState();
System.out.println("---------");
//resume (with the same args: text,3)
stop = 10; //break after 10
comb = new RepeatComb(text, 3);
comb.resume(state); // resume here
do {
if (stop-- == 0) break;
System.out.println(comb.getCur());
} while (comb.next());
}
}
Update: I've added functions for getting state and resuming from it
and example of use. state array can be saved in file, then restored.
I am taking an input file with various infix expressions, calculating them, and printing them back to another output file with each line formatted as:
THE MODULO 10 VALUE OF %%%%% IS %
The output text and modulo 10 answer are both correct; however, I cannot get the program to reprint the entire expression in between "OF" and "IS."
I tried putting output.write(token) in the getToken() method, but I got a "cannot find symbol" error. So I understand that I can't access the BufferedWriter from another method since it is declared in main, but how can I get around that?
import java.io.*;
public class Lab1
{
public static char token;
public static String expr;
public static int k = 0;
public static void main (String[] args)
{
int exprValue;
String line;
try
{
BufferedReader input = new BufferedReader(new FileReader("inputfile.txt"));
BufferedWriter output = new BufferedWriter(new FileWriter("outputfile.txt"));
while ((line = input.readLine()) != null)
{
output.write("THE MODULO 10 VALUE OF ");
expr = line;
getToken();
output.write(token);
exprValue = expression();
output.write(" IS " + exprValue);
output.newLine();
output.newLine();
k = 0;
}
input.close();
output.close();
}
catch (IOException ex)
{
System.err.println("Exception:" + ex);
}
}
public static void getToken()
{
k++;
int count = k-1;
if(count < expr.length())
{
token = expr.charAt(count);
}
}
public static int expression()
{
int termValue;
int exprValue;
exprValue = term();
while(token == '+')
{
getToken();
termValue = term();
exprValue = (exprValue + termValue)%10;
}
return exprValue;
}
public static int factor()
{
int factorValue = token;
if(Character.isDigit(token))
{
factorValue = Character.getNumericValue(token);
getToken();
}
else if(token == '(')
{
getToken();
factorValue = expression();
if(token == ')')
{
getToken();
}
}
return factorValue;
}
public static int term()
{
int factorValue;
int termValue;
termValue = factor();
while(token == '*')
{
getToken();
factorValue = factor();
termValue = (termValue * factorValue)%10;
}
return termValue;
}
}
Currently my input is:
(3*6+4)*(4+5*7)
3*((4+5*(1+6)+2))
My output is:
THE MODULO 10 VALUE OF ( IS 8
THE MODULO 10 VALUE OF 3 IS 3
Solved the problem. In the while loop in the main method, replace output.write(token) with output.write(expr)
I'm trying to make a 2d array of an object in java. This object in java has several private variables and methods in it, but won't work. Can someone tell me why and is there a way I can fix this?
This is the exeception I keep getting for each line of code where I try to initialize and iterate through my 2d object.
"Exception in thread "main" java.lang.NullPointerException
at wumpusworld.WumpusWorldGame.main(WumpusWorldGame.java:50)
Java Result: 1"
Here is my main class:
public class WumpusWorldGame {
class Agent {
private boolean safe;
private boolean stench;
private boolean breeze;
public Agent() {
safe = false;
stench = false;
breeze = false;
}
}
/**
* #param args
* the command line arguments
* #throws java.lang.Exception
*/
public static void main(String [] args) {
// WumpusFrame blah =new WumpusFrame();
// blah.setVisible(true);
Scanner input = new Scanner(System.in);
int agentpts = 0;
System.out.println("Welcome to Wumpus World!\n ******************************************** \n");
//ArrayList<ArrayList<WumpusWorld>> woah = new ArrayList<ArrayList<WumpusWorld>>();
for (int i = 0 ; i < 5 ; i++) {
WumpusWorldObject [] [] woah = new WumpusWorldObject [5] [5];
System.out.println( "*********************************\n Please enter the exact coordinates of the wumpus (r and c).");
int wumpusR = input.nextInt();
int wumpusC = input.nextInt();
woah[wumpusR][wumpusC].setPoints(-3000);
woah[wumpusR][wumpusC].setWumpus();
if ((wumpusR <= 5 || wumpusC <= 5) && (wumpusR >= 0 || wumpusC >= 0)) {
woah[wumpusR][wumpusC].setStench();
}
if (wumpusC != 0) {
woah[wumpusR][wumpusC - 1].getStench();
}
if (wumpusR != 0) {
woah[wumpusR - 1][wumpusC].setStench();
}
if (wumpusC != 4) {
woah[wumpusR][wumpusC + 1].setStench();
}
if (wumpusR != 4) {
woah[wumpusR + 1][wumpusC].setStench();
}
System.out.println( "**************************************\n Please enter the exact coordinates of the Gold(r and c).");
int goldR = input.nextInt();
int goldC = input.nextInt();
woah[goldR][goldC].setGold();
System.out.println("***************************************\n How many pits would you like in your wumpus world?");
int numPits = input.nextInt();
for (int k = 0 ; k < numPits ; k++) {
System.out.println("Enter the row location of the pit");
int r = input.nextInt();
System.out.println("Enter the column location of the pit");
int c = input.nextInt();
woah[r][c].setPit();
if ((r <= 4 || c <= 4) && (r >= 0 || c >= 0)) {
woah[r][c].setBreeze();
}
if (c != 0) {
woah[r][c - 1].setBreeze();
}
if (r != 0) {
woah[r - 1][c].setBreeze();
}
if (c != 4) {
woah[r][c + 1].setBreeze();
}
if (r != 4) {
woah[r + 1][c].setBreeze();
}
}
for (int x = 0 ; x < 4 ; x++) {
int j = 0;
while (j < 4) {
agentpts = agentpts + woah[x][j].getPoints();
Agent [] [] k = new Agent [4] [4];
if (woah[x][j].getWumpus() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("You just got ate by the wumpus!!! THE HORROR!! Your score is " + agentpts);
}
if (woah[x][j].getStench() == true) {
k[x][j].stench = true;
System.out.println("You smell something funny... smells like old person.");
}
if (woah[x][j].getBreeze() == true) {
k[x][j].breeze = true;
System.out.println("You hear a breeze. yeah");
}
if (woah[x][j].getPit() == true) {
agentpts = agentpts + woah[x][j].getPoints();
System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH! you dumb bith, your dead now.");
}
// if breeze or stench, if breeze and stench, if nothing, etc then move.
k[x][j].safe = true;
// if(k[i][j].isSafe()!=true){
// } else { }
}
}
}
}
}
Here is my class object that I'm trying to implement:
package wumpusworld;
/**
*
* #author Jacob
*/
public class WumpusWorldObject {
private boolean stench;
private boolean breeze;
private boolean pit;
private boolean wumpus;
private boolean gold;
private int points;
private boolean safe;
public WumpusWorldObject(){
}
public boolean getPit() {
return pit;
}
public void setPit() {
this.pit = true;
}
public boolean getWumpus() {
return wumpus;
}
public void setWumpus() {
this.wumpus = true;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public boolean getStench() {
return stench;
}
public void setStench() {
this.stench = true;
}
public boolean getBreeze() {
return breeze;
}
public void setBreeze() {
this.breeze = true;
}
public boolean getSafe() {
return safe;
}
public void setSafe() {
this.safe = true;
}
public void setGold(){
this.gold=true;
}
}
Creating array doesn't mean it will be automatically filled with new instances of your class. There are many reasons for that, like
which constructor should be used
what data should be passed to this constructor.
This kind of decisions shouldn't be made by compiler, but by programmer, so you need to invoke constructor explicitly.
After creating array iterate over it and fill it with new instances of your class.
for (int i=0; i<yourArray.length; i++)
for (int j=0; j<yourArray[i].length; j++)
yourArray[i][j] = new ...//here you should use constructor
AClass[][] obj = new AClass[50][50];
is not enough, you have to create instances of them like
obj[i][j] = new AClass(...);
In your code the line
woah[wumpusR][wumpusC].setPoints(-3000);
must be after
woah[wumpusR][wumpusC] = new WumpusWorldObject();
.