Testing test = new Testing(score);Java - Printerwriter - java

I'm doing a snake game, and I want after the game is over, the score is saved in a file
I did this, but there's error in the two lines that sends the value to the Testing Class
private boolean isGameOver(int headLocX, int headLocY) {
for (int i = SNAKE_LENGTH_DEFAULT; i < totalBodyPart - 2; i++) {
Point partLoc = snakeBodyPart[i].getLocation();
if (partLoc.equals(new Point(headLocX, headLocY))) {
Testing test = new Testing(score);
return true;
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Testing
{
public Testing(int score)
{
File file = new File("C:\\Users\\Eng. Mohammed\\Desktop\\Snake 1.0.1\\Snake\\Score.Txt");
PrintWriter printWriter = null;
try
{
printWriter = new PrintWriter(file);
printWriter.println(score);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
finally
{
if ( printWriter != null )
{
printWriter.close();
}
}
}
}

Change this method
private boolean isGameOver(int headLocX, int headLocY) {
for (int i = SNAKE_LENGTH_DEFAULT; i < totalBodyPart - 2; i++) {
Point partLoc = snakeBodyPart[i].getLocation();
if (partLoc.equals(new Point(headLocX, headLocY))) {
Testing test = new Testing();
Testing(score);//It is an invalid call no method is defined like this or a class can't be initialized like this.
return true;
}
}
TO
private boolean isGameOver(int headLocX, int headLocY) {
for (int i = SNAKE_LENGTH_DEFAULT; i < totalBodyPart - 2; i++) {
Point partLoc = snakeBodyPart[i].getLocation();
if (partLoc.equals(new Point(headLocX, headLocY))) {
Testing test = new Testing(score);//This is the correct way to initialize the Testing class.
return true;
}
}

Related

BufferOverflowException in java threads

Receiving an exception "BufferOverflowException" while running sikuli script via threads. The same script works properly without thread object. I have no clue what causes the bufferoverflowexception. Please guide.
Sample Code:-
import org.sikuli.script.*; // Library import
public class Sikuli {
private Screen screen = new Screen();
private Pattern getPattern(String imagePath) {
return new Pattern(imagePath);
}
public void click(String imagePath) throws FindFailed, InterruptedException {
screen.click(getPattern(imagePath));
}
public void sendKeys(String value) {
screen.type(value);
}
import Sukuli // Custom sikuli class import
public class foo {
Sikuli sk = new Sikuli();
public void test() {
Thread t1 = new Thread(() -> {
sk.click(new Pattern("imagePath"));
sk.type("fooboo");
});
t1.start();
}
}
From Sikuli Library Methods which are being referred by my class methods:-
public int type(String text) {
try {
return this.keyin((Object)null, text, 0);
} catch (FindFailed var3) {
return 0;
}
}
private <PFRML> int keyin(PFRML target, String text, int modifiers) throws FindFailed {
if (target != null && 0 == this.click(target, 0)) {
return 0;
} else {
Debug profiler = Debug.startTimer("Region.type", new Object[0]);
if (text != null && !"".equals(text)) {
String showText = "";
for(int i = 0; i < text.length(); ++i) {
showText = showText + Key.toJavaKeyCodeText(text.charAt(i));
}
String modText = "";
String modWindows = null;
if ((modifiers & 4) != 0) {
modifiers -= 4;
modifiers |= 4;
log(3, "Key.WIN as modifier", new Object[0]);
modWindows = "Windows";
}
if (modifiers != 0) {
modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers));
if (modWindows != null) {
modText = modText.replace("Meta", modWindows);
}
}
Debug.action("%s TYPE \"%s\"", new Object[]{modText, showText});
log(3, "%s TYPE \"%s\"", new Object[]{modText, showText});
profiler.lap("before getting Robot");
IRobot r = this.getRobotForRegion();
int pause = 20 + (Settings.TypeDelay > 1.0 ? 1000 : (int)(Settings.TypeDelay * 1000.0));
Settings.TypeDelay = 0.0;
profiler.lap("before typing");
r.typeStarts();
for(int i = 0; i < text.length(); ++i) {
r.pressModifiers(modifiers);
r.typeChar(text.charAt(i), KeyMode.PRESS_RELEASE);
r.releaseModifiers(modifiers);
r.delay(pause);
}
r.typeEnds();
profiler.lap("after typing, before waitForIdle");
r.waitForIdle();
profiler.end();
return 1;
} else {
return 0;
}
}
}
Trace logs:-
[log] CLICK on L[1517,53]#S(0) (555 msec)[log] TYPE "fooboo"Exception in thread "Thread-4" java.nio.BufferOverflowException
at java.nio.Buffer.nextPutIndex(Buffer.java:521)
at java.nio.HeapByteBuffer.put(HeapByteBuffer.java:169)
at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeString(AbstractStreamEncoder.java:127)
at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encodeStringData(AbstractStreamEncoder.java:171)
at org.apache.maven.surefire.api.stream.AbstractStreamEncoder.encode(AbstractStreamEncoder.java:157)
at org.apache.maven.surefire.booter.spi.EventChannelEncoder.encodeMessage(EventChannelEncoder.java:398)
at org.apache.maven.surefire.booter.spi.EventChannelEncoder.setOutErr(EventChannelEncoder.java:188)
at org.apache.maven.surefire.booter.spi.EventChannelEncoder.testOutput(EventChannelEncoder.java:183)
at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:113)
at org.apache.maven.surefire.api.booter.ForkingRunListener.writeTestOutput(ForkingRunListener.java:44)
at org.apache.maven.surefire.common.junit4.JUnit4RunListener.writeTestOutput(JUnit4RunListener.java:235)
at org.apache.maven.surefire.api.report.ConsoleOutputCapture$ForwardingPrintStream.println(ConsoleOutputCapture.java:144)
at org.sikuli.basics.Debug.log(Debug.java:881)
at org.sikuli.basics.Debug.action(Debug.java:645)
at org.sikuli.script.Region.keyin(Region.java:4613)
at org.sikuli.script.Region.type(Region.java:4493)
at Sikuli.sendKeys(Sikuli.java:87)

Serialization with implemenation

Hey so I'm new to using serialization, at least the way that our professor wants us to. I have the issue that for some reason it will not serialize even with java.io.Serializable implemented. I tried the direct path and "Serializable" neither work. Im not sure whats going wrong or why, as far as I understand there should not be any methods that I need to implement, correct?
THE ERROR I GET
java.io.NotSerializableException: Transaction
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
at TransactionManager.serialize(TransactionManager.java:81)
at Test3.main(Test3.java:62)
java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: Transaction
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1598)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
at TransactionManager.deSerialize(TransactionManager.java:96)
at Test3.main(Test3.java:67)
Caused by: java.io.NotSerializableException: Transaction
at java.base/java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1185)
at java.base/java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:349)
at TransactionManager.serialize(TransactionManager.java:81)
at Test3.main(Test3.java:62)
THE CODE
import java.awt.print.Book;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class TransactionManager implements Serializable {
private ArrayList<Transaction> col;
public TransactionManager() {
col = new ArrayList<Transaction>();
}
public void add(Transaction obj) {
col.add(obj);
}
public void clear() {
col.clear();
}
public int getCount() {
return col.size();
}
public ArrayList<Transaction> getAll() {
ArrayList<Transaction> temp = col;
Collections.sort(temp, new Comparator<Transaction>() {
public int compare(Transaction s1, Transaction s2) {
return ((Integer) s1.getId()).compareTo(s2.getId());
}
});
return temp;
}
public ArrayList<Transaction> findBuyer(String name) {
ArrayList<Transaction> temp = new ArrayList<>();
for (int i = 0; i < col.size(); i++) {
if (col.get(i).getBuyer().equals(name)) {
temp.add(col.get(i));
}
}
Collections.sort(temp, new Comparator<Transaction>() {
public int compare(Transaction s1, Transaction s2) {
return ((Integer) s1.getId()).compareTo(s2.getId());
}
});
return temp;
}
public ArrayList<Transaction> findSeller(String name) {
ArrayList<Transaction> temp = new ArrayList<>();
for (int i = 0; i < col.size(); i++) {
if (col.get(i).getSeller().equals(name)) {
temp.add(col.get(i));
}
}
Collections.sort(temp, new Comparator<Transaction>() {
public int compare(Transaction s1, Transaction s2) {
return ((Integer) s1.getId()).compareTo(s2.getId());
}
});
return temp;
}
public Transaction findId(int ID) {
for (int i = 0; i < col.size(); i++) {
if (col.get(i).getId() == ID) {
return col.get(i);
}
}
return null;
}
public void serialize() throws IOException {
FileOutputStream output = new FileOutputStream(new File("savePerson.ser"));
ObjectOutputStream outputStream = new ObjectOutputStream(output);
for (int i = 0; i < col.size(); i++) {
outputStream.writeObject(col.get(i));
}
output.close();
outputStream.close();
}
public void deSerialize() throws IOException, ClassNotFoundException {
FileInputStream inputStream = new FileInputStream(new File("savePerson.ser"));
boolean cont = true;
try {
ObjectInputStream ois = new ObjectInputStream(inputStream);
while (cont) {
Transaction obj = null;
try {
obj = (Transaction) ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
if (obj != null)
col.add(obj);
else
cont = false;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
inputStream.close();
}
}
}

Why am I getting "missing return statement" error in Java even though I have return statement and exception in thread main error in 2nd class?

For example, I am getting the error here- this is just a snippet. I got the error 3 times in 3 different operators.
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
I also have the same error here:
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
And then in my second class (the user interface portion), I keep getting this error: Exception in thread "main" java.lang.NoClassDefFoundError: Directory
Here is the entire code for that class:
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) throws IOException {
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
And here is the code for my directory class:
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return true;
else
return false;
}
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
The point is that the compiler can't know if your for loop will be entered at all. Therefore you need a final return after the end of the for loop, too. In other words: any path that can possibly be taken within your method needs a final return statement. One easy way to achieve this ... is to have only one return statement; and put that on the last line of the method. This could look like:
Object getSomething() {
Object rv = null; // rv short for "returnValue"
for (int i=0; i < myArray.length; i++) {
if (whatever) {
rv = godKnowsWhat;
} else {
rv = IdontCare;
}
}
return rv;
}
In your second example, the indenting seems to indicate that you have a return in the else statement
directory[directorySize++] = name;
return true;
But when you look closer, you will realize that there are TWO statements after the else
else
directory[directorySize++] = name;
return true;
So this actually reads like
else
directory[directorySize++] = name;
return true;
Meaning: always put {braces} around all your blocks, even for (supposedly) one-liner then/else lines. That helps to avoid such mistakes, when a one-liner turns into a two-liner (or vice versa ;-)
The "NoClassDefFoundException" means: within the classpath that is specified to java ... there is no class Directory.class
To resolve that, you should study what the java classpath is about; and how to set it correctly.

How can i return an array in java that is accessible by other objects?

I want to return an array that is accessible by other objects after having read a text file. My instruction parsing class is:
import java.io.*;
public class Instruction {
public String[] instructionList;
public String[] readFile() throws IOException {
FileInputStream in = new FileInputStream("directions.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
}
The above takes in a text file with 5 lines of text in it. In my main() I want to run that function and have the string array be accessible to other objects.
import java.util.Arrays;
public class RoverCommand {
public static void main(String[] args) throws Exception {
Instruction directions = new Instruction();
directions.readFile();
String[] directionsArray;
directionsArray = directions.returnsInstructionList();
System.out.println(Arrays.toString(directionsArray));
}
}
What's the best way to do that? I would need the elements of the array to be integers if they are numbers and strings if they are letters. P.S. I'm brand new to Java. is there a better way to do what I'm doing?
You don't have to use generics. I try to catch exceptions in the accessors and return null if anything blows up. So you can test if the value returned is null before proceeding.
// Client.java
import java.io.IOException;
public class Client {
public static void main(String args[]) {
try {
InstructionList il = new InstructionList();
il.readFile("C:\\testing\\ints.txt", 5);
int[] integers = il.getInstructionsAsIntegers();
if (integers != null) {
for (int i : integers) {
System.out.println(i);
}
}
} catch (IOException e) {
// handle
}
}
}
// InstructionList.java
import java.io.*;
public class InstructionList {
private String[] instructions;
public void readFile(String path, int lineLimit) throws IOException {
FileInputStream in = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
instructions = new String[lineLimit];
for (int i = 0; i < lineLimit; i++) {
instructions[i] = br.readLine();
}
in.close();
}
public String[] getInstructionsAsStrings() {
return instructions; // will return null if uninitialized
}
public int[] getInstructionsAsIntegers() {
if (this.instructions == null) {
return null;
}
int[] instructions = new int[this.instructions.length];
try {
for (int i = 0; i < instructions.length; i++) {
instructions[i] = new Integer(this.instructions[i]);
}
} catch (NumberFormatException e) {
return null; // data integrity fail, return null
}
return instructions;
}
}
check instructionList is null or not. if it is null, call readFile method.
public String[] returnsInstructionList() {
if (instructionList== null){
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
because of readFile can throw exception, it would be good to use one extra variable. like:
private boolean fileReaded = false;
public String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
and if readFile can be run concurrently, easiest way to make function synchronized, like
private boolean fileReaded = false;
public synchronized void readFile() throws IOException {
.
.
.
}
public synchronized String[] returnsInstructionList() {
if (!fileReaded){
fileReaded = true;
try { readFile(); } catch(Exception e){}
}
return instructionList;
}
There is no guarantee that readFile is called before returnsInstructionList is invoked. Leaving you returnsInstructionList returning null.
I would :
public String[] getContentsFromFile(String fileName) throws IOException {
FileInputStream in = new FileInputStream(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
int n = 5;
instructionList = new String[n];
for (int j = 0; j < instructionList.length; j++) {
instructionList[j] = br.readLine();
}
in.close();
return instructionList;
}
Part two to the question you can use generics. To achieve what you want but you have to incorporate a way to say what it is.
Eg
public class Foo {
public ReturnForFoo returnAStringOrIntger(boolean val) {
if(val){
return new ReturnForFoo("String", ValueType.STRING) ;
}
return new ReturnForFoo(10, ValueType.INTEGER); //int
}
}
public class ReturnForFoo {
Object value;
ValueType type;
public ReturnForFoo(Object value, ValueType type) {
this.value=value;
this.type=type
}
// Asume you have getters for both value and value type
public static ENUM ValueType {
STRING,
INTEGER,
UNKNOWN
}
}
This code is in your main.
Foo foo = new Foo();
String value;
int val;
ReturnForFoo returnForFoo = foo.returnAStringOrIntger(true);
// NOTE you can use switch instead of if's and else if's. It will be better
if(returnForFoo.getValueType().equals(ValueType.INTEGER)){
val = (int) returnForFoo.getValue();
} else if(returnForFoo.getValueType().equals(ValueType.STRING)){
value = (String) returnForFoo.getValue();
} else {
// UNKOWN Case
}

Queue that has objects returns true for isEmpty() Java

I have a program that creates a queue, enqueues objects to the queue and then dequeues them one by one if the queue is not empty. The problem I am having is that the queue comes up empty each time it is checked. Print is called on the queue after enqueuing each object and it prints the queue's contents just fine.
import java.util.*;
import java.io.*;
public class Processor2
{
private LinkedQueue queue = new LinkedQueue();
private int time = 0;
private int count = 100;
private int amount = 0;
private PrintWriter out;
private Person temp;
private boolean var;
private Random randomNum = new Random();;
private String turn;
private int popCount=0;
private int loopCount =0;
public void start()
{
amount = randomNum.nextInt(5);
amount += 5;
pop(amount, time);
sim();
}
public void pop(int num, int time)
{
for(int i=1; i<=num; i++)
{
Person pe = new Person(i, time, 0);
queue.enqueue(pe);
System.out.println(queue);
}
popCount += num;
}
public void sim()
{
try
{
out = new PrintWriter(new FileWriter("output.txt"));
while(loopCount<=100)
{
var = queue.isEmpty();
if(var=true)
{
System.out.println("queue is empty");
}
if(var=false)
{
Object temp = queue.dequeue();
double rand = Math.random();
if(rand < 0.5)
{
System.out.println("inside if else statement");
// does stuff with object //
loopCount++;
}
else
{
System.out.println("inside if else statement");
// does stuff with object //
loopCount++;
}
}
}
out.close();
}
catch (IOException ioe)
{
System.out.println("Error Writing to File: " + ioe);
}
}
}
there doesn't seem to be anything wrong with the queue's isEmpty() method, but here it is:
public boolean isEmpty()
{
if(count == 0)
{
return true;
}
else
{
return false;
}
}
var = queue.isEmpty();
if(var=true) // this line *sets* var to true
{
System.out.println("queue is empty");
}
If you change if (var=true) to if(var==true) or just if(var) you should see a different result

Categories

Resources