How to represent ranges in while statments? - java

I am writing a small game for fun that uses an action system for multiple teammates.
I do not know how to represent the range of all members 0-9 in an array in a while loop.
I know that, there is a way to do closedOpen, but I don't know how that would fit into the code.
int[2][10][0] hea //Using two teams, each with 10 members, who have multiple traits
// ^ I know this isn't perfect syntax
while (hea[0][0-9][0]!=0){ // Tests for if at least one member of team has actions
Actions
}
// Is there a way to represent the middle step in the array without typing out all and statements

How about a for loop?:
for (int i = 0; i < hea.length; i++) {
int[][] team = hea[i];
for (int member = 0; member < team.length; member++) {
int[] traits = team[member];
//Check actions
}
}
Speaking from a game design perspective, I would not shy away from using classes for things like this:
public class Team {
private final List<Player> players = new ArrayList<>();
public static final int MAX_SIZE = 10;
}
public class Player {
public String getName();
public List<Action> getActions();
}
public class Action {
private final int[] basic; //however you wish to implement
}
public class Game {
private final List<Team> teams = new ArrayList<>();
public void addPlayer(Player player);
}
Check out the Oracle Java Tutorials for a more in-depth explaination on learning java.

One of the most direct ways is to write a (private) method to do the checks all over the array. Something like:
/** Tests if at least one member of the team has actions left */
private boolean haveActionsLeft(int [][][] hea, int team, int members) {
for (int m = 0; m < members; m++) {
if (hea[team][m][0] >= 0) {
return true;
}
}
return false;
}
And then you can call the function into your while statement's condition:
...
while (haveActionsLeft(hea, 0, 10)) {
Actions
}

If I'm not mistaken by your intent, this is the perfect use case for a for loop
A for loop takes a value and increments (or decrements) it and is a good way to iterate through a fixed number of options.
for(int i = 0; i < 9; i++) {
if(hea[0][i][0] != 0) {
Actions
}
}
This says: start i at 0, and go through the loop. At the end of the loop, increment i. continue until i reaches 9 and then break the loop.

Related

How to decide the state of an object before starting to code?

I have the following code for displaying the sum of two consecutive element of ArrayList until the element left is one.for example:-
if i entered
1 2 3 4 5
output
3 7 5 //adding the two consecutive last one is as it is
10 5//doing the same thing
15
code
import java.util.*;
import java.lang.Integer;
class Substan{
ArrayList <Integer> list = new ArrayList <Integer> ();
ArrayList <Integer> newList = new ArrayList <Integer> ();// this will be the list containing the next sequence.
int index=0;
int sum=0;
Substan(){
Scanner read = new Scanner(System.in);
String choice;
System.out.println("Enter the elements of the array");
do{
int element = read.nextInt();
list.add(element);
System.out.println("More?");
choice = read.next();
}while(choice.equals("y") || choice.equals("Y"));
}
/* precondition- we have the raw list that user has enterd.
postcondition - we have displayed all the sublists,by adding two consecutives numbers and the last one is having one element.
*/
void sublist(){
while(noofElementsIsNotOneInList()){
index =0;
while(newListIsNotComplete()){
if(nextElementIsThere()){
sum = addTheConsecutive();
}
else{
sum = getLastNumber();
}
storeSumInNewList();
}
displayTheNewList();
System.out.println("");
updateTheLists();
}
displayTheNewList(); //as we have danger of Off By One Bug (OBOB)
System.out.println("");
}
private boolean noofElementsIsNotOneInList(){
boolean isnotone = true;
int size = list.size();
if ( size == 1){
isnotone = false;
}
return isnotone;
}
private boolean newListIsNotComplete(){
boolean isNotComplete = true;
int listSize = list.size();
int newListSize = newList.size();
if (listSizeIsEven()){
if ( newListSize == listSize/2){
isNotComplete = false;
}
}
else{
if( newListSize == (listSize/2) +1){
isNotComplete = false;
}
}
return isNotComplete;
}
private boolean listSizeIsEven(){
if ( list.size()%2 == 0 ){
return true;
}
else{
return false;
}
}
/*
we are at some index.
returns true if we have an element at (index+1) index.
*/
private boolean nextElementIsThere(){
if ( list.size() == index+1 ){
return false;
}
else{
return true;
}
}
/* precondition-we are at index i
postcondition - we will be at index i+2 and we return sum of elements at index i and i+1.
*/
private int addTheConsecutive(){
int sum = list.get(index)+list.get(index+1);
index += 2;
return sum;
}
/* we are at last element and we have to return that element.
*/
private int getLastNumber(){
return list.get(index);
}
private void storeSumInNewList(){
newList.add(sum);
}
private void displayTheNewList(){
int size = newList.size();
for ( int i=0;i<size;i++){
System.out.print(newList.get(i)+" ");
}
}
/*precondition - we have processed all the elements in the list and added the result in newList.
postcondition - Now my list will be the newList,as we are processing in terms of list and newList reference will have a new object.
*/
private void updateTheLists(){
list = newList;
newList = new ArrayList <Integer>();// changing the newList
}
public static void main(String[] args) {
Substan s = new Substan();
s.sublist();
}
}
So i have done a lot of refinement of my code but having a problem of sharing the local variables with the other methods.for example i have used index instance for storing the index and initially i thought that i will put this as not an instance but a local variable in method sublist() but as it cannot be viewed from other methods which needed to use the index like addTheConsecutive().So considering that i put the index at class level.So is it wright approach that put the variables that are shared at class level rather than looking at only the state of the object initially before coding and stick to that and never change it?
Consider this:
An object can communicate with other(s) only by sharing its attributes. So, if you need an object to read the state of another, the only way it can be done is by giving it "permission" to read the other object attributes.
You have two ways to do that:
Declaring the object attributes public, or
Creating getXXX() methods (makes sense for private attributes)
I personally prefer option two, because the getXXX() method returns the value ("state") of a particular attribute without the risk of being modified. Of course, if you need to modify a private attribute, you should also write a setXXX() method.
Example:
public class MyClass {
private int foo;
private String bar;
/*
* Code
*/
public int getFoo() {
return foo;
}
public String getBar() {
return bar;
}
public void setFoo(int foo) {
this.foo = foo;
}
public void setBar(String bar) {
this.bar = bar;
}
/*
* More code
*/
}
This way all the object attributes are encapsulated, and:
they cannot be read by any other object, unless you specifically call the appropriate getXXX() function, and
cannot be altered by other objects, unless you specifically call the appropriate setXXX() function.
Compare it with the non-abstracted version.
for (int index = 0; index < list.size(); index += 2) {
int sum = list.get(index);
if (index + 1 < list.size() {
sum += list.get(index + 1);
}
newList.add(sum);
}
Now, top-down refining the algorithm using names is a sound methodology, which helps in further creative programming.
As can seen, when abstracting the above again:
while (stillNumbersToProcess()) {
int sum = sumUpto2Numbers();
storeSumInNewList(sum);
}
One may keep many variables like sum as local variables, simplifying state.
One kind of helpful abstraction is the usage of conditions, in a more immediate form:
private boolean listSizeIsEven() {
return list.size() % 2 == 0;
}
private boolean nextElementIsThere() {
return index + 1 < list.size();
}
There's no point in declaring index at Class level since you dont want it to be a member or an instance of that class. Instead make it local to the method and pass it to other methods as argument where you want to access it.
I think you are asking the wrong question.
Your class variables make very little sense, as do many of the methods. This is mostly because:
Your class is doing too much
Your algorithm is a little odd
The class variables that you do have make much more sense passed as method parameters. Some methods need to see them, and some don't.
Your class is also a little odd, in that calling subList twice on the same class will not produce the same answer.
The code is littered with methods I don't quite see the point in, such as:
private boolean noofElementsIsNotOneInList(){
boolean isnotone = true;
int size = list.size();
if ( size == 1){
isnotone = false;
}
return isnotone;
}
Shouldn't this be:
private boolean noofElementsIsNotOneInList(){
return list.size() == 1;
}
And it makes no sense for it to use some arbitrary List, pass one in so that you know which List you are checking:
private boolean noofElementsIsNotOneInList(final Collection<?> toCheck){
return toCheck.size() == 1;
}
The same logic can be applied to almost all of your methods.
This will remove the instance variables and make your code much more readable.
TL;DR: Using lots of short appropriately named methods: good. Having those methods do things that one wouldn't expect: bad. Having lots of redundant code that makes things very hard to read: bad.
In fact, just to prove a point, the whole class (apart from the logic to read from stdin, which shouldn't be there anyway) can transformed into one short, recursive, method that requires no instance variables at all:
public static int sumPairs(final List<Integer> list) {
if (list.size() == 1)
return list.get(0);
final List<Integer> compacted = new LinkedList<>();
final Iterator<Integer> iter = list.iterator();
while (iter.hasNext()) {
final int first = iter.next();
if (iter.hasNext()) compacted.add(first + iter.next());
else compacted.add(first);
}
return sumPairs(compacted);
}
Now you could break this method apart into several appropriately named shorter methods, and that would make sense. It's sometimes more helpful to start from the other end. Sketch out the logic of your code and what it's trying to do, then find meaningful fragments to split it into. Possibly after adding unit tests to verify behaviour.
what about doing by Recursion:
public int calculateSum(List<Integer> nums) {
displayList(nums);
if (nums.size() == 1) {
return nums.get(0);
}
List<Integer> interim = new ArrayList<Integer>();
for (int i = 0; i < nums.size(); i = i + 2) {
if (i + 1 < nums.size()) {
interim.add(nums.get(i) + nums.get(i + 1));
} else {
interim.add(nums.get(i));
}
}
return calculateSum(interim);
}
public static void displayList(List<Integer> nums){
System.out.println(nums);
}
Steps:
Run calculate sum until list has 1 element
if list has more than 1 element:
iterate the list by step +2 and sum the element and put into a new List
again call calculate sum

Is there a way to have shortcut for text in Java?

I am trying to avoid repeating masses of code and was wondering if there was a short cut for it? I want a literal shortcut, which just replaces the shortcut with text in compilation.
for example:
private int a = 0;
/*Shortcut sc = new Shortcut ( for(a = 0; a < 5; a++) ); */
if (truth = true)
sc.doTask(a);
else
sc.doTask((a+1);
I know it doesn't affect the efficiency of coding, but makes the task look a bit more organized.
It seems what you are trying to do is will leave your code unmaintainable and hard to read (Unless you were asking how to organize your code in functions).
It's not always about coding efficiency. You have to make sure that your code is not harder to maintain and understand by other developers.
If you want to avoid repetition of code put the repeated code in some well defined methods.
public class Test {
public static void main(String[] args) {
Test test = new Test();
// Now you can use the so called shortcut that is called a method everywhere you want.
int sum = test.getSum(1, 2, 3);
System.out.println("Sum is " + sum);
// Now again reuse the method instead of loads of code :)
sum = test.getSum(2, 4, 5);
System.out.println("New sum is " + sum);
}
public int getSum(int... numbers) {
int sum = 0;
for (int num : numbers) {
sum += num;
}
return sum;
}
}
BTW. Your if(truth=true) is assignment to variable called "truth" and will always evaluate to true. Your else will never be called.
Ill take a stab. To reduce boiler plate code you can use methods. Take this example
public class MyFooClass {
private int[] numbers;
public void doStuff1() {
// do something
for(int i=0;i<numbers.length;i++) {
// check for duplicates or something
}
}
public void doOtherStuff() {
// do something
for(int i=0;i<numbers.length;i++) {
// check for duplicates or something
}
}
}
as you can see we check for duplicates 2 times, we can reuse that code in another method.
public class MyFooClass {
private int[] numbers;
public void doStuff1() {
// do something
checkForDuplicatesOrSomething();
}
public void doOtherStuff() {
// do something
checkForDuplicatesOrSomething();
}
private void checkForDuplicatesOrSomething() {
for(int i=0;i<numbers.length;i++) {
// check for duplicates or something
}
}
}
Instead of calling System.out.println("blah blah blah my text"); each time you want to print something you could code your own method like this.
public void p(Object o) {
System.out.println(o);
}
Then in your code simply call this method like this:
String s = "foo";
StringBuilder sb1 = new StringBuilder("i hate this town");
p(s);
p(sb1);

Using a data structure to solve this in O(n)

we have sequence of 4 characters (A,B,C and D)that map to numbers form 1 to n.
we define components to be:
Component(k) :
A {cell[k]}
if Color(left_k) = Color(k)
then
A <-- A U Component(left_k)
if Color(right_k) = Color(k)
then
A <-- A U Component(left_k)
return A
there is 3 types of operations(the numbers in list indicate the input):
by giving index it should remove the component in that index(the numbers mapping to characters are fixed)
example : AABBBDA is the string. if index is 3 it should return AADA
by giving index it should rotate the string based on the component on that index(the numbers mapping to characters are fixed)
example : AABBBDA is the string. if index is 3 it should return DABBBAA
it should print the string.
inputs are like:
1 2 --> first operation with index=2
2 3 --> second operation with index=3
3 --> third operation
It's an assignment, happy to get help.
this is what i've tried so far:
public static void main(String[] args)
{
int numberOfOps;
String[] print = new String[30];
List list = new List();
Scanner input = new Scanner(System.in);
int count = input.nextInt();
String colors = new String();
colors = input.next();
for(int i = 0; i < count; i++)
{
list.add(colors.charAt(i));
}
numberOfOps = input.nextInt();
list.printElement();
for (int i = 0; i < numberOfOps; i++)
{
int op = input.nextInt();
if(op == 1)
{
int index = input.nextInt();
char c = list.item[index];
int temp = index;
int prevIndex = index;
int nexIndex = index;
if(index != 0)
{
while (list.item[--index] == c)
{
prevIndex--;
}
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex-1, nexIndex+1);
}
else
{
while (list.item[++temp] == c)
{
nexIndex++;
}
list.setNext(prevIndex, nexIndex+1);
}
}
if(op == 2)
{
int index = input.nextInt();
}
if(op == 3)
{
print[i] = list.printElement();
}
}
}
here is my List class:
public class List {
// reference to linked list of items
public static final int MAX_LIST = 20;
public static final int NULL = -1;
public char item[] = new char[MAX_LIST]; // data
public int avail;
public int next[] = new int[MAX_LIST]; // pointer to next item
private int numItems; // number of items in list
public List()
{
int index;
for (index = 0; index < MAX_LIST-1; index++)
next[index] = index + 1;
next[MAX_LIST-1] = NULL;
numItems = 0;
avail = 0;
} // end default constructor
public void add(char e)
{
item[avail] = e;
avail = next[avail];
numItems++;
}
public String printElement()
{
String temp = null;
int index = 0;
while(index<avail)
{
temp += item[index];
System.out.println(item[index]);
index = next[index];
}
return temp;
}
public int size()
{
return numItems;
}
public void setNext(int i, int value)
{
next[i] = value;
}
}
if you test it you'll get, it has lots of problems, such as, I have no idea to do the rotate operation, and it has problem with connecting two components when the middle component has been removed.
This is a difficult question to answer, because the requirements are not properly stated.
For example the first bunch of pseudo-code does not make it clear whether A is a set, a multi-set or a list. The notation (use of curly brackets, and U (union?)) seems to say set ... but the output seems to be a list. Or maybe it is supposed to be a schema for a data structure??
And even the inputs are not clearly described.
But putting that on one side, there is still room for some (hopefully) helpful advice.
Make sure that >>you<< understand the requirements. (I imagine that the real requirements for the assignment are better stated than this, and the details have been "lost in translation".)
I would actually use an array list (or a StringBuilder) rather than a linked list for this. (But a properly implemented linked list ... implementing the List API ... would work.)
But whatever data structure you chose, there is no point in implementing it from scratch ... unless you are specifically required to do that. There are perfectly good list classes in the Java standard libraries. You should reuse them ... rather than attempting to reinvent the wheel (and doing a bad job).
If you are required to implement your own data structure type, then your current attempt is a mess. It looks like a hybrid between an array list and a linked list ... and doesn't succeed in being either. (For example, a decent array list implementation does not need a MAX_LIST, and doesn't have next pointers / indexes. And a linked list does not have any arrays inside it.)

Accessing 2-dimensional array from an object class.

In Java I have a 2-dimensional array of objects but I can't access any of those array of objects in the object's class methods. What should I do?
Here's my class:
class GoPiece
{
final int boardSize = 19;
final int empty = 0;
final int black = 1;
final int white = 2;
int pieceType = empty;
int leftRight;
int downUp;
int turnPlayed;
boolean legal;
// GoPiece's Constructor with 3 parameters.
GoPiece(int blackOrWhite, int horizontalCoordinate, int verticalCoordinate)
{
pieceType = blackOrWhite;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
if ((true));
}
// GoPiece's Constructor with 2 parameters.
GoPiece(int horizontalCoordinate, int verticalCoordinate)
{
pieceType = empty;
leftRight = horizontalCoordinate;
downUp = verticalCoordinate;
}
// GoPiece's Constructor with no parameters.
GoPiece()
{
leftRight = 0;
downUp = 0;
}
// Initialize an empty Go board full of GoPieces.
GoPiece[][] InitializeBoard()
{
GoPiece[][] intersection = new GoPiece[boardSize][boardSize];
for(int horizontal = 0; horizontal < boardSize; horizontal++)
{
for(int vertical = 0; vertical < boardSize; vertical++)
{
intersection[horizontal][vertical] = new GoPiece(horizontal,vertical);
}
}
return intersection;
}
// Make a piece a certain type: empty, black, or white.
public void SetType(int newType)
{
pieceType = newType;
}
public int GetType()
{
return pieceType;
}
public void CheckKill()
{
int foobar = this.GetType();
}
}
I can then use InitializeBoard() in another part of my program to create a two dimensional array of GoPieces... this works, but How do I access all of those pieces other than the one I'm referencing in the class GoPiece's member functions? I tried passing the whole array into one of GoPieces functions, but that didn't seem to work.
Go is an Ancient Chinese Board game. The CheckKill() method above is where I tried to access different parts of the array, but failed. Here I have some working dummy code.
Thank you.
You need to create a separate class to represent the board itself (including the current placement of pieces). The logic for creating a board, testing for a kill, etc., belong to the board, not to an individual piece.
Do you mean you want to call a method with the array like InitializeBoard.GetType(); Where InitializeBoard is a 2 Dimensional Array?
You can't do that. You Must Specify which GoPiece to get out of InitializeBoard. Example: InitializeBoard[0][0].GetType(); If you must call all methods, you can use a for loop to call each individually.

What is wrong with my implementation of this algorithm to compute the first N prime numbers?

I think the constructor is logically correct, I just can't figure out how to call it in the main ! :) Can anyone help please ? If someone would just have a quick look over my code it would be nice :) Thanks a lot !
Also, I am using arrayLists in this implementation and I have to do it this way so I don't wish to change it, even though it is far more easily implemented using only arrays.
import java.util.*;
public class PrimeNumberss {
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(10);
}
public PrimeNumberss (int initialCapacity) {
ArrayList<Integer> listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity);
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
while (start != initialCapacity)
{
if (isPrimeNumber[start])
{
listOfPrimeNumbers.add(start);
//add to array list
numberOfPrimes++;
for (int i = start; start < initialCapacity; i+=start)
{
isPrimeNumber[i] = false;
}
}
start++;
}
}
}
Your algorithm is not correct; you will only find the primes less than N (your initial capacity), not the first N primes.
If you're going to store each prime, you should store them in a class variable not a variable local to the constructor. You won't be able to access them outside the constructor if you do.
You should expose the list using a getter method to provide access to them.
You're not printing anything in the constructor.
i==initialCapacity is clearly wrong.
Everything important is there, its small changes. Right now you are getting primes less than N, so if you want to change it to first N primes that's going to be a real functional difference. For now lets just make N=50 so you'll get well over 10 primes.
public class PrimeNumberss {
private List listOfPrimeNumbers; //add a member variable for the ArrayList
public static void main(String args []){
PrimeNumberss PrimeNumbers = new PrimeNumberss(50);
PrimeNumbers.print(); //use our new print method
}
public PrimeNumberss (int initialCapacity) {
listOfPrimeNumbers = new ArrayList<Integer>(initialCapacity/2); //initialCapacity/2 is an easy (if not tight) upper bound
long numberOfPrimes = 0; //Initialises variable numberOfPrimes to 0
int start = 2;
boolean[] isPrimeNumber = new boolean[initialCapacity + 1];
for (int i=0;i==initialCapacity;i++) {//setting all values in array of booleans to true
isPrimeNumber[i] = true;
}
//.... complete the constructor method as you have it. honestly, i didnt even read it all
public void print() //add this printout function
{
int i = 1;
it = listOfPrimeNumbers.listIterator();
while (it.hasNext())
{
System.out.println("the " + i + "th prime is: " + it.next());
i++;
}
//or just System.out.println(listOfPrimeNumbers);, letting ArrayList's toString do the work. i think it will be in [a,b,c,..,z] format
}
public List getPrimes() {return listOfPrimeNumbers;} //a simple getter isnt a bad idea either, even though we arent using it yet
}
On a side note, you could probably d oa little better with the naming (PrimeNumberss and PrimeNumbers??), but I didnt change any of that. Also, intiialCapacity does not reflect what it really means. Maybe something along the lines of 'top'.

Categories

Resources