Resolving a code with an infinite loop - java

I have a code for optimumRequestOrder. It has 3 main methods: request(int len, int Qty), request(int len) and calculate().
Unfortunately, calculate code goes for infinite loop when trying big numbers such as (Integer.Max_value, Integer.Max_value).
import java.io.PrintStream;
public class OptimumRequestOrder {
private int xstdLen;
private int maxRequest;
private int len = 0;
private int[][] dataRequest;
public OptimumRequestOrder(int size) {
this.maxRequest = size;
this.len = 0;
this.dataRequest = new int[this.maxRequest][this.maxRequest];
}
public void setStdLen(int stdLen) {
this.xstdLen = stdLen;
}
public void request(int inLength, int inQty) {
if (!full()) {
this.dataRequest[this.len][0] = inLength;
this.dataRequest[this.len][1] = inQty;
this.len += 1;
} else {
System.err.println("Overflow\n");
}
}
public void delRequest(int inLength) {
int temp = 0;
if (!empty()) {
for (int i = 0; i < this.len; i++) {
if (this.dataRequest[i][0] == inLength) {
temp = i;
}
}
for (int i = temp; i < this.len; i++) {
this.dataRequest[i][0] = this.dataRequest[(i + 1)][0];
this.dataRequest[i][1] = this.dataRequest[(i + 1)][1];
}
len = len - 1;
} else {
System.err.println("Underflow");
}
}
public int[][] getDataRequest() {
return this.dataRequest;
}
public int getLen() {
return this.len;
}
public int calculate() {
if (!empty()) {
int balance = this.xstdLen;
int totalLen = 1;
int i = 0;
int[][] dataR = this.dataRequest;
System.out.println("ni dataR===>" + dataR[0][0] + " " + dataR[0][1]);
while (wloop1(dataR)) {
System.out.println("wloop1=" + i + " : " + dataR[i][0] + " qty: " + dataR[i][1]);
if (i < this.len) {
System.out.println("balance=" + balance);
if (balance >= dataR[i][0]) {
System.out.println("QTY " + i + ": " + dataR[i][1]);
if (dataR[i][1] > 0) {
balance -= dataR[i][0];
dataR[i][1] -= 1;
} else {
System.out.println("Qty=0");
i += 1;
totalLen += 1;
}
} else {
System.out.println("balance kurang");
i += 1;
}
} else if (wloop0(dataR, balance)) {
System.out.println("balance masih boleh ditolak");
if (wloop1(dataR)) {
System.out.println("balance masih boleh ditolak n qty<>0");
i = 0;
} else {
System.out.println("balance masih boleh ditolak n qty=0");
return totalLen;
}
} else {
System.out.println("balance dah tak boleh ditolak");
if (wloop1(dataR)) {
System.out.println("balance tiada n qty<>0");
i = 0;
balance = this.xstdLen;
totalLen += 1;
System.out.println("totalLen==>>>>" + totalLen);
} else {
System.out.println("balance tiada n qty=0");
return totalLen;
}
}
}
return totalLen;
}
System.err.println("Underflow");
return 0;
}
public boolean wloop0(int[][] dataR, int bal) {
for (int i = 0; i < this.len; i++) {
if ((bal >= dataR[i][0]) && (dataR[i][1] > 0)) {
return true;
}
}
return false;
}
public boolean wloop1(int[][] dataR) {
for (int i = 0; i < this.len; i++) {
if (dataR[i][1] > 0) {
return true;
}
}
return false;
}
public boolean empty() {
return this.len == 0;
}
public boolean full() {
return this.len == this.maxRequest;
}
public void printq() {
System.out.print("len: " + this.len);
for (int i = 0; i < this.len; i++) {
System.out.print("dataR[" + i + ",0]=" + this.dataRequest[i][0] + "; ");
System.out.print("dataR[" + i + ",1]=" + this.dataRequest[i][1] + "; ");
}
System.out.println();
}
}
Please help me in resolving this problem.

Related

Binary heap output not as expected

I have a homework that the teacher test if it's corrects by checking it's output using this website moodle.caseine.org, so to test my code the program execute these lines and compare the output with the expected one, this is the test :
Tas t = new Tas();
Random r = new Random(123);
for(int i =0; i<10000;i++)t.inser(r.nextInt());
for(int i =0;i<10000;i++)System.out.println(t.supprMax());
System.out.println(t);
And my Heap (Tas) class:
package td1;
import java.util.ArrayList;
import java.util.List;
public class Tas {
private List<Integer> t;
public Tas() {
t = new ArrayList<>();
}
public Tas(ArrayList<Integer> tab) {
t = new ArrayList<Integer>(tab);
}
public static int getFilsGauche(int i) {
return 2 * i + 1;
}
public static int getFilsDroit(int i) {
return 2 * i + 2;
}
public static int getParent(int i) {
return (i - 1) / 2;
}
public boolean estVide() {
return t.isEmpty();
}
#Override
public String toString() {
String str = "";
int size = t.size();
if (size > 0) {
str += "[" + t.get(0);
str += toString(0);
str += "]";
}
return str;
}
public boolean testTas() {
int size = t.size();
int check = 0;
if (size > 0) {
for (int i = 0; i < t.size(); i++) {
if (getFilsGauche(i) < size) {
if (t.get(i) < t.get(getFilsGauche(i))) {
check++;
}
}
if (getFilsDroit(i) < size) {
if (t.get(i) < t.get(getFilsDroit(i))) {
check++;
}
}
}
}
return check == 0;
}
public String toString(int i) {
String str = "";
int size = t.size();
if (getFilsGauche(i) < size) {
str += "[";
str += t.get(getFilsGauche(i));
str += toString(getFilsGauche(i));
str += "]";
}
if (getFilsDroit(i) < size) {
str += "[";
str += t.get(getFilsDroit(i));
str += toString(getFilsDroit(i));
str += "]";
}
return str;
}
//insert value and sort
public void inser(int value) {
t.add(value);
int index = t.size() - 1;
if (index > 0) {
inserCheck(index); // O(log n)
}
}
public void inserCheck(int i) {
int temp = 0;
int parent = getParent(i);
if (parent >= 0 && t.get(i) > t.get(parent)) {
temp = t.get(parent);
t.set(parent, t.get(i));
t.set(i, temp);
inserCheck(parent);
}
}
//switch position of last element is list with first (deletes first and return it)
public int supprMax() {
int size = t.size();
int max = 0;
if (size > 0) {
max = t.get(0);
t.set(0, t.get(size - 1));
t.remove(size - 1);
supprMax(0);
}
else {
throw new IllegalStateException();
}
return max;
}
public void supprMax(int i) {
int size = t.size();
int temp = 0;
int index = i;
if (getFilsGauche(i) < size && t.get(getFilsGauche(i)) > t.get(index)) {
index = getFilsGauche(i);
}
if (getFilsDroit(i) < size && t.get(getFilsDroit(i)) > t.get(index)) {
index = getFilsDroit(i);
}
if (index != i) {
temp = t.get(index);
t.set(index, t.get(i));
t.set(i, temp);
supprMax(index);
}
}
public static void tri(int[] tab) {
Tas tas = new Tas();
for (int i = 0; i < tab.length; i++) {
tas.inser(tab[i]);
}
for (int i = 0; i < tab.length; i++) {
tab[i] = tas.supprMax();
}
}
}
The last 3 lines of the test are :
-2145024521
-2147061786
-2145666206
But the last 3 of my code are :
-2145024521
-2145666206
-2147061786
The problem are probably with the inser and supprMax methods.
I hate to get a bad grade just because of 3 lines placement, because it is a program that verify the code, it dosn't care the the solution was close, it's still says it's wrong.

Creating a Word List array that can be modified by adding and removing words

In this problem, I am attempting to begin with an array and add or remove words. My problem so far is adding words. I want to have an array String[] {"",""} and fill this up, and if a word is repeated, do nothing. So, add("computer"), add("again"), and add("computer") would result in {"computer", "again"} and give me count 3. I keep getting {"computer", "computer", "again"} remove("computer") would result in {"again", "again"} and give me count 1. Could on look at this code and help?
public class WordList {
public String[] words;
int count;
public WordList() {
count = 0;
words = new String[] {"",""};
}
public int addWord(String w) {
WordList r = new WordList();
int x = r.findWord(w);
int y = words.length;
if (x>-1) {
return count;
}
else if (x==-1) {
if (count < words.length) {
words[count] = w;
}
else if (count == words.length) {
String[] nwords = new String[words.length * 2];
for (int i = 0; i < words.length; i++) {
nwords[i] = words[i];
}
words = nwords;
words[y] = w;
}
count++;
}
return count;
}
public void removeWord(String s) {
WordList r = new WordList();
int x = r.findWord(s);
if (x == -1) {
return;
}
if (x>-1) {
for (int j=0;j<words.length;j++) {
words[j] = words[j+1];
count--;
}
}
return;
}
public int findWord(String w) {
for (int i =0;i<words.length; i++) {
if (w.equals(words[i])) {
return i;
}
}
return -1;
}
public boolean equals(WordList other) {
if (words.length != other.count) {
return false;
} else {
for (int i = 0; i < words.length; i++) {
if (words[i] != other.words[i]) {
return false;
}
}
}
return true;
}
public String toString() {
String s = "There are " + count + " word" + ((words.length == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl.addWord("abacus"));
System.out.println(wl.addWord("computer"));
wl.removeWord("computer");
}
}
First of all. Please consider Arraylist or Map.
Nevertheless i tried to keep changes to the minimal
public class WordList {
public String[] words;
int count;
public WordList() {
count = 0;
words = new String[] {"",""};
}
public int addWord(String w) {
//WordList r = new WordList();
int x = findWord(w);
int y = words.length;
if (x>-1) {
return count++;
}
else if (x==-1) {
if (count < words.length) {
words[count] = w;
}
else if (count == words.length) {
String[] nwords = new String[words.length * 2];
for (int i = 0; i < words.length; i++) {
nwords[i] = words[i];
}
words = nwords;
words[y] = w;
}
count++;
}
return count;
}
public void removeWord(String s) {
//WordList r = new WordList();
int x = findWord(s);
if (x == -1) {
return;
}
if (x>-1) {
for (int j=0;j<words.length;j++) {
if(words.length < j+1 && !words[j+1].isBlank()){
words[j] = words[j+1];
}
}
count--;
}
return;
}
public int findWord(String w) {
for (int i =0;i<words.length; i++) {
if (w.equals(words[i])) {
return i;
}
}
return -1;
}
public boolean equals(WordList other) {
if (words.length != other.count) {
return false;
} else {
for (int i = 0; i < words.length; i++) {
if (words[i] != other.words[i]) {
return false;
}
}
}
return true;
}
public String toString() {
String s = "There are " + count + " word" + ((words.length == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl);
System.out.println(wl.addWord("abacus"));
System.out.println(wl);
System.out.println(wl.addWord("computer"));
System.out.println(wl);
wl.removeWord("computer");
System.out.println(wl);
}
}
The severe ones are:
1. You are working on new instances of wordlist (r) when adding and removing which is absolutely wrong.
2. When removing word you have to check the length of word before going for j+1
You should use a Set, not an array.
That will reduce your code to:
class WordList {
private Set<String> words;
public WordList() {
words = new HashSet<>();
}
public int addWord(String w) {
words.add(w);
return words.size();
}
public void removeWord(String s) {
words.remove(s);
}
public boolean findWord(String w) {
return words.contains(w);
}
public boolean equals(WordList other) {
return this.words.equals(other.words);
}
#Override
public String toString() {
String s = "There are " + words.size() + " word" + ((words.size() == 1)?"":"s") + " in the word list:\n";
for (String w : words) {
s = s + w + "\n";
}
return s;
}
public static void main(String[] args) {
WordList wl = new WordList();
System.out.println(wl.addWord("computer"));
System.out.println(wl.addWord("abacus"));
System.out.println(wl.addWord("computer"));
wl.removeWord("computer");
}
}
Output
1
2
2

Postfix to Infix program that needs fixing

I need help with this program because it is not compiling correctly.
The program is supposed to do this:
java PostfixToInfix
1 2 3 + *
1*(2+3)
I am getting these errors when compiling:
PostfixToInfix.java:64: error: bad operand types for binary operator '-'
s.push(o2 - o1);
^
first type: String
second type: String
PostfixToInfix.java:68: error: bad operand types for binary operator '*'
s.push(o1 * o2);
^
first type: String
second type: String
2 errors
How many I supposed to code this so that it works properly? I am unsure what is wrong with my code that it is not allowing it do the functions properly.
This is my code:
import java.util.Scanner;
import java.util.Stack;
public class PostfixToInfix
{
public static void main(String[] args)
{
String[] input = readExpr();
if(checkSyntax(input) == true)
{
int k = 0;
Stack<String> s = new Stack<>();
for(int i = 0; i < input.length; ++i)
{
if(isOperator(input[i]))
{
String o1;
String o2;
if(!(s.empty()))
{
o1 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(!(s.empty()))
{
o2 = s.pop();
}
else
{
for(int j = 0; j < i; ++j)
{
k += input[j].length() + 1;
}
System.out.println("Too few operands for " + input[i]);
writeExpr(input);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
return;
}
if(input[i].equals("+"))
{
s.push(o1 + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 - o1);
}
else
{
s.push(o1 * o2);
}
}
else
{
s.push(input[i]);
}
}
String Result = s.pop();
if(!(s.empty()))
{
System.out.println("Too few operators to produce a single result");
}
else
{
System.out.println(Result);
}
}
} // end main
static String[] readExpr()
{
Scanner stdin = new Scanner(System.in);
String s = stdin.nextLine();
String[] sA = s.split(" ");
return sA;
}
static void writeExpr(String[] expr)
{
for(int i = 0; i < expr.length; ++i)
{
System.out.print(expr[i] + " ");
}
System.out.println();
}
static boolean isOperator(String s)
{
if(s.equals("+") || s.equals("-") || s.equals("*"))
{
return true;
}
return false;
}
static boolean checkSyntax(String[] expr)
{
int k = 0;
for(int i = 0; i < expr.length; ++i)
{
if(!(isOperator(expr[i])))
{
try
{
Double.parseDouble(expr[i]);
}
catch (Exception e)
{
for(int j = 0; j < i; ++j)
{
k += expr[j].length() + 1;
}
writeExpr(expr);
for(int l = 0; l < k; ++l)
{
System.out.print(" ");
}
System.out.println("^");
System.out.println("Not a number or valid operator");
return false;
}
}
}
return true;
}
} // end Postfix2
class StringStack
{
int top;
String[] pancake;
StringStack() //constructor for a new empty stack
{
top = 0;
pancake = new String[1000];
} // end DoubleStack
boolean empty() //whether the stack is empty
{
return top == 0;
} // end empty
String pop() //remove and return the top element; throw an error if empty
{
if(empty())
{
throw new Error("Error");
}
top -= 1;
return pancake[top];
} // end pop
void push(String x) //add x to the top of the stack
{
if(top < 1000)
{
pancake[top] = x;
top += 1;
}
else{
throw new Error("Error");
}
} // end push
} // end StringStack
Change you code like this.
if(input[i].equals("+"))
{
s.push(o1 + "+" + o2);
}
else if(input[i].equals("-"))
{
s.push(o2 + "-" + o1);
}
else
{
s.push(o1 + "*" + o2);
}
But the result for "1 2 3 + *" is "3+2*1".
It is another problem.

Difficulty navigating 2d String array that correlates to another 2d int array

So I have a class that holds a bunch of stat info and such about a "gamer". I'm trying to implement a mock trophy system for certain stat goals that were achieved through an RNG.
I have a 2d int array that holds values for the grade/level of the trophy, that once achieved upgrades the trophy from bronze, to silver, etc and a corresponding 2d String array that holds the titles of such trophy levels. In testing what seemed to work with a now unused method actually provided trophies to only certain types. What I have now is a path I think I need to follow in order for this to work. I have a method called getBadges(int requestedStat) that takes an index value for another array to view that stats trophies. In that method is a for loop that compares the method's argument to both 2d arrays to determine if the stat's value (stored in another array) qualifies it for a bronze, silver, or gold trophy. My main problem is I'm getting lost in how to access these different data points in my 2d arrays without going out of the index's range. Not to mention when I set up a bunch of if-else statements my test output always produced the trophy's name, but no trophy level. Like such:
Healer: No Badge
Explorer: No Badge
Socialite: No Badge
Contributor: No Badge
As the skill points go up so should the badge levels (i.e. go from "No Badge" to "Bronze" etc). Is this a logic or syntax error? I'm super confused on what is happening in my code, despite my pseudo-code efforts. Here is the Gamer class:
package GamerProject;
import java.io.Serializable;
import java.util.Comparator;
public class Gamer implements Serializable, Comparable<Gamer> {
private String playerName;
private static final int HEALTH_POINTS_RESD = 23;
private static final int AREAS_VISITED = 200;
private static final int PLAYERS_ENCOUNTERED = 175;
private static final int MAPS_CREATED = 1500;
private static final int ITEMS_GATHERED = 20;
private static final int ITEMS_REPAIRED = 100;
private static final int ITEMS_MERGED = 125;
private static final int TOP_SCORES = 250;
private static final int DMG_POINTS_DEALT = 17;
private static final int MAPS_COMPLETED = 750;
private static final int LEVEL2 = 10000;
private static final int LEVEL3 = 25000;
private static final int LEVEL4 = 80000;
private static final int LEVEL5 = 150000;
private static final int LEVEL6 = 300000;
private static final int LEVEL7 = 1000000;
private static final int LEVEL8 = 2200000;
private static final int LEVEL9 = 4500000;
private static final int LEVEL10 = 10000000;
private static final int LEVEL11 = 20000000;
private static final int LEVEL12 = 35000000;
private final int[] gamerStatValues = new int[10];
private final int[] gamerActions = {HEALTH_POINTS_RESD, AREAS_VISITED, PLAYERS_ENCOUNTERED, MAPS_CREATED,
ITEMS_GATHERED, ITEMS_REPAIRED, ITEMS_MERGED, TOP_SCORES, DMG_POINTS_DEALT, MAPS_COMPLETED};
private final int[] expValues = {LEVEL2, LEVEL3, LEVEL4, LEVEL5, LEVEL6, LEVEL7,
LEVEL8, LEVEL9, LEVEL10, LEVEL11, LEVEL12};
private final int[][] badgePoints = {
{0, 2000, 10000, 30000, 100000, 200000},
{0, 50, 1000, 5000, 17000, 40000},
{0, 100, 1000, 2000, 10000, 30000},
{0, 3, 10, 20, 90, 150},
{0, 2000, 10000, 30000, 100000, 200000},
{0, 100, 1000, 5000, 15000, 40000},
{0, 100, 500, 2000, 10000, 40000},
{0, 20, 200, 1000, 5000, 20000},
{0, 2000, 10000, 30000, 100000, 300000},
{0, 10, 50, 200, 500, 5000}};
private final String[] badgeTitles = {"Healer: ", "Explorer: ", "Socialite: ", "Contributor: ",
"Hoarder: ", "Fixer: ", "Joiner: ", "Leader: ", "Punisher: ", "Obsessed: ",};
private final String[] badgeRanks = {"No Badge ", "Tin ", "Bronze ", "Silver ", "Gold ", "Platinum "};
Gamer() {
playerName = "";
}
public int getTotalExp() {
int totalExp = 0;
for (int i = 0; i < gamerStatValues.length; i++) {
totalExp += (gamerStatValues[i] * gamerActions[i]);
}
return totalExp;
}
public int getLevel() {
int playerLevel = 1;
int totalExp = getTotalExp();
for (int i = 0; i < expValues.length; i++) {
if (totalExp >= expValues[i]) {
playerLevel += 1;
//System.out.println(getTotalExp());
}
}
return playerLevel;
}
public String getBadge(int requestedStat) {
String badgeOutput = "";
//index = 0;
if (requestedStat >= 0 && requestedStat <=9) {
for (int i = 0; i < badgeRanks.length; i++) {//not sure how to get around going out of the array bounds
if (gamerActions[requestedStat] >= badgePoints[requestedStat][i]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 1]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i];
} else if (gamerActions[requestedStat] >= badgePoints[requestedStat][i+1]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 2]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i+1];
}
}
//did this as an extraneous solution. Still doesn't work
// if (gamerActions[requestedStat] >= badgePoints[requestedStat][index]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 1]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+1]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 2]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+1];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+2]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 3]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+2];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+3]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 4]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+3];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+4]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 5]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+4];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+5]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 6]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+5];
// } else {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+6];
// }
//
} else {
badgeOutput = "No Badges Available";
}
return badgeOutput;
}
//Incomplete Method
public String getBadges() {
String badgeOutput = "Badges: ";
for (int i = 0; i < badgeTitles.length; i++) {
// if (gamerActions[i]) {
//
// }
}
return badgeOutput;
}
public String getPlayerName() {
return playerName;
}
public int getHealthPointsResd() {
return gamerStatValues[0];
}
public int getAreasVisited() {
return gamerStatValues[1];
}
public int getPlayersEncountered() {
return gamerStatValues[2];
}
public int getMapsCreated() {
return gamerStatValues[3];
}
public int getItemsGathered() {
return gamerStatValues[4];
}
public int getItemsRepaired() {
return gamerStatValues[5];
}
public int getItemsMerged() {
return gamerStatValues[6];
}
public int getTopScores() {
return gamerStatValues[7];
}
public int getDmgPointsDealt() {
return gamerStatValues[8];
}
public int getMapsCompleted() {
return gamerStatValues[9];
}
//Unused Method
public void updateRandomGamerAction(int intValue) {
if (intValue == 0) {
gamerActions[0]+=1;
} else if (intValue == 1) {
gamerActions[1]+=1;
} else if (intValue == 2) {
gamerActions[2]+=1;
} else if (intValue == 3) {
gamerActions[3]+=1;
} else if (intValue == 4) {
gamerActions[4]+=1;
} else if (intValue == 5) {
gamerActions[5]+=1;
} else if (intValue == 6) {
gamerActions[6]+=1;
} else if (intValue == 7) {
gamerActions[7]+=1;
} else if (intValue == 8) {
gamerActions[8]+=1;
} else {
gamerActions[9]+=1;
}
}
public String setPlayerName(String playerName) {
this.playerName = playerName;
return this.playerName;
}
public int setHealthPointsResd(int healthPointsResd) {
if (healthPointsResd >= 0) {
gamerStatValues[0] = healthPointsResd;
return gamerStatValues[0];
} else {
return gamerStatValues[0];
}
}
public int setAreasVisited(int areasVisited) {
if (areasVisited >= 0) {
gamerStatValues[1] = areasVisited;
return gamerStatValues[1];
} else {
return gamerStatValues[1];
}
}
public int setPlayersEncountered(int playersEncountered) {
if (playersEncountered >= 0) {
gamerStatValues[2] = playersEncountered;
return gamerStatValues[2];
} else {
return gamerStatValues[2];
}
}
public int setMapsCreated(int mapsCreated) {
if (mapsCreated >= 0) {
gamerStatValues[3] = mapsCreated;
return gamerStatValues[3];
} else {
return gamerStatValues[3];
}
}
public int setItemsGathered(int itemsGathered) {
if (itemsGathered >= 0) {
gamerStatValues[4] = itemsGathered;
return gamerStatValues[4];
} else {
return gamerStatValues[4];
}
}
public int setItemsRepaired(int itemsRepaired) {
if (itemsRepaired >= 0) {
gamerStatValues[5] = itemsRepaired;
return gamerStatValues[5];
} else {
return gamerStatValues[5];
}
}
public int setItemsMerged(int itemsMerged) {
if (itemsMerged >= 0) {
gamerStatValues[6] = itemsMerged;
return gamerStatValues[6];
} else {
return gamerStatValues[6];
}
}
public int setTopScores(int topScores) {
if (topScores >= 0) {
gamerStatValues[7] = topScores;
return gamerStatValues[7];
} else {
return gamerStatValues[7];
}
}
public int setDmgPointsDealt(int dmgPointsDealt) {
if (dmgPointsDealt >= 0) {
gamerStatValues[8] = dmgPointsDealt;
return gamerStatValues[8];
} else {
return gamerStatValues[8];
}
}
public int setMapsCompleted(int mapsCompleted) {
if (mapsCompleted >= 0) {
gamerStatValues[9] = mapsCompleted;
return gamerStatValues[9];
} else {
return gamerStatValues[9];
}
}
public void setStatsToZero(){
for (int i = 0; i < gamerActions.length; i++) {
gamerActions[i] = 0;
}
}
public String statsString() {
return "Stats: " + "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
public String shortDecription() {
return String.format("%16s: Level %2d, Experience Points: %,10d",
playerName, this.getLevel(), this.getTotalExp());
}
#Override
public String toString() {
return "Gamer{" + "Player Name = " + playerName + " Player Stats: "
+ "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
#Override
public int compareTo(Gamer player) {
if (this.getTotalExp() > player.getTotalExp()) {
return 1;
} else if (this.getTotalExp() == player.getTotalExp()) {
return 0;
} else {
return -1;
}
}
}
and here is the driver I'm testing it with:
package GamerProject;
import java.util.Random;
public class Program7Driver {
private static final int rngRange = 10;
private static final Gamer[] gamers = new Gamer[10];
private static final String[] gamerNames = {"BestGamer99", "CdrShepardN7",
"Gandalf_The_Cool", "SharpShooter01", "TheDragonborn", "SithLord01",
"MrWolfenstien", "Goldeneye007", "DungeonMaster91", "MasterThief","TheDarkKnight"};
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < gamers.length; i++) {
gamers[i] = new Gamer();
gamers[i].setPlayerName(gamerNames[i]);
gamers[i].setStatsToZero();
}
// for (int i = 0; i < 200000; i++) {
// int rng = rand.nextInt(rngRange);
// gamers[rng].setRandomGamerAction(rng);
// }
int count = 0;
for (int i = 0; i < 20000; i++) {
int rng = rand.nextInt(rngRange);
System.out.println(gamers[0].getBadge(count));
//System.out.println(gamers[0].toString());
//gamers[0].updateRandomGamerAction(rng);
if (rng == 0) {
gamers[0].setHealthPointsResd(gamers[0].getHealthPointsResd()+1);
} else if (rng == 1) {
gamers[0].setAreasVisited(gamers[0].getAreasVisited()+1);
} else if (rng == 2) {
gamers[0].setPlayersEncountered(gamers[0].getPlayersEncountered()+1);
} else if (rng == 3) {
gamers[0].setMapsCreated(gamers[0].getMapsCreated()+1);
} else if (rng == 4) {
gamers[0].setItemsGathered(gamers[0].getItemsGathered()+1);
} else if (rng == 5) {
gamers[0].setItemsRepaired(gamers[0].getItemsRepaired()+1);
} else if (rng == 6) {
gamers[0].setItemsMerged(gamers[0].getItemsMerged()+1);
} else if (rng == 7) {
gamers[0].setTopScores(gamers[0].getTopScores()+1);
} else if (rng == 8) {
gamers[0].setDmgPointsDealt(gamers[0].getDmgPointsDealt()+1);
} else {
gamers[0].setMapsCompleted(gamers[0].getMapsCompleted()+1);
}
count += 1;
if (count == 10) {
count -= 10;
}
// System.out.println(gamers[i].statsString());
}
}
}
Okay, I made some changes. See if this does what you were wanting:
package GamerProject;
import java.io.Serializable;
import java.util.Comparator;
public class Gamer implements Serializable, Comparable<Gamer> {
/**
*
*/
private static final long serialVersionUID = 1L;
private String playerName;
private static final int HEALTH_POINTS_RESD = 23;
private static final int AREAS_VISITED = 200;
private static final int PLAYERS_ENCOUNTERED = 175;
private static final int MAPS_CREATED = 1500;
private static final int ITEMS_GATHERED = 20;
private static final int ITEMS_REPAIRED = 100;
private static final int ITEMS_MERGED = 125;
private static final int TOP_SCORES = 250;
private static final int DMG_POINTS_DEALT = 17;
private static final int MAPS_COMPLETED = 750;
private static final int LEVEL2 = 10000;
private static final int LEVEL3 = 25000;
private static final int LEVEL4 = 80000;
private static final int LEVEL5 = 150000;
private static final int LEVEL6 = 300000;
private static final int LEVEL7 = 1000000;
private static final int LEVEL8 = 2200000;
private static final int LEVEL9 = 4500000;
private static final int LEVEL10 = 10000000;
private static final int LEVEL11 = 20000000;
private static final int LEVEL12 = 35000000;
private final int[] gamerStatValues = new int[10];
private final int[] gamerActions = {HEALTH_POINTS_RESD, AREAS_VISITED, PLAYERS_ENCOUNTERED, MAPS_CREATED,
ITEMS_GATHERED, ITEMS_REPAIRED, ITEMS_MERGED, TOP_SCORES, DMG_POINTS_DEALT, MAPS_COMPLETED};
private final int[] expValues = {LEVEL2, LEVEL3, LEVEL4, LEVEL5, LEVEL6, LEVEL7,
LEVEL8, LEVEL9, LEVEL10, LEVEL11, LEVEL12};
private final int[][] badgePoints = {
{0, 2000, 10000, 30000, 100000, 200000},
{0, 50, 1000, 5000, 17000, 40000},
{0, 100, 1000, 2000, 10000, 30000},
{0, 3, 10, 20, 90, 150},
{0, 2000, 10000, 30000, 100000, 200000},
{0, 100, 1000, 5000, 15000, 40000},
{0, 100, 500, 2000, 10000, 40000},
{0, 20, 200, 1000, 5000, 20000},
{0, 2000, 10000, 30000, 100000, 300000},
{0, 10, 50, 200, 500, 5000}};
private final String[] badgeTitles = {"Healer: ", "Explorer: ", "Socialite: ", "Contributor: ",
"Hoarder: ", "Fixer: ", "Joiner: ", "Leader: ", "Punisher: ", "Obsessed: ",};
private final String[] badgeRanks = {"No Badge ", "Tin ", "Bronze ", "Silver ", "Gold ", "Platinum "};
Gamer() {
playerName = "";
}
public int getTotalExp() {
int totalExp = 0;
for (int i = 0; i < gamerStatValues.length; i++) {
totalExp += (gamerStatValues[i] * gamerActions[i]);
}
return totalExp;
}
public int getLevel() {
int playerLevel = 1;
int totalExp = getTotalExp();
for (int i = 0; i < expValues.length; i++) {
if (totalExp >= expValues[i]) {
playerLevel += 1;
//System.out.println(getTotalExp());
}
}
return playerLevel;
}
public String getBadge(int requestedStat) {
String badgeOutput = "";
//index = 0;
if (requestedStat >= 0 && requestedStat <=9) {
for (int i = 0; i < badgeRanks.length; i++) {//not sure how to get around going out of the array bounds
if (gamerActions[requestedStat] >= badgePoints[requestedStat][i]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 1]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i];
} else if (gamerActions[requestedStat] >= badgePoints[requestedStat][i+1]
&& gamerActions[requestedStat] < badgePoints[requestedStat][i + 2]) {
badgeOutput = badgeTitles[requestedStat] + badgeRanks[i+1];
}
}
//did this as an extraneous solution. Still doesn't work
// if (gamerActions[requestedStat] >= badgePoints[requestedStat][index]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 1]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+1]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 2]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+1];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+2]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 3]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+2];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+3]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 4]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+3];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+4]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 5]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+4];
// } else if (gamerActions[requestedStat] >= badgePoints[requestedStat][index+5]
// && gamerActions[requestedStat] < badgePoints[requestedStat][index + 6]) {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+5];
// } else {
// badgeOutput = badgeTitles[requestedStat] + badgeRanks[index+6];
// }
//
} else {
badgeOutput = "No Badges Available";
}
return badgeOutput;
}
//Incomplete Method
public String getBadges() {
String badgeOutput = "Badges: ";
for (int i = 0; i < badgeTitles.length; i++) {
// if (gamerActions[i]) {
//
// }
}
return badgeOutput;
}
public String getPlayerName() {
return playerName;
}
public int getHealthPointsResd() {
return gamerStatValues[0];
}
public int getAreasVisited() {
return gamerStatValues[1];
}
public int getPlayersEncountered() {
return gamerStatValues[2];
}
public int getMapsCreated() {
return gamerStatValues[3];
}
public int getItemsGathered() {
return gamerStatValues[4];
}
public int getItemsRepaired() {
return gamerStatValues[5];
}
public int getItemsMerged() {
return gamerStatValues[6];
}
public int getTopScores() {
return gamerStatValues[7];
}
public int getDmgPointsDealt() {
return gamerStatValues[8];
}
public int getMapsCompleted() {
return gamerStatValues[9];
}
//Unused Method
public void updateRandomGamerAction(int intValue) {
if (intValue == 0) {
gamerActions[0]+=1;
} else if (intValue == 1) {
gamerActions[1]+=1;
} else if (intValue == 2) {
gamerActions[2]+=1;
} else if (intValue == 3) {
gamerActions[3]+=1;
} else if (intValue == 4) {
gamerActions[4]+=1;
} else if (intValue == 5) {
gamerActions[5]+=1;
} else if (intValue == 6) {
gamerActions[6]+=1;
} else if (intValue == 7) {
gamerActions[7]+=1;
} else if (intValue == 8) {
gamerActions[8]+=1;
} else {
gamerActions[9]+=1;
}
}
public String setPlayerName(String playerName) {
this.playerName = playerName;
return this.playerName;
}
public int setHealthPointsResd(int healthPointsResd) {
if (healthPointsResd >= 0) {
gamerStatValues[0] = healthPointsResd;
return gamerStatValues[0];
} else {
return gamerStatValues[0];
}
}
public int setAreasVisited(int areasVisited) {
if (areasVisited >= 0) {
gamerStatValues[1] = areasVisited;
return gamerStatValues[1];
} else {
return gamerStatValues[1];
}
}
public int setPlayersEncountered(int playersEncountered) {
if (playersEncountered >= 0) {
gamerStatValues[2] = playersEncountered;
return gamerStatValues[2];
} else {
return gamerStatValues[2];
}
}
public int setMapsCreated(int mapsCreated) {
if (mapsCreated >= 0) {
gamerStatValues[3] = mapsCreated;
return gamerStatValues[3];
} else {
return gamerStatValues[3];
}
}
public int setItemsGathered(int itemsGathered) {
if (itemsGathered >= 0) {
gamerStatValues[4] = itemsGathered;
return gamerStatValues[4];
} else {
return gamerStatValues[4];
}
}
public int setItemsRepaired(int itemsRepaired) {
if (itemsRepaired >= 0) {
gamerStatValues[5] = itemsRepaired;
return gamerStatValues[5];
} else {
return gamerStatValues[5];
}
}
public int setItemsMerged(int itemsMerged) {
if (itemsMerged >= 0) {
gamerStatValues[6] = itemsMerged;
return gamerStatValues[6];
} else {
return gamerStatValues[6];
}
}
public int setTopScores(int topScores) {
if (topScores >= 0) {
gamerStatValues[7] = topScores;
return gamerStatValues[7];
} else {
return gamerStatValues[7];
}
}
public int setDmgPointsDealt(int dmgPointsDealt) {
if (dmgPointsDealt >= 0) {
gamerStatValues[8] = dmgPointsDealt;
return gamerStatValues[8];
} else {
return gamerStatValues[8];
}
}
public int setMapsCompleted(int mapsCompleted) {
if (mapsCompleted >= 0) {
gamerStatValues[9] = mapsCompleted;
return gamerStatValues[9];
} else {
return gamerStatValues[9];
}
}
public void setStatsToZero(){
for (int i = 0; i < gamerActions.length; i++) {
gamerActions[i] = 0;
}
}
public String statsString() {
return "Stats: " + "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
public String shortDecription() {
return String.format("%16s: Level %2d, Experience Points: %,10d",
playerName, this.getLevel(), this.getTotalExp());
}
#Override
public String toString() {
return "Gamer{" + "Player Name = " + playerName + " Player Stats: "
+ "Health Points Restored = " + gamerStatValues[0]
+ ",\n Areas Visited = " + gamerStatValues[1] + ", PlayersEncountered = " + gamerStatValues[2]
+ ", Maps Created = " + gamerStatValues[3] + ",\n Items Gathered = " + gamerStatValues[4]
+ ", Items Repaired = " + gamerStatValues[5] + ", Items Merged = " + gamerStatValues[6]
+ ",\n Top Scores = " + gamerStatValues[7] + ", Damage Points Dealt = " + gamerStatValues[8]
+ ", Maps Completed = " + gamerStatValues[9] + '}';
}
#Override
public int compareTo(Gamer player) {
if (this.getTotalExp() > player.getTotalExp()) {
return 1;
} else if (this.getTotalExp() == player.getTotalExp()) {
return 0;
} else {
return -1;
}
}
}
And the other:
package GamerProject;
import java.util.Random;
public class Program7Driver {
private static final int rngRange = 10;
private static final Gamer[] gamers = new Gamer[10];
private static final String[] gamerNames = {"BestGamer99", "CdrShepardN7",
"Gandalf_The_Cool", "SharpShooter01", "TheDragonborn", "SithLord01",
"MrWolfenstien", "Goldeneye007", "DungeonMaster91", "MasterThief","TheDarkKnight"};
public static void main(String[] args) {
Random rand = new Random();
for (int i = 0; i < gamers.length; i++) {
gamers[i] = new Gamer();
gamers[i].setPlayerName(gamerNames[i]);
gamers[i].setStatsToZero();
}
// for (int i = 0; i < 200000; i++) {
// int rng = rand.nextInt(rngRange);
// gamers[rng].setRandomGamerAction(rng);
// }
int count = 0;
for (int i = 0; i < gamers.length; i++) {
int rng = rand.nextInt(rngRange);
System.out.println(gamers[i]);
//System.out.println(gamers[0].toString());
//gamers[0].updateRandomGamerAction(rng);
if (rng == 0) {
gamers[0].setHealthPointsResd(gamers[0].getHealthPointsResd()+1);
} else if (rng == 1) {
gamers[0].setAreasVisited(gamers[0].getAreasVisited()+1);
} else if (rng == 2) {
gamers[0].setPlayersEncountered(gamers[0].getPlayersEncountered()+1);
} else if (rng == 3) {
gamers[0].setMapsCreated(gamers[0].getMapsCreated()+1);
} else if (rng == 4) {
gamers[0].setItemsGathered(gamers[0].getItemsGathered()+1);
} else if (rng == 5) {
gamers[0].setItemsRepaired(gamers[0].getItemsRepaired()+1);
} else if (rng == 6) {
gamers[0].setItemsMerged(gamers[0].getItemsMerged()+1);
} else if (rng == 7) {
gamers[0].setTopScores(gamers[0].getTopScores()+1);
} else if (rng == 8) {
gamers[0].setDmgPointsDealt(gamers[0].getDmgPointsDealt()+1);
} else {
gamers[0].setMapsCompleted(gamers[0].getMapsCompleted()+1);
}
count += 1;
if (count == 10) {
count -= 10;
}
// System.out.println(gamers[i].statsString());
}
}
}

Reacting to a specific char - TCP and char[][] issue

I'm creating a TCP game of Battleship in Java, and as I've made some functions work, methods that used to work no longer work.
Here's what's happening when it's a users turn. A bomb being dropped on 2 diffrent char[][], where clientGrid is the actual grid where the client has his ships. It's on this grid where the dropBomb method is being printed, and tells us whether a bomb has hit or not. clientDamage is just an overview for the server to see where he has previously dropped bombs.
if (inFromServer.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(clientDamage));
}
Here's the drop bomb method. It's proved to work before, however I have made some small changes to it. However I can't see why it wouldn't work. + indicates that there is a ship, x indicates that the target already has been bombed, and the else is ~, which is water. The method always returns "Nothing was hit on this coordinate...", and I can't seem to figure out why?
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
board[row][col] = 'x';
return "Ship has been hit!";
} else if (board[row][col] == 'x') {
return "Already bombed.";
} else {
board[row][col] = 'x';
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
}
Here is the full code... can someone please point out what I'm missing?
//server = player 1
//client = player 2
public class BattleshipGame {
public static ArrayList<Ship> fleet;
public static InetAddress clientAddress;
public static BattleshipGame battleship;
private final static int gridSize = 11;
public final static int numberOfShips = 3;
public static char[][] serverGrid;
public static char[][] clientGrid;
public static char[][] serverDamage;
public static char[][] clientDamage;
private int whosTurn;
private int whoStarts;
public static int count;
public static int bombCount;
public BattleshipGame() {
whoStarts = 0;
start();
showShipList();
}
public static String printBoard(char[][] board) {
String out = "";
for (int i = 1; i < board.length; i++) {
for (int j = 1; j < board.length; j++) {
out += board[j][i];
}
out += '\n';
}
return out;
}
public void start() {
Random rand = new Random();
if (rand.nextBoolean()) {
whoStarts = 1;
whosTurn = 1;
} else {
whoStarts = 2;
whosTurn = 2;
}
whoStarts = 1;
whosTurn = 1;
System.out.println("Player " + whoStarts + " starts\n");
}
public void initializeGrid(int playerNo) {
serverGrid = new char[gridSize][gridSize];
for (int i = 0; i < serverGrid.length; i++) {
for (int j = 0; j < serverGrid.length; j++) {
serverGrid[i][j] = '~';
}
}
serverDamage = new char[gridSize][gridSize];
for (int i = 0; i < serverDamage.length; i++) {
for (int j = 0; j < serverDamage.length; j++) {
serverDamage[i][j] = '~';
}
}
clientGrid = new char[gridSize][gridSize];
for (int i = 0; i < clientGrid.length; i++) {
for (int j = 0; j < clientGrid.length; j++) {
clientGrid[i][j] = '~';
}
}
clientDamage = new char[gridSize][gridSize];
for (int i = 0; i < clientDamage.length; i++) {
for (int j = 0; j < clientDamage.length; j++) {
clientDamage[i][j] = '~';
}
}
if (playerNo == 1) {
System.out.println("\nYour grid (player 1):\n"
+ printBoard(serverGrid));
} else if (playerNo == 2) {
System.out.println("\nYour grid (player 2):\n"
+ printBoard(clientGrid));
} else {
System.out.println("No such player.");
}
}
public static void deployShip(char[][] board, Ship ship, char direction,
int x, int y) {
if (direction == 'H') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x + i][y] = '+';
}
System.out
.println("Ship has been placed horizontally on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
} else if (direction == 'V') {
if (x < gridSize && y < gridSize) {
for (int i = 0; i < ship.getSize(); i++) {
board[x][y + i] = '+';
}
System.out
.println("Ship has been placed vertically on coordinates "
+ x + ", " + y + ".");
} else {
System.out.println("Unable to place ship in this coordinate.");
}
}
}
public static String dropBomb(int row, int col, char[][] board) {
if (row < gridSize && col < gridSize) {
if (board[row][col] == '+') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Ship has been hit!";
}
if (board[row][col] == 'x') {
System.out.println(board[row][col]);
bombCount++;
return "Already bombed.";
}
if (board[row][col] == '~') {
System.out.println(board[row][col]);
board[row][col] = 'x';
bombCount++;
return "Nothing was hit on this coordinate...";
}
} else {
return "No such coordinate.";
}
return "";
}
public void showShipList() {
System.out
.println("Choose ships to add to your fleet from the following list ("
+ numberOfShips + " ships allowed):");
ArrayList<Ship> overview = new ArrayList<Ship>();
Ship ac = new Ship("Aircraft carrier", 5, false);
Ship bs = new Ship("Battleship", 4, false);
Ship sm = new Ship("Submarine", 3, false);
Ship ds = new Ship("Destroyer", 3, false);
Ship sp = new Ship("Patrol Boat", 2, false);
overview.add(ac);
overview.add(bs);
overview.add(sm);
overview.add(ds);
overview.add(sp);
for (int i = 0; i < overview.size(); i++) {
System.out.println(i + 1 + ". " + overview.get(i));
}
}
public static ArrayList<Ship> createFleet(ArrayList<Ship> fleet, int choice) {
if (count < numberOfShips && choice > 0 && choice < 6) {
if (choice == 1) {
Ship ac = new Ship("Aircraft carrier", 5, false);
fleet.add(ac);
count++;
System.out.println("Aircraft carrier has been added to fleet.");
} else if (choice == 2) {
Ship bs = new Ship("Battleship", 4, false);
fleet.add(bs);
count++;
System.out.println("Battleship has been added to fleet.");
} else if (choice == 3) {
Ship sm = new Ship("Submarine", 3, false);
fleet.add(sm);
count++;
System.out.println("Submarine has been added to fleet.");
} else if (choice == 4) {
Ship ds = new Ship("Destroyer", 3, false);
fleet.add(ds);
count++;
System.out.println("Destroyer has been added to fleet.");
} else if (choice == 5) {
Ship sp = new Ship("Patrol Boat", 2, false);
fleet.add(sp);
count++;
System.out.println("Patrol boat has been added to fleet.");
}
} else {
System.out.println("Not an option.");
}
System.out.println("\nYour fleet now contains:");
for (Ship s : fleet) {
System.out.println(s);
}
return fleet;
}
}
public class TCPServer extends BattleshipGame {
private static final int playerNo = 1;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
ServerSocket serverSocket = new ServerSocket(6780);
Socket socket = serverSocket.accept();
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(System.in));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(socket.getOutputStream());
Scanner scan = new Scanner(System.in);
while (true) {
if (inFromServer.ready()) {
setup(scan, playerNo);
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, clientGrid));
System.out.println(printBoard(clientGrid));
dropBomb(x, y, clientDamage);
outToClient.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
printBoard(clientDamage);
}
if (inFromClient.ready()) {
System.out.println(inFromClient.readLine());
System.out.println(printBoard(serverGrid));
}
}
// socket.close();
// serverSocet.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(serverGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(serverGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
public class TCPClient extends BattleshipGame {
private static final int playerNo = 2;
public static void main(String[] args) {
System.out.println("You are player: " + playerNo);
battleship = new BattleshipGame();
try {
InetAddress.getLocalHost().getHostAddress();
Socket socket = new Socket(InetAddress.getLocalHost()
.getHostAddress(), 6780);
DataOutputStream dataOutputStream = new DataOutputStream(
socket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(System.in));
Scanner scan = new Scanner(System.in);
setup(scan, playerNo);
while (true) {
if (inFromClient.ready()) {
System.out.println("\nInput coordinate");
int x = scan.nextInt();
int y = scan.nextInt();
System.out.println(dropBomb(x, y, serverGrid));
dropBomb(x, y, serverDamage);
dataOutputStream.writeChars("Enemy player has targeted " + x + ", " + y +'\n');
System.out.println(printBoard(serverDamage));
}
if (inFromServer.ready()) { // modtag data fra server
System.out.println(inFromServer.readLine());
System.out.println(printBoard(clientGrid));
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void setup(Scanner inFromUser, int playerNo) {
fleet = new ArrayList<Ship>();
while (count < numberOfShips) {
createFleet(fleet, inFromUser.nextInt());
}
battleship.initializeGrid(playerNo);
for (int i = 0; i < fleet.size(); i++) {
System.out.println(fleet.get(i));
System.out.println("Define direction (V/H) plus coordinates");
deployShip(clientGrid, fleet.get(i), inFromUser.next().charAt(0), inFromUser.nextInt(), inFromUser.nextInt());
}
System.out.println("Placements:\n" + printBoard(clientGrid));
System.out.println("Fleet has been deployed. Press enter to continue.\n");
}
}
package Battleships;
public class Ship {
private String name;
private int size;
private boolean isDestroyed;
public Ship(String n, int s, boolean d) {
this.name = n;
this.size = s;
this.isDestroyed = d;
}
public String getName() {
String output = "";
output = "[" + name + "]";
return output;
}
public int getSize() {
return size;
}
public String toString() {
String output = "";
output = "[" + name + ", " + size + ", " + isDestroyed + "]";
return output;
}
}

Categories

Resources