• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Gonff

Banned
Got a quick question for some of you.

Right now I am programming in multiple languages on a regular basis and using multiple IDEs.

A quick rundown:

C++ - Visual Studio or Qt Creator
PHP, HTML5, CSS, Javascript - Komodo Edit
Java - Netbeans
Android - Eclipse or AIDE

Now, I get kinda tired of using the same editor for too long, and I have been trying to stay away from Visual Studio. It is one of the best IDEs I have ever used, but I realized that using IDEs that do most of the work for you really hinder progress. Not only that, but I am doing most of my programming these days multi-platform (Linux and Windows environments), so I need something that is cross-compatible.

What kind of editors do people suggest for these languages? Even though I have a decent job, I kind of have a lot going on lately and cannot afford to pay $100 for an editor, so something preferably free.

The most important one right now is web stuff (so PHP, HTML5 and Javascript). I like Komodo Edit, but lately it has been giving me issues and I am getting to the breaking point.
 
What kind of editors do people suggest for these languages? Even though I have a decent job, I kind of have a lot going on lately and cannot afford to pay $100 for an editor, so something preferably free.

The most important one right now is web stuff (so PHP, HTML5 and Javascript). I like Komodo Edit, but lately it has been giving me issues and I am getting to the breaking point.

Sublime is easily the best text editor I've ever used. For me, it works fantastic for editing in pretty much any language. It's not free, but it has an unlimited length full access trial period. (I personally haven't bought a license yet, but fully plan to do so once I finish school and get an actual job.)

This set of tutorials is great for learning some of the stuff you can do with Sublime.
 

phoenixyz

Member
Sublime is easily the best text editor I've ever used. For me, it works fantastic for editing in pretty much any language. It's not free, but it has an unlimited length full access trial period. (I personally haven't bought a license yet, but fully plan to do so once I finish school and get an actual job.)

This set of tutorials is great for learning some of the stuff you can do with Sublime.
+1
SublimeText is great. I like all the little features IDEs like Visual Studio or Netbeans have but I struggle using them because the editors themselves are not nearly as good as Sublime Text.
 

Prelithe

Member
What kind of editors do people suggest for these languages? Even though I have a decent job, I kind of have a lot going on lately and cannot afford to pay $100 for an editor, so something preferably free.

The most important one right now is web stuff (so PHP, HTML5 and Javascript). I like Komodo Edit, but lately it has been giving me issues and I am getting to the breaking point.

For PHP/JS stuff I recommend PhpStorm. Yes, it costs $99, but personally it's worth the money.

http://www.jetbrains.com/phpstorm/
 

Gonff

Banned
PhpStorm sounds nice, but one of the reasons I don't want to spend money like that is because my interests and what I do at work changes on a whim.

Right now I am doing a lot of PHP (working on a resume website and online portfolio), but in a few months I might get back into a lot of C++ or Perl.

If I was confident that I'd be doing PHP for a good portion of the future, I could validate spending $100 on something like that.

Sublime Text seems neat though. I've actually been using it as a companion to Komodo. My biggest issue with it is its lack of an (S)FTP browser.
 

Mabef

Banned
I have an excel question. ehh. Basically, I want to recreate a method/function inside of excel, but I don't know enough about excel.

I'm calculating some card game probability. My 'class' is cards, my 'objects' are the individual cards (each has a handful of values), and my 'method' is a bunch of math that inputs the card stats and outputs a few probabilities.

I want to have a list of cards that automatically sends each item through my probability calculator, and have the probability calculator return a few numbers to the list.
Code:
List of cards...
----
"Card name" | Card stats | Probability
User defined|User defined| probability = probCalculator(cardStat1, cardStat2...)

...
int probCalculator(cardStat1, cardStat2){
do math
return probability
}
I only know how to do math functions that takes inputs from specific cells (like =A1*A2).
 
jeebus. finally got most of my code down with no apparent errors and then blam. stackoverflow errors :l i'm stumped. have at it.
here's the error

Code:
Exception in thread "main" java.lang.StackOverflowError
	at java.util.AbstractCollection.<init>(Unknown Source)
	at java.util.AbstractList.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
GameWorld.class

Code:
public class GameWorld implements IObservable, IGameWorld 
{
// create collections class
public Vector<GameObject> GameObjectList = new Vector<GameObject>(); // PROBLEM - get a stack overflow here.
private Vector<IObserver> ObserverList = new Vector<IObserver>();
Random rand = new Random();
// declare objects
Tank pTank = new Tank(10, 10);
Tank eTank = new Tank(10,10);
Missile missile = new Missile(5);
Missile pMissile = new Missile(5);
Tree tree = new Tree(rand.nextInt(20) + 1);
Rock rock = new Rock(rand.nextInt(20) + 1, rand.nextInt(20) + 1);
// ... other attributes
public GameWorld() // create objects and add them to vector
{
GameObjectList.add(pTank);
GameObjectList.add(eTank);
GameObjectList.add(missile);
GameObjectList.add(tree);
GameObjectList.add(rock);
// other methods 

}
// other methods
}

Then I get another error in the gameobject class. The problem I had earlier with trying to implement interface methods with a inner class was a waste of time, so I made separate classes for every class.

Code:
public class Tank extends Movable implements ISteerable // association with Movable and is Steerable FIX
{
	 private int armorStrength;
	 private int missileCount;
	 public Tank()
	 {}
	 
	 public Tank(int armStr, int misslCt) // problem?
	 {
		 armorStrength = armStr; // default armorStrength
		 missileCount = misslCt; // default missileCount
	 }
	 public void setDirection(int direction)
	 {
		this.setDirection(direction); // get input from left turn or right turn
		// updateValues();
	 }
// access/mutators here

I'm stumped. But I think my GameObjectList isn't storing any objects so therefore it's crashing.
 

diaspora

Member
Did you write the healthcare website, by any chance?

smODdvw.jpg
 

CronoShot

Member
Running into a problem (shocker). I'm trying to make a problem that displays a random walk across a 10x10 grid using capital letters:

Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 10
typedef char Grid[SIZE][SIZE];


int can_move_up(int i, int j, Grid walk);

int can_move_down(int i, int j, Grid walk);

int can_move_left(int i, int j, Grid walk);

int can_move_right(int i, int j, Grid walk);

void init_array(Grid walk);

void generate_random_walk(Grid walk);

void print_array(Grid walk);


int main(void)
{
    Grid walk;
    
    srand((unsigned) time(NULL));
    
    init_array(walk);
    
    generate_random_walk(walk);
    
    print_array(walk);
    
    return 0;
}


int can_move_up(int i, int j, Grid walk)
{
    return (i > 0) && (walk[i-1][j] == '.');
}

int can_move_down(int i, int j, Grid walk)
{
    return (i < SIZE) && (walk[i+1][j] == '.');
}

int can_move_left(int i, int j, Grid walk)
{
    return (j > 0) && (walk[i][j-1] == '.');
}

int can_move_right(int i, int j, Grid walk)
{
    return (j < SIZE) && (walk[i][j+1] == '.');
}

void init_array(Grid walk)
{
    int i, j;
    
    for (i = 0; i < SIZE; i++)
    {
        for (j = 0; j < SIZE; j++)
        {
            walk[i][j] = '.';
        }
    }
}

void generate_random_walk(Grid walk)
{
    int i, j, direction;
    char letter;
    
    i = 0;
    j = 0;
    
    for (letter = 'A'; letter <= 'Z'; letter++)
    {
    direction = rand() % 4;
    
    switch (direction)
    {
        case 0: if (can_move_up) {
            walk[i-1][j] = letter;
        }break;
        case 1: if (can_move_down) {
            walk[i+1][j] = letter;
        }break;
        case 2: if (can_move_left) {
            walk[i][j-1] = letter;
        }break;
        case 3: if (can_move_right) {
            walk[i][j+1] = letter;
        }break;
    }
        if (walk[i-1][j] != '.' && walk[i+1][j] != '.' && walk[i][j+1] != '.' && walk[i][j-1] != '.') {
            break;
        }
    }
}

void print_array(Grid walk)
{
    int i, j;
    
    for (i = 0; i < SIZE; i++)
    {
        for (j = 0; j < SIZE; j++)
        {
            printf("%c ", walk[i][j]);
        }
        printf("\n");
    }
}

Just finished writing a first draft and tried to run it for the first time. It seems to compile, but I'm getting a 'Segmentation fault: 11' error when I try to run it. Googling around it looks like some sort of memory error, but I'm not sure what's causing it.
 
If you're getting a segmentation fault I recommend loading up a debugger and stepping through the program execution to see on what line the segfault is occurring. It's usually pretty obvious once you see which line is causing the problem.

Just glancing at it real quick, I think you're probably trying to access memory outside of the allocated size for walk. Within your "can_move" functions, you're checking to make sure that i or j is within range, but in the same statement also checking what's in walk at certain points of i or j. I'm assuming at some points i or j (or i+1 or j+1) are larger then SIZE, thus it's trying to access memory that wasn't allocated to walk.

If SIZE was 3, and i was 3, then the statement walk[i+1][j] would be bad. I recommend checking the sizes of i and j before referencing anything in walk with them.
 

CronoShot

Member
If you're getting a segmentation fault I recommend loading up a debugger and stepping through the program execution to see on what line the segfault is occurring. It's usually pretty obvious once you see which line is causing the problem.

Just glancing at it real quick, I think you're probably trying to access memory outside of the allocated size for walk. Within your "can_move" functions, you're checking to make sure that i or j is within range, but in the same statement also checking what's in walk at certain points of i or j. I'm assuming at some points i or j (or i+1 or j+1) are larger then SIZE, thus it's trying to access memory that wasn't allocated to walk.

If SIZE was 3, and i was 3, then the statement walk[i+1][j] would be bad. I recommend checking the sizes of i and j before referencing anything in walk with them.

Thanks. Just got it done.

Had a bit of an embarrassing moment when I sat there for 20 minutes wondering why the grid was empty each time, then realized my can_move function calls had no parameters. Derp.
 

hateradio

The Most Dangerous Yes Man
Got a quick question for some of you.

Right now I am programming in multiple languages on a regular basis and using multiple IDEs.

A quick rundown:

C++ - Visual Studio or Qt Creator
PHP, HTML5, CSS, Javascript - Komodo Edit
Java - Netbeans
Android - Eclipse or AIDE
I used to use NetBeans a lot, but now I switched to IntelliJ (Community Edition). I like it quite a bit.
 

Water

Member
If you're getting a segmentation fault I recommend loading up a debugger and stepping through the program execution to see on what line the segfault is occurring. It's usually pretty obvious once you see which line is causing the problem.
Usually you shouldn't need to step through the execution to locate a segfault, just run under the debugger and look at the backtrace / call stack after the crash.
 
jeebus. finally got most of my code down with no apparent errors and then blam. stackoverflow errors :l i'm stumped. have at it.
here's the error

Code:
Exception in thread "main" java.lang.StackOverflowError
	at java.util.AbstractCollection.<init>(Unknown Source)
	at java.util.AbstractList.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
GameWorld.class

Code:
public class GameWorld implements IObservable, IGameWorld 
[...]

Then I get another error in the gameobject class. The problem I had earlier with trying to implement interface methods with a inner class was a waste of time, so I made separate classes for every class.

Code:
public class Tank extends Movable implements ISteerable 
[...]

I'm stumped. But I think my GameObjectList isn't storing any objects so therefore it's crashing.
Very strange. Usually you only get a StackOverflowError when you use too much recursion and the call stack is not big enough, but that doesn't seem to be the issue here. Have you used a debugger to see the state of each variable? By the way, use an ArrayList<T> instead of the Vector class, Vector is basically a legacy class that has some small disadvantages over ArrayList.
 

Sharp

Member
jeebus. finally got most of my code down with no apparent errors and then blam. stackoverflow errors :l i'm stumped. have at it.
here's the error

I'm stumped. But I think my GameObjectList isn't storing any objects so therefore it's crashing.
I would need to see the entire program in order to be able to help you diagnose it. If you don't feel comfortable posting it here, you can PM me.
 

usea

Member
Code:
public class Tank extends Movable implements ISteerable // association with Movable and is Steerable FIX
{
	 [...]
	 public void setDirection(int direction)
	 {
		this.setDirection(direction); // get input from left turn or right turn
		// updateValues();
	 }
Is setDirection supposed to immediately re-call itself? That'd lead to a stack overflow for sure. I imagine you meant getDirection?
 

Sharp

Member
Is setDirection supposed to immediately re-call itself? That'd lead to a stack overflow for sure. I imagine you meant getDirection?
Good catch--but it's not clear to me where, if anywhere, that's being called. And actually, on a properly tail-call optimizing compiler, I don't even know if this would lead to a stack overflow...
 

usea

Member
Good catch--but it's not clear to me where, if anywhere, that's being called. And actually, on a properly tail-call optimizing compiler, I don't even know if this would lead to a stack overflow...
Probably wouldn't lead to a bunch of vector calls in the stack trace either.
 
Running to a problem that's annoying me. I have a BST with the following:
Code:
typedef struct BST{
 node pointer; /*this points to another node containing all the info*/
 struct tree *left;
 struct tree *right;
}tree;

Now node has this:
Code:
struct important{
char *string;
int count;
/*...other things like an array inside of it*/
}; typedef struct important *node;
What I'm trying to do is add items of nodes into the BST.
my insert in something like:
Code:
tree * insert(tree *list,node *add){{
tree *ptr=NULL;
	if(list==NULL){
		ptr=(tree*)malloc(sizeof(tree));
		ptr->pointer=add;
		ptr->left=NULL;
		ptr->right=NULL;
		return ptr;
	}
	if((strcmp((*add)->string, theTree->pointer->string))<0){
		insert(theTree->left,add);
	}
	if((strcmp((*add)->string, theTree->pointer->string))>0){
		insert(theTree->right,add);}
	return list;
I get "assignment from incompatible pointer type"
I tried putting a * in pointer to be: node *pointer;
But then I get:
Code:
 error: request for member ‘string’ in something not a structure or union
This is annoying me so much, I can't figure it out. Anyone can help?
 
What is "word" defined as? I don't see it anywhere in your node struct definition. From just glancing at it real quick, shouldn't you be trying to access "theTree->string" instead of "theTree->word->string"?

Also, in your parameter list, should they both defined as "node" (with a lower case N)? I don't see anywhere where you've defined a "Node" struct (just a node).
 
What is "word" defined as? I don't see it anywhere in your node struct definition. From just glancing at it real quick, shouldn't you be trying to access "theTree->string" instead of "theTree->word->string"?

Also, in your parameter list, should they both defined as "node" (with a lower case N)? I don't see anywhere where you've defined a "Node" struct (just a node).
Woops, typo. It's theTree->pointer->string.

I changed the function to be this actually:
Code:
tree * insert(tree *list, WordPtr *add){
/unchanged*/
}
....let me edit my previous post
Edit: but no, the tree doesn't have a member called string. Pointer has it. So it can't be theTree->string.
 
Very strange. Usually you only get a StackOverflowError when you use too much recursion and the call stack is not big enough, but that doesn't seem to be the issue here. Have you used a debugger to see the state of each variable? By the way, use an ArrayList<T> instead of the Vector class, Vector is basically a legacy class that has some small disadvantages over ArrayList.
I'll use a debugger to check it out. Thanks.

I would need to see the entire program in order to be able to help you diagnose it. If you don't feel comfortable posting it here, you can PM me.

Hmmm mebbe.

Is setDirection supposed to immediately re-call itself? That'd lead to a stack overflow for sure. I imagine you meant getDirection?

that might be it. thanks.

Good catch--but it's not clear to me where, if anywhere, that's being called. And actually, on a properly tail-call optimizing compiler, I don't even know if this would lead to a stack overflow...

Thanks for all the help so far. Really good things to catch. 12 more hours to code this Tank game.
EDIT:

I guess the only things that I need to do for this program is to implement a Observable interface by updating JLabel values and ... fix any bugs that happen.
 
Woops, typo. It's theTree->pointer->string.

I changed the function to be this actually:

....let me edit my previous post
Edit: but no, the tree doesn't have a member called string. Pointer has it. So it can't be theTree->string.

This looks suspicious:

"(*add)->string"

I don't have a lot of time at the moment to look into it a lot, but *add is a pointer to a typedef'd struct pointer, which is kinda asking for trouble (at least in terms of debugging).

Honestly, I would recommend simplifying the code a bit. The amount of pointers makes it confusing to follow, and typedef'ing pointers is not generally a good idea in my opinion. Whenever I've written binary trees, I just keep all of my info for each node in a single struct. I realize that might not be ideal if your node is supposed to house a lot of information, but it's easier to code and debug. Right now you have a base struct with a pointer to a typedef'd pointer struct, which can be hard to follow, and it's really easy to mess up your pointers and dereferences in there.
 
This looks suspicious:

"(*add)->string"

I don't have a lot of time at the moment to look into it a lot, but *add is a pointer to a typedef'd struct pointer, which is kinda asking for trouble (at least in terms of debugging).

Honestly, I would recommend simplifying the code a bit. The amount of pointers makes it confusing to follow, and typedef'ing pointers is not generally a good idea in my opinion. Whenever I've written binary trees, I just keep all of my info for each node in a single struct. I realize that might not be ideal if your node is supposed to house a lot of information, but it's easier to code and debug. Right now you have a base struct with a pointer to a typedef'd pointer struct, which can be hard to follow, and it's really easy to mess up your pointers and dereferences in there.
Nvm, I solved it. Sometimes, I really think the best solution to my stupid mistakes is just to leave and come back to it later. If I just made it ptr->pointer=(*add). Thanks though!

edit: NVM my edit, I solved it. Forgot to add theTree->left or right in my insertion method!
 
Nope. I'm definitely still stumped. There's about 20+ classes so I won't show all the code except for the code that keeps on giving the errors.

here's a example of the uml diagram

http://i.imgur.com/rN5cPO9.png

Error Code
Code:
at java.util.AbstractList.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at java.util.Vector.<init>(Unknown Source)
	at a2.GameWorld.<init>(GameWorld.java:9)
	at a2.Movable.<init>(Movable.java:12)
	at a2.Tank.<init>(Tank.java:8)
and keeps on repeating.

GameWorld
Code:
package a2;

import java.awt.*;
import java.util.*;

public class GameWorld implements IObservable, IGameWorld 
{
// create collections class
private Vector<GameObject> GameObjectList = new Vector<GameObject>(); // PROBLEM stack overflow error
private Vector<IObserver> ObserverList = new Vector<IObserver>(); // vector to hold observers

// declare objects
private Tank pTank = new Tank(10, 10);
private EnemyTank eTank = new EnemyTank(10,10);
private Missile missile = new Missile(5);
private Random rand = new Random();
private Tree tree = new Tree(rand.nextInt(20) + 1);
private Rock rock = new Rock(rand.nextInt(20) + 1, rand.nextInt(20) + 1);
private int locX = 0 + (int) (Math.random() * ((1+ 1023.0) - 0)); // random from 0 - 1023.0
private int locY = 0 + (int) (Math.random() * ((1 + 1023.0) - 0)); // random spawn location
private Point newCoord = new Point(); // to fill in for new location
private int randFixed = 0 + (int) (Math.random() * ((1+ 20) - 0));
private int time; // time decrement
private int numberofLives; // number of lives
private int score; // player score
private Scanner userInput; // userinput to create items
private int numTank, numRock, numTree; // get user input for number of objects to create
public GameWorld() // create objects and add them to vector
{

	getpTank().setColor(Color.BLACK);
	eTank.setColor(Color.BLUE);
	rock.setColor(Color.ORANGE);
	tree.setColor(Color.GREEN);
	newCoord.x = locX; // All GameObjects have a random location of 0-1023.0 for x,y
	newCoord.y = locY;
	
}
public void spawn() // create game from user inputs
{
	System.out.println("How many enemy tanks to spawn?");
	userInput = new Scanner(System.in);
	numTank = userInput.nextInt();
	System.out.println();
	for (int i = 0; i < numTank; i++)
	{
		eTank = new EnemyTank(10,10);
		getGameObjectList().add(eTank);
		eTank.setStrategy(new FirstStrat()); // set strategy
	}
	System.out.println("How many trees to spawn?");
	userInput = new Scanner(System.in);
	numTree = userInput.nextInt();
	System.out.println();
	for (int i = 0; i < numTree; i++)
	{ 
		tree = new Tree(randFixed); // random variables
		getGameObjectList().add(tree);
	}
	System.out.println("How many rocks to spawn?");
	userInput = new Scanner(System.in);
	numRock = userInput.nextInt();
	System.out.println();
	for (int i = 0; i < numRock; i++)
	{
		rock = new Rock(randFixed, randFixed); // random variables
		getGameObjectList().add(rock);
	}
	getGameObjectList().add(pTank); // add player Tank
	
}
public void add(GameObject o) // add object to gameworld
{
	getGameObjectList().add(o);
}
public Iterator<GameObject> getIterator() // iterate object in gmeworld
{
	return getGameObjectList().iterator();
}
public boolean removeObj(Object obj) // remove object in gameworld
{
	getGameObjectList().remove(obj);
	return false;
}

public void update(IObserver obs, GameObject obj) // update gameworld
{
	System.out.println("Updated " + obj);
}
public void addObserver(IObserver o) // add observable to list
{
	ObserverList.add(o);
}
public void notifyObservers() // iterate to notify observers of change
{
	GameWorldProxy proxy = new GameWorldProxy(this);
	for ( IObserver o : ObserverList)
	{
		o.update((IObservable)proxy, null);
	}
}
// accessor mutators
public int getTime()
{
	return time;
}
public int getScore()
{
	return score;
}
public int getLives()
{
	return numberofLives;
}
public void setScore(int s)
{
	score = s; // new score
}

public void setTime(int t)
{
	time = t; // new time
}
public void setLives(int l)
{
	numberofLives = l; // new lives
}
public Tank getpTank() {
	return pTank;
}
public void setpTank(Tank pTank) {
	this.pTank = pTank;
}
public Missile getMissile() {
	return missile;
}
public void setMissile(Missile missile) {
	this.missile = missile;
}
public EnemyTank getETank() {
	return eTank;
}
public void setETank(EnemyTank eTank) {
	this.eTank = eTank;
}

public Rock getRock() {
	return rock;
}

public void setRock(Rock rock) {
	this.rock = rock;
}

public Tree getTree() {
	return tree;
}

public void setTree(Tree tree) {
	this.tree = tree;
}
public Vector<GameObject> getGameObjectList() {
	return GameObjectList;
}
public void setGameObjectList(Vector<GameObject> gameObjectList) {
	GameObjectList = gameObjectList;
}
}

Tank
Code:
package a2;

public class Tank extends Movable implements ISteerable 
{
	 private int armorStrength;
	 private int missileCount;

	 public Tank(int armStr, int misslCt) // problem? 
	 {
		 armorStrength = armStr; // default armorStrength
		 missileCount = misslCt; // default missileCount
	 }
	 public void setDirection(int direction) // accessor and mutators
	 {
		 this.setDirection(direction);		 
	 }

	 public int getarmorStr()
	 {
		 return armorStrength;
	 }
	 public int getmissileCount()
	 {
		 return missileCount;
	 }
	 public void setArmorStr(int armStr)
	 {
		 this.armorStrength = armStr;
	 }
	 public void setMissileCt(int missCt)
	 {
		 this.missileCount = missCt;
	 }
}

Movable
Code:
package a2;

import java.awt.Point;

abstract class Movable extends GameObject// is part of GameObjects
{
	 // direction
	 private int direction; // always even multiples of 5
	 private int speed;
	 private double deltaX;
	 private double deltaY;
	 private GameWorld GW = new GameWorld(); // ERROR
	 
	 public Movable()  
	 {
		super();
		
	 }
	 public int getDirection() // accessors and mutators
	 {
		 return direction;
	 }
	 public int getSpeed()
	 {
		 return speed;
	 }
	 public void setSpeed(int spd)
	 {
		 this.setSpeed(spd);
	 }
	 public void move(int dir, int spd) 
	 {
		 // update it's location based on its current speed and direction
		 // 0 = north, 90 = east, 180 = south, 270 = west
		 Point oldLoc = new Point();
		 Point newLoc = new Point();
		 Point theta = new Point();
		 oldLoc.x = getLocation().x;
		 oldLoc.y = getLocation().y;
		 this.direction = dir; // get from specific GameObject
		 this.speed = spd; 
		 deltaX = Math.cos(Math.toRadians(90))*speed;
		 deltaY = Math.sin(Math.toRadians(90))*speed;
		 theta.x = (int) deltaX;
		 theta.y = (int) deltaY;
		 
		 // new location; 
		 newLoc.x = oldLoc.x + theta.x;
		 newLoc.y = oldLoc.y + theta.y;
		 
		 for (int i = 0; i < GW.getGameObjectList().size(); i++) // then set new location with setLocation(newLoc)
		 {
			 GW.getGameObjectList().elementAt(i).setLocation(newLoc);
		 }
		 
	 }
	 public void update() // update the firing strategies
	 {
		 for ( int i = 0; i < GW.getGameObjectList().size(); i++ )
		 {
			 if (GW.getGameObjectList().elementAt(i) instanceof EnemyTank)
			 {
				 EnemyTank enTank = (EnemyTank) GW.getGameObjectList().elementAt(i);
				 // get first strat
				 if (enTank.getStrategy() == new FirstStrat() )
				 {
					 enTank.setStrategy(new SecondStrat()); // switch to second
				 }
				 if (enTank.getStrategy() == new SecondStrat() ) // vice versa
				 {
					 enTank.setStrategy(new FirstStrat());
				 }
				  
			 }
		 }
		 
	 }
}

There's recursion somewhere that's not safe and I can't pinpoint it. /Headdesk.
 

Chris R

Member
Your tank has a GameWorld that makes a Tank that has a GameWorld that makes a Tank ect it looks like to me... Haven't touched java in years though.
 

usea

Member
1) setDirection(int) is still calling itself.

2) it seems really strange to me that Movable's move() function updates the location of every game object in the world. (including itself)

rhfb is right. Why are you making a new GameWorld inside of Movable? That makes zero sense.

Every Tank is Movable. So every tank has another world inside of it. etc
 
i'm calling game world to access the gameobjectlist vector in order to use the iterator to be able to update the locations of the gameobjects.

and the movable move() is something that has to be implemented in that way for professor's requirements.
 

usea

Member
i'm calling game world to access the gameobjectlist vector in order to use the iterator to be able to update the locations of the gameobjects.
That's not how it works. You're making a new one, you're not calling the one that already exists.

Code:
private GameWorld GW = new GameWorld(); // ERROR
This says to make a new GameWorld, completely separate from the other ones you've already made. You make a new one for every tank. And those new worlds each go and make their own tanks, which make their own new worlds. It gets out of control very quickly.
 

Gonff

Banned
Nope. I'm definitely still stumped. There's about 20+ classes so I won't show all the code except for the code that keeps on giving the errors.

Tank
Code:
package a2;

public class Tank extends Movable implements ISteerable 
{
	 private int armorStrength;
	 private int missileCount;

	 public Tank(int armStr, int misslCt) // problem? 
	 {
		 armorStrength = armStr; // default armorStrength
		 missileCount = misslCt; // default missileCount
	 }
	 public void setDirection(int direction) // accessor and mutators
	 {
		 this.setDirection(direction);		 
	 }

	 public int getarmorStr()
	 {
		 return armorStrength;
	 }
	 public int getmissileCount()
	 {
		 return missileCount;
	 }
	 public void setArmorStr(int armStr)
	 {
		 this.armorStrength = armStr;
	 }
	 public void setMissileCt(int missCt)
	 {
		 this.missileCount = missCt;
	 }
}


There's recursion somewhere that's not safe and I can't pinpoint it. /Headdesk.

Unless I am reading it wrong, isn't your method here setDirection infinitely recursive?
 

Jokab

Member
Unless I am reading it wrong, isn't your method here setDirection infinitely recursive?

It definitely is. At first I thought there was a mistake where the intention was to call the method in the superclass Movable (the mistake being that it would have called the local method anyway), but that that doesn't seem to be the case.
 

diaspora

Member
There's something about this simple program that's baffling me:

Code:
#include<stdio.h>

int main()
{
	int num, i;
	char letters;
	
	printf("Enter an integer: ");
	
	while(scanf("%d%c",&num,&letters) != 2)
	{
    	printf("Please enter an integer only : ");
    	scanf("%c",&letters);
	}
	
	for(i=0; i < num; i++)
		printf("*");
	
	return 0;
}

Essentially it's printing a * for an entered integer. 1 = *, 2 = ** etc (for loop), but also making sure the input is just an integer, otherwise the instructions in the while loop execute. Fine. But what I don't get about the while loop is the condition. What does it mean? Is it scanning for both an int and a char? Or is it looking for an int OR char? When scanning in the while loop's instructions, why is it looking for a char?
 
It definitely is. At first I thought there was a mistake where the intention was to call the method in the superclass Movable (the mistake being that it would have called the local method anyway), but that that doesn't seem to be the case.

yea i'll writing a new method for setdirection. thanks everyone for the help.
 

arit

Member
There's something about this simple program that's baffling me:

Code:
#include<stdio.h>

int main()
{
	int num, i;
	char letters;
	
	printf("Enter an integer: ");
	
	while(scanf("%d%c",&num,&letters) != 2)
	{
    	printf("Please enter an integer only : ");
    	scanf("%c",&letters);
	}
	
	for(i=0; i < num; i++)
		printf("*");
	
	return 0;
}

Essentially it's printing a * for an entered integer. 1 = *, 2 = ** etc (for loop), but also making sure the input is just an integer, otherwise the instructions in the while loop execute. Fine. But what I don't get about the while loop is the condition. What does it mean? Is it scanning for both an int and a char? Or is it looking for an int OR char? When scanning in the while loop's instructions, why is it looking for a char?

scanf scans the input according to a given format, here it would be "%d%c". So it takes all the chars as long as it could parse them as an integer and saves them to number, then takes a look at the next input, which would be an char, since a number would be just parsed along the previous ones and it would return 2 since it has parsed 2 inputs according to format.

If you append a
Code:
printf("%d", (int)letters);
after the output, you'll see it. Though it would leave any additional inputs after the first char back in stdin.
Code:
printf("%d", (int)letters);
printf(", %d", (int)getchar());

Would show you 97, 10 if you enter 13aenterkey (or 97, 98 with 13abwhateverenterkey).

EDIT: the more I think about it, the more I'm not understanding the why either. If you'd only scanf for %d and check for 1 as return value, you would stay in the loop until you get a parsable int. So in the end I think it is just a try at kicking the '\n' out of the stdin buffer after a "correct" user input.
 
Hi! guys I'm back with another question in this program I'm tasked with writing a program that meets these requirements.

For research purposes and to better help students, the admissions office of your local university wants to know how well female and male students perform in certain courses. You receive a file that contains female and male student GPAs for certain courses. Due to confidentiality, the letter code f is used for female students and m for male students. Every file entry consists of a letter code followed by a GPA. Each line has one entry. The number of entries in the file is unknown. Write a program that computes and outputs the average GPA for both female and male students. Format your results to two decimal places.

As of right now I'm received an error that my file has not loaded. All the coding looks right in my eyes. Need some suggestions.
Code:
#include<fstream>
#include<iomanip>
#include<iostream>
#include<cstdlib>
using namespace std;

void openFiles(ifstream& in_stream,ofstream& out_stream);
void initialize(int& countFemale,int& countMale,double& sumFemaleGPA,double& sumMaleGPA);
void sumGrades(int& countMale,int& countFemale,double& sumMaleGPA,double& sumFemaleGPA,ifstream& in_stream); 
void averageGrade(double& avgMaleGPA, double& avgFemaleGPA,int countMale,int countFemale,double sumMaleGPA,double sumFemaleGPA);
void printResults(double avgMaleGPA,double avgFemaleGPA,ofstream& out_stream);



int main ()
{
	ifstream in_stream;
	ofstream out_stream;
	
	
	int countFemale, countMale;
	double sumFemaleGPA, sumMaleGPA;
	double avgFemaleGPA, avgMaleGPA;

	initialize(countFemale,countMale,sumFemaleGPA,sumMaleGPA);
	openFiles(in_stream,out_stream);
	sumGrades(countMale,countFemale,sumMaleGPA,sumFemaleGPA,in_stream);
	averageGrade(avgMaleGPA,avgFemaleGPA,countMale,countFemale,sumMaleGPA,sumFemaleGPA);
	printResults(avgMaleGPA,avgFemaleGPA,out_stream);

	in_stream.close();
	out_stream.close();


return 0;
}

void openFiles(ifstream& in_stream,ofstream& out_stream)
{
	
	
	
	
	in_stream.open("Project01_Part02Data.txt");
	if (in_stream.fail() )
	{ 
		cout << "Input file opening failed. " << endl;
		exit(1);
	}
	out_stream.open("outfile.dat");
	if (out_stream.fail() )
	{
		cout << "Output file opening failed" << endl;
		exit(1);
	}
	out_stream.setf(ios::showpoint);
	out_stream.setf(ios::fixed);
	out_stream.precision(2);
}
void initialize(int& countFemale,int& countMale,double& sumFemaleGPA,double& sumMaleGPA)
{
    countFemale = 0;
    countMale = 0;
    sumFemaleGPA = 0.0;
    sumMaleGPA = 0.0;
}
void sumGrades(int& countMale,int& countFemale,double& sumMaleGPA,double& sumFemaleGPA,ifstream& in_stream) 
{
	char ch = 'a';
	double GPA;
	while (ch != '#')
	{ 		
		in_stream >> ch >> GPA;
		if (ch == 'm')
		{
			sumMaleGPA = sumMaleGPA + GPA;
			countMale++;
		} 
		else 
		{
			sumFemaleGPA = sumFemaleGPA + GPA;
			countFemale++;
		}
	}	
}

	

void averageGrade(double& avgMaleGPA, double& avgFemaleGPA,int countMale,int countFemale,double sumMaleGPA,double sumFemaleGPA) 
{
	avgMaleGPA = sumMaleGPA / countMale;
	avgFemaleGPA = sumFemaleGPA / countFemale;
}
void printResults(double avgMaleGPA,double avgFemaleGPA,ofstream& out_stream) 
{
	out_stream << "Average male GPA: " << avgMaleGPA
			<< "Average female GPA: " << avgFemaleGPA << endl;
}
 
Another question, I've been strongly contemplating purchasing a MacBook Pro.So I also plan to use Xcode to program by labs. My lab instructor only requests we upload the cpp file. He uses Windows will I be able to this without having to dual boot my laptop.
 

Kalnos

Banned
Another question, I've been strongly contemplating purchasing a MacBook Pro.So I also plan to use Xcode to program by labs. My lab instructor only requests we upload the cpp file. He uses Windows will I be able to this without having to dual boot my laptop.

You should be able to do it fine.
 

Dr_Swales

Member
Gaf I'm currently struggling with design patterns at school. The book we are using is head first design patterns. Are there any other books or websites people would recommend? I'm really struggling recognizing and implementing design patterns. I'm fine when it comes to homework I eventually figure it out, but I do not feel at all comfortable with it.

The book we recommend to our students is the book by 'The Gang of Four' titled "Design Patterns: Elements of Reusable Object-Oriented Software". The first half of the book is a look at OO programming in general and the second half is all about design patterns with example implementations in C++.

There are some handy on-line resources such as this website.

Good Luck!
 

diaspora

Member
scanf scans the input according to a given format, here it would be "%d%c". So it takes all the chars as long as it could parse them as an integer and saves them to number, then takes a look at the next input, which would be an char, since a number would be just parsed along the previous ones and it would return 2 since it has parsed 2 inputs according to format.

What do you mean that an integer input would be parsed along the previous ones? I get what you mean by "takes all the chars as long as it could parse them as an integer and saves them to number", but not that.
 

NaM

Does not have twelve inches...
Powershell is very powerful, I just wish I had discovered this a long time ago so I could have saved myself some headaches.
 
Powershell is very powerful, I just wish I had discovered this a long time ago so I could have saved myself some headaches.

Can you recommend a good Powershell tutorial? I feel it would be helpful to learn, but I'm just so much more comfortable with Bash, so I tend to just use Cygwin when I'm on Windows.
 

Sharp

Member
PowerShell is awful. PowerShell 3 improves this somewhat but basically anything useful that you have to do you have to do directly using .NET instructions. Take my advice and just write whatever you thought would be easier in PowerShell in C#, it'll save you time and heartache.
 

upandaway

Member
Man what a dilemma. I wrote the code, I should be able to copy paste it guilt free, but deep down I know that I don't fully understand it like I did when I wrote it, and it'll take me to review a bunch of material to get to that point again. I can't even use the excuse that I can use that time saved to learn new things, because I know any minute I save by copy-pasting will go straight to games or the neogafs.

So every time I copy something I have to think long and hard whether I want to go back to understand it again, it messes with my head.
I considered that it might feel better if I wrote all code with re-implementation in mind to begin with, but I don't know...
 

nan0

Member
PowerShell is awful. PowerShell 3 improves this somewhat but basically anything useful that you have to do you have to do directly using .NET instructions. Take my advice and just write whatever you thought would be easier in PowerShell in C#, it'll save you time and heartache.

Why not both? There's scriptcs, which enables you to execute C# programs as scripts.

Can you recommend a good Powershell tutorial? I feel it would be helpful to learn, but I'm just so much more comfortable with Bash, so I tend to just use Cygwin when I'm on Windows.

There's a free Powershell eBook, which is pretty extensive.
 

usea

Member
I strongly recommend LINQPad for quickly running C# code. I can't say it's better than Powershell because I don't know powershell. But it's pretty fantastic. I use it every day it quickly type up and run some C# code.
 
Top Bottom