Unexpected error with my class - java

When writing a class it is giving me an expected token error and I can not figure out how to solve it or why it is giving it to me.
Here's the code:
public class SetUpDoors {
private int DoorAmount;
private int WinningDoorAmount;
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
void setDoorAmount(int userDoors){
DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
WinningDoorAmount = userWinningDoors;
}
}
it is giving the error on the ; at the end of private int winnerSelect = 0;
and an error for the } right below DoorAmount--;
The first is expected token "{" and the second is add "}" to complete block.

You must declare following code inside a method.
For example:
public void newMethod(){
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}

try this
public class SetUpDoors {
private int DoorAmount;
private int WinningDoorAmount;
private int[] DoorArray= new int[DoorAmount];
private int winnerSelect = 0;
{
for (int i = 0; i < DoorAmount; i++) {
if (WinningDoorAmount > 0) {
winnerSelect = (int) Math.round( Math.random());
DoorArray[i] = winnerSelect;
if(winnerSelect == 1) {
WinningDoorAmount--;
}
}
else {
DoorArray[i] = 0;
}
DoorAmount--;
}
}
void setDoorAmount(int userDoors){
DoorAmount = userDoors;
}
void setWinningDoorAmount(int userWinningDoors) {
WinningDoorAmount = userWinningDoors;
}
}

Related

Where is a problem with this multithreading code?

I want to calculate sum of 2D array with multithreading. But I can't get correct result and programm can't end for some reason.
MatrixService devides task to threads and contains result. (methods getSumma() and setSumma(int summa) are taken from Herbert Schildt)
public class MatrixService {
private boolean valueGet = false;
private int summa;
public int sum(int[][] matrix, int nThreads) {
for (int i = 0; i < nThreads; i++) {
new ColumnSummator(this, matrix, nThreads, i);
}
return summa;
}
public synchronized int getSumma() {
while (valueGet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
valueGet = true;
notify();
return summa;
}
public synchronized void setSumma(int summa) {
while (!valueGet) {
try {
wait();
} catch (InterruptedException e) {
System.out.println(e.getMessage());
}
}
this.summa = summa;
valueGet = false;
notify();
}
}
ColumnSummator choose columns for sum which this Thread should calculate
import java.util.ArrayList;
import java.util.List;
public class ColumnSummator implements Runnable {
private int summOfColumns;
private final MatrixService matrixService;
private final int[][] matrix;
private final List<Integer> numberColumnsForCount = new ArrayList<>();
public ColumnSummator(MatrixService matrixService, int[][] matrix, int nThreads, int columnSummatorId) {
this.matrixService = matrixService;
this.matrix = matrix;
for (int i = 0; i < matrix[0].length; i++) {
if (i % nThreads == columnSummatorId) {
numberColumnsForCount.add(i);
}
}
new Thread(this).start();
}
#Override
public void run() {
for (int i = 0; i < matrix[0].length; i++) {
if (numberColumnsForCount.contains(i)) {
for (int j = 0; j < matrix.length; j++) {
summOfColumns += matrix[j][i];
}
}
}
matrixService.setSumma(matrixService.getSumma() + summOfColumns);
}
}
And inside main:
public static void main(String[] args) {
MatrixService matrixService = new MatrixService();
int[][] matrix = new int[10][10];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
matrix[i][j] = (i + 1) * (j + 1);
}
}
int summa = matrixService.sum(matrix, 6);
System.out.println(summa);
}

New to Programming (Java) - dont know how to fix an error with a small Console Game simular to Snake

I just started to learn Java and am working on a small project which is supposed to create a gameField in a 2 dimensional String Array Field Borders are marked with a "#". In this Field I want to spawn a player who is marked as ">". This player can then turn left or right (∧ for looking up for example) and then has the option to move forward one space.
I currently have the gameField created and now want to spawn the player into that 2 dimensional String Array for which I have made a spawnPlayer method/function in the class Player. I now want to add / open that method/function in the main method. This is where I am getting the error messages and dont know what to do.
public class KonsolenWanderer {
public static void main(String[] args) {
Field field1 = new Field();
field1.createField();
Player player1 = new Player();
//Error is here!!!
player1.spawnPlayer();
}
}
public class Field {
private String [][] fieldSize = new String [10][10];
public void createField() {
for(int i = 0; i < fieldSize.length; i++) {
for(int j = 0; j < fieldSize[i].length; j++) {
//Creating Field Border
if(i == 0 || i == 9 || j == 0 || j == 9) {
fieldSize[i][j] = "#";
}
else {
fieldSize[i][j] = " ";
}
System.out.print(fieldSize[i][j]);
}
System.out.println();
}
}
public String[][] getFieldSize() {
return fieldSize;
}
public void setFieldSize(String[][] fieldSize) {
this.fieldSize = fieldSize;
}
}
public class Player {
private static int xPosition;
private static int yPosition;
private String up = "∧";
private String down = "∨";
private String left = "<";
private String right = ">";
private String currentDirection;
Player() {
xPosition = 4;
yPosition = 4;
}
public void spawnPlayer(String[][]fieldSize) {
fieldSize[xPosition][yPosition] = ">";
}
public static void moveForward() {
}
public static void turnPlayerLeft() {
}
public static void turnPlayerRight() {
}
}
You need to set the position inside the field object or expose fieldSize from within Field class.
public class KonsolenWanderer {
public static void main(String[] args) {
Field field = new Field();
field.createField();
Player player1 = new Player();
//Error is here!!!
player1.spawnPlayer(new String[8][8], field);
field.showField();
}
}
class Field {
private String [][] fieldSize = new String [10][10];
public void createField() {
for(int i = 0; i < fieldSize.length; i++) {
for(int j = 0; j < fieldSize[i].length; j++) {
//Creating Field Border
if(i == 0 || i == 9 || j == 0 || j == 9) {
fieldSize[i][j] = "#";
}
else {
fieldSize[i][j] = " ";
}
System.out.print(fieldSize[i][j]);
}
System.out.println();
}
}
public void showField() {
for(int i = 0; i < fieldSize.length; i++) {
for(int j = 0; j < fieldSize[i].length; j++) {
System.out.print(fieldSize[i][j]);
}
System.out.println();
}
}
public String[][] getFieldSize() {
return fieldSize;
}
public void setFieldSize(String[][] fieldSize) {
this.fieldSize = fieldSize;
}
public void setPlayerPosition(int i, int j) {
i++;
j++;
fieldSize[i][j] = ">";
}
}
class Player {
private static int xPosition;
private static int yPosition;
private String up = "∧";
private String down = "∨";
private String left = "<";
private String right = ">";
private String currentDirection;
Player() {
xPosition = 4;
yPosition = 4;
}
public void spawnPlayer(String[][] fieldSize, Field field) {
for(int i = 0; i < fieldSize.length; i++) {
if (i == fieldSize.length -1){
for(int j = 0; j < fieldSize[i].length; j++) {
if (j == fieldSize.length - 1 )
field.setPlayerPosition(i, j);
}
}
}
}
public static void moveForward() {
}
public static void turnPlayerLeft() {
}
public static void turnPlayerRight() {
}
}

Array-based implementation of a sorted linked list

I need to write a java linked list which needs to be array based and sorted. So the array contains nodes which have 2 fields: the data, and the index of the next element in the list. The last element of the list needs to have an index of -1.
Can someone help how to add an element to such list. this is the code I wrote so far but does not seems to be right because I can add elements but the indexes are not right.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
public ArrayLL(){
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException{
if(this.getSize() == 0){
ANode a = new ANode(s, -1);
list[0] = a;
}else if(size == MAX_CAP + 1){
throw new IOException("List is full");
}else{
int index = 0;
for(int i=0; i < list.length; i++){
if(list[i].getData() == null){
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if(this.getSize()==1){
if (list[index].getData().compareTo(list[0].getData()) < 0){
list[index].setLink(0);
list[0].setLink(-1);
}else{
list[index].setLink(-1);
list[0].setLink(index);
}
}else{
int i = 0;
while(list[i].getData() != null){
if(list[index].getData().compareTo(list[i].getData()) < 0){
list[index].setLink(i);
if(i>0)
list[i-1].setLink(index);
}else{
i++;
}
}
}
}
size++;
}
public ANode[] getList(){
return list;
}
public int getSize(){
return size;
}
}
class ANode{
private String data;
private int link;
public ANode(String d){
data = d;
link = -1;
}
public ANode(String d, int l){
data = d;
link = l;
}
public String getData(){
return data;
}
public int getLink(){
return link;
}
public void setLink(int l){
link = l;
}
}
It was fun to solve this tricky program... :-)... i enjoyed it...here is the working solution...I tested using various scenarios...
In order to make sure I do not change much of your code...I did not optimize the code..there are many places where code can be more simpler and readable...
import java.io.IOException;
public class ArrayLL {
public static void main(String[] args) throws IOException {
ArrayLL myList = new ArrayLL();
myList.addElem("c");
myList.addElem("b");
myList.addElem("a");
myList.addElem("d");
int i = myList.startOfListIndex;
while(myList.list[i].getLink()!=-1)
{
System.out.println(myList.list[i].getData());
i = myList.list[i].getLink();
}
System.out.println(myList.list[i].getData());
}
private int MAX_CAP = 100;
private ANode[] list;
private int size;
private int startOfListIndex = 0;
public ArrayLL() {
list = new ANode[MAX_CAP];
for (int i = 0; i < list.length; i++) {
list[i] = new ANode(null);
}
size = 0;
}
public void addElem(String s) throws IOException {
if (this.getSize() == 0) {
ANode a = new ANode(s, -1);
list[0] = a;
} else if (size == MAX_CAP + 1) {
throw new IOException("List is full");
} else {
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getData() == null) {
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if (this.getSize() == 1) {
if (list[index].getData().compareTo(list[0].getData()) < 0) {
list[index].setLink(0);
list[0].setLink(-1);
startOfListIndex = index;
} else {
list[index].setLink(-1);
list[0].setLink(index);
}
} else {
int i = startOfListIndex;
int prevIndex = -1;
while (i!=-1 && list[i].getData() != null) {
if (list[index].getData().compareTo(list[i].getData()) < 0) {
list[index].setLink(i);
if(prevIndex!=-1)
list[prevIndex].setLink(index);
else
startOfListIndex = index;
break;
} else {
prevIndex = i;
i=list[i].getLink();
}
}
if(i==-1)
{
list[prevIndex].setLink(index);
}
}
}
size++;
}
public ANode[] getList() {
return list;
}
public int getSize() {
return size;
}
}
class ANode {
private String data;
private int link;
public ANode(String d) {
data = d;
link = -1;
}
public ANode(String d, int l) {
data = d;
link = l;
}
public String getData() {
return data;
}
public int getLink() {
return link;
}
public void setLink(int l) {
link = l;
}
}
This is the full solution i believe as it works for all the test i have done, but there might be something i haven't thought of. The solution includes the removeElem() method too.
package listpackage;
import java.io.IOException;
public class ArrayLL {
private int MAX_CAP = 100;
private ANode[] list;
private int size;
private int startOfListIndex = 0;
public ArrayLL() {
list = new ANode[MAX_CAP];
list[list.length-1] = new ANode(null, -1);
for(int i = 0; i < list.length-1; i++){
list[i] = new ANode(null, i+1);
}
size = 0;
}
public void addElem(String s) throws IOException {
if (this.getSize() == 0) {
ANode a = new ANode(s, -1);
list[0] = a;
}else if (size == MAX_CAP + 1) {
throw new IOException("List is full");
}else{
int index = 0;
for (int i = 0; i < list.length; i++) {
if (list[i].getData() == null) {
index = i;
break;
}
}
ANode b = new ANode(s);
list[index] = b;
if (this.getSize() == 1) {
if (list[index].getData().compareTo(list[0].getData()) < 0) {
list[index].setLink(0);
list[0].setLink(-1);
startOfListIndex = index;
} else {
list[index].setLink(-1);
list[0].setLink(index);
}
} else {
int i = startOfListIndex;
int prevIndex = -1;
while (i!=-1 && list[i].getData() != null) {
if (list[index].getData().compareTo(list[i].getData()) < 0) {
list[index].setLink(i);
if(prevIndex!=-1)
list[prevIndex].setLink(index);
else
startOfListIndex = index;
break;
}else{
prevIndex = i;
i=list[i].getLink();
}
}
if(i==-1)
{
list[prevIndex].setLink(index);
}
}
}
size++;
}
public void removeElem(String s) throws IOException {
if (this.getSize() == 0) {
throw new IOException("List is empty");
}else{
int firstEmpty = 0;
for(int i = 0; i< list.length; i++){
if(list[i].getData() == null){
firstEmpty = i;
break;
}
}
int elemindex = 0;
int prev = -1;
int next=-1;
for(int i = 0; i < list.length; i++){
if(list[i].getData() != null && list[i].getData().compareTo(s) == 0){
elemindex = i;
next = list[i].getLink();
for(int j = 0; j < list.length; j++){
if(list[j].getLink() == elemindex){
prev = j;
break;
}
}
list[elemindex].setDataNull();
list[elemindex].setLink(firstEmpty);
if(next != -1)
list[prev].setLink(next);
else
list[prev].setLink(-1);
size--;
}else{
elemindex++;
}
}
}
}
public ANode[] getList() {
return list;
}
public int getSize() {
return size;
}
}
class ANode {
private String data;
private int link;
public ANode(String d) {
data = d;
link = -1;
}
public ANode(String d, int l) {
data = d;
link = l;
}
public String getData() {
return data;
}
public void setDataNull(){
this.data = null;
}
public int getLink() {
return link;
}
public void setLink(int l) {
link = l;
}
}

"A Java Exception has occurred"

So I'm trying to run my pacman project as a jar(also tried runnable) and I just get the error message you see in the title. It runs perfectly fine in eclipse/netbeans, but whilst cleaning/building i see the warnings:
Note: C:\Users\Lucas\Documents\Eclipse\PackMan\src\game\packman\GameData.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
The main class is correct and assigned. Does anybody know what I'm doing wrong?
Here is my GameData class
public class GameData {
int mazeNo;
CopyOnWriteArrayList<Position> pills;
CopyOnWriteArrayList<Position> powerPills;
public MoverInfo packman;
public GhostInfo[] ghostInfos = new GhostInfo[4];
public int score;
Maze[] mazes;
boolean dead = false;
boolean win = false;
public GameData() {
mazes = new Maze[4];
// load mazes information
for (int m=0; m<4; m++) {
mazes[m] = new Maze(m);
}
setMaze(mazeNo);
}
private void setMaze(int m) {
packman = new MoverInfo(mazes[m].packmanPos);
for (int g=0; g<4; g++) {
ghostInfos[g] = new GhostInfo(mazes[m].ghostPos);
}
pills = new CopyOnWriteArrayList((List<Position>)(mazes[m].pills.clone()));
powerPills = new CopyOnWriteArrayList((List<Position>)(mazes[m].powerPills.clone()));
}
public void movePackMan(int reqDir) {
if (move(reqDir, packman)) {
packman.curDir = reqDir;
} else {
move(packman.curDir, packman);
}
}
private int wrap(int value, int incre, int max) {
return (value+max+incre)%max;
}
private boolean move(int reqDir, MoverInfo info) {
// current position of packman is (row, column)
int row = info.pos.row;
int column = info.pos.column;
int rows = mazes[mazeNo].rows;
int columns = mazes[mazeNo].columns;
int nrow = wrap(row, MoverInfo.DROW[reqDir], rows);
int ncol = wrap(column, MoverInfo.DCOL[reqDir], columns);
if (mazes[mazeNo].charAt(nrow, ncol) != '0') {
info.pos.row = nrow;
info.pos.column = ncol;
return true;
}
return false;
}
public void update() {
if (pills.contains(packman.pos)) {
pills.remove(packman.pos);
score += 5;
} else if (powerPills.contains(packman.pos)) {
powerPills.remove(packman.pos);
score += 50;
for (GhostInfo g:ghostInfos) {
g.edibleCountDown = 500;
}
}
for (GhostInfo g:ghostInfos) {
if (g.edibleCountDown > 0) {
if (touching(g.pos, packman.pos)) {
// eat the ghost and reset
score += 100;
g.curDir = g.reqDir = MoverInfo.LEFT;
g.pos.row = mazes[mazeNo].ghostPos.row;
g.pos.column = mazes[mazeNo].ghostPos.column;
g.edibleCountDown = 0;
}
g.edibleCountDown--;
} else {
if (touching(g.pos, packman.pos)) {
dead = true;
}
}
}
// level is cleared
if (pills.isEmpty() && powerPills.isEmpty()) {
mazeNo++;
if (mazeNo < 4) {
setMaze(mazeNo);
} else if (mazeNo == 5) {
win = true;
} else {
// game over
dead = true;
}
}
}
private boolean touching(Position a, Position b) {
return Math.abs(a.row-b.row) + Math.abs(a.column-b.column) < 3;
}
public void moveGhosts(int[] reqDirs) {
for (int i=0; i<4; i++) {
GhostInfo info = ghostInfos[i];
info.reqDir = reqDirs[i];
if (move(info.reqDir, info)) {
info.curDir = info.reqDir;
} else {
move(info.curDir, info);
}
}
}
public int getWidth() {
return mazes[mazeNo].width;
}
public int getHeight() {
return mazes[mazeNo].height;
}
public List<Integer> getPossibleDirs(Position pos) {
List<Integer> list = new ArrayList<>();
for (int d=0; d<4;d++) {
Position npos = getNextPositionInDir(pos, d);
if (mazes[mazeNo].charAt(npos.row, npos.column) != '0') {
list.add(d);
}
}
return list;
}
private Position getNextPositionInDir(Position pos, int d) {
int nrow = wrap(pos.row, MoverInfo.DROW[d], mazes[mazeNo].rows);
int ncol = wrap(pos.column, MoverInfo.DCOL[d], mazes[mazeNo].columns);
return new Position(nrow, ncol);
}
}

Test fixture wont initialise an array

I am trying to test my journey class methods, however, any method that uses the jArray field gives a null pointer exception as the arraylist has not actually been created. I was under the impression that my test fixture would address this yet the problem persists, any help appreciated.
private buscard.Journey tj1;
private buscard.Journey tj2;
/**
* Default constructor for test class JourneyTest
*/
public JourneyTest()
{
tj1 = new buscard.Journey(20120101, 120000, "74", 1);
tj2 = new buscard.Journey(20120102, 120000, "74", 1);
ArrayList<Journey> jArray = new ArrayList<Journey>();
jArray.add(tj1);
}
/**
* Sets up the test fixture.
*
* Called before every test case method.
*/
protected void setUp()
{
tj1 = new buscard.Journey(20120101, 120000, "74", 1);
tj2 = new buscard.Journey(20120102, 120000, "74", 1);
ArrayList<Journey> jArray = new ArrayList<Journey>();
jArray.add(tj1);
}
public void testGetDate()
{
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals(20120101, testJ1.getDate());
}
public void testGetTime(){
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals(12.0, testJ1.getTime());
}
public void testGetBusNumber(){
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals("74", testJ1.getBusNumber());
}
public void testConstructor(){
Journey testJ1 = new Journey(20120101, 12.00, "74", 1);
assertEquals("74", testJ1.getBusNumber());
assertEquals(12.0, testJ1.getTime());
assertEquals(20120101, testJ1.getDate());
}
}
package buscard;
import java.util.ArrayList;
/**
* Write a description of class journey here.
*
* #author (your name)
* #version (a version number or a date)
*/
class Journey
{
public int date;
public double time;
public String busNumber;
public int journeyType;
public static double dayCharge = 0;
public static final double maxDayCharge = 3.50;
public static double weekCharge = 0;
public static final double maxWeekCharge = 15;
public static double monthCharge = 0;
public static final double maxMonthCharge = 48;
private int journeyNumber;
private static int numberOfJourneys = 0;
public double costOfJourney;
public static ArrayList<Journey> jArray;
public Journey(int date, double time, String busNumber, int journeyType)
{
this.date = date;
this.time = time;
this.busNumber = busNumber;
this.journeyType = journeyType;
journeyNumber = ++numberOfJourneys;
}
static
{
ArrayList<Journey> jArray = new ArrayList<Journey>();
}
public int getDate(){
return date;
}
public double getTime(){
return time;
}
public String getBusNumber(){
return busNumber;
}
public double getCostOfJourney(){
return costOfJourney;
}
public int getJourneyType(){
return journeyType;
}
public boolean isInSequence(int date, double time){
Journey prevJourney = jArray.get(jArray.size()-1);
return((prevJourney.getDate() < date)||(prevJourney.getDate() == date && prevJourney.time < time));
}
public static double returnLeast(){
double d = maxDayCharge - dayCharge;
double m = maxMonthCharge - monthCharge;
double w = maxWeekCharge - weekCharge;
double least = 0;
if (d <= w && d <= m)
{
least = d;
}
else if(w <= d && w <= m)
{
least = w;
}
else if(m <= d && m <= w)
{
least = m;
}
return least;
}
public double journeyCost(Journey reqJourney){
if (journeyType == 1){
if (dayCharge <= 2.50 && weekCharge <= 14 && monthCharge <= 47)
{
costOfJourney = 1;
}
else
{
costOfJourney = returnLeast();
}
}
else if (journeyType == 2)
{
if (dayCharge <= 1.80 && weekCharge <= 13.30 && monthCharge <= 46.30)
{
costOfJourney = 1.70;
}
else
{
costOfJourney = returnLeast();
}
}
else if (journeyType == 3)
{
if (dayCharge <= 1.60 && weekCharge <= 13.10 && monthCharge <= 46.10)
{
costOfJourney = 1.90;
}
else
{
costOfJourney = returnLeast();
}
}
return costOfJourney;
}
public static void updateCurrentCharges(int date){
int newDayOfYear = DateFunctions.getYearDay(date);
int newWeekOfYear = DateFunctions.getYearWeek(date);
int newMonthOfYear = DateFunctions.getYearMonth(date);
if (newDayOfYear > WmBusPass.dayOfYear)
{
WmBusPass.dayOfYear = newDayOfYear;
dayCharge = 0;
}
if (newWeekOfYear > WmBusPass.weekOfYear)
{
WmBusPass.weekOfYear = newWeekOfYear;
weekCharge = 0;
}
if (newMonthOfYear > WmBusPass.monthOfYear)
{
WmBusPass.monthOfYear = newMonthOfYear;
monthCharge = 0;
}
}
}
jArray is static field of Journey class.
You should replace
ArrayList<Journey> jArray = new ArrayList<Journey>();
with
buscard.Journey.jArray = new ArrayList<Journey>();

Categories

Resources