• 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

Chris R

Member
I haven't touched assembly in 5 or 6 years, I just saw that you were trying to treat 0x14 as 14 and thought that changing it to 0xe might fix it for you. Sorry it didn't! Someone with more assembly knowledge might know what's up though.
 
I would also ask: where are you storing your x and y? Tracking the values of regs, assuming the following ASM:
Code:
main:
	ori	$5, $0, 0x1	; $5 = 1
	ori	$6, $0, 0x1	; $5 = 1, $6 = 1
	ori	$7, $0, 0xE	; $5 = 1, $6 = 1, $7 = 14
	sll	$5, $5, 3	; $5 = 8, $6 = 1, $7 = 14
	sll	$6, $6, 1	; $5 = 8, $6 = 2, $7 = 14
	subu	$8, $5, $6	; $5 = 8, $6 = 2, $7 = 14, $8 = 6
	addu	$10, $7, $8	; $5 = 8, $6 = 2, $7 = 14, $8 = 6, $10 = 20

what you're calculating is the result of (8 - 2) + 14. You need to incorporate X and Y somewhere.

Let's say, for example, that X is in R1 and Y is in R2.

Code:
main:
	ori	$3, $0, 0xE	; $3 = 0xE (14)
	sll	$1, $1, 3	; $1 = x << 3 = 8x
	sll	$2, $2, 1	; $2 = y << 1 = 2y
	subu	$4, $1, $2	; $4 = $1 - $2 = (8x - 2y)
	addu	$4, $4, $3	; $4 = $4 + $3 = (8x - 2y) + 14
R4 contains the result.
 

Mabef

Banned
I'm going through a Java class atm and have a pretty simple question.

I have a for loop that loops by an amount set by the user. Here's kind of what it looks like, if there are syntax errors it's because I'm going off memory..

Code:
System.out.print("How many exams? ";
count[0] = input.nextInt();

for (int i = 0; i < count[0]; i++){
     System.out.print("Enter exam " + (i+1) + " score: ");
}

It works good, except if the user enters 0. Then I get errors.
Code:
Exception in thread "main" java.lang.ArithmeticException: / by zero
I'm guessing it's because of "i < count[0]", aka "do while 0 < 0". Is there a smart way to avoid this? I was going to couch the whole thing in an if statement, if (count[0] != 0), but that seems a little clunky?
 
I would also ask: where are you storing your x and y? Tracking the values of regs, assuming the following ASM:
Code:
main:
	ori	$5, $0, 0x1	; $5 = 1
	ori	$6, $0, 0x1	; $5 = 1, $6 = 1
	ori	$7, $0, 0xE	; $5 = 1, $6 = 1, $7 = 14
	sll	$5, $5, 3	; $5 = 8, $6 = 1, $7 = 14
	sll	$6, $6, 1	; $5 = 8, $6 = 2, $7 = 14
	subu	$8, $5, $6	; $5 = 8, $6 = 2, $7 = 14, $8 = 6
	addu	$10, $7, $8	; $5 = 8, $6 = 2, $7 = 14, $8 = 6, $10 = 20

what you're calculating is the result of (8 - 2) + 14. You need to incorporate X and Y somewhere.

Let's say, for example, that X is in R1 and Y is in R2.

Code:
main:
	ori	$3, $0, 0xE	; $3 = 0xE (14)
	sll	$1, $1, 3	; $1 = x << 3 = 8x
	sll	$2, $2, 1	; $2 = y << 1 = 2y
	subu	$4, $1, $2	; $4 = $1 - $2 = (8x - 2y)
	addu	$4, $4, $3	; $4 = $4 + $3 = (8x - 2y) + 14
R4 contains the result.

I'm currently storing X and Y in R5 and R6 respectively

as such:

Code:
                ori     $5,$0,0x1   ## loads R5 with 1 (x)
                ori     $6,$0,0x1   ## loads R6 with 1 (y)
		ori 	$7,$0,0xE   ## loads R7 with 14 
		sll 	$5, $5, 3   ## Shifts value in R5 3 places to represent multiplication by 8
		sll 	$6, $6, 1   ## Shifts value in R6 1 place to represent multiplication by 2 
		subu 	$8, $5, $6  ## Subtracts vale in R6 from R5 and stores in R8
		addu 	$10, $7, $8 ## Adds the difference in R8 to constant value in R7 (14) and stores the sum in R10
 

Slavik81

Member
I'm going through a Java class atm and have a pretty simple question.

I have a for loop that loops by an amount set by the user. Here's kind of what it looks like, if there are syntax errors it's because I'm going off memory..

Code:
System.out.print("How many exams? ";
count[0] = input.nextInt();

for (int i = 0; i < count[0]; i++){
     System.out.print("Enter exam " + (i+1) + " score: ");
}

It works good, except if the user enters 0. Then I get errors.
Code:
Exception in thread "main" java.lang.ArithmeticException: / by zero
I'm guessing it's because of "i < count[0]", aka "do while 0 < 0". Is there a smart way to avoid this? I was going to couch the whole thing in an if statement, if (count[0] != 0), but that seems a little clunky?
I don't know Java, but I don't think your code there could cause that error. That's a divide-by-zero error, but you aren't doing any division. The issue is caused by something that's in your real program, but not in what you've typed out here.
 
It seems that everything is arithmetically correct, just that the answer is outputted in hex, which i guess is ok. I'm extremely new to assembly and i'm not sure if it's even possible for a decimal number to be represented in a SPIM register. I'm gonna go ahead and just assume that this is ok enough because i'm starting to get a headache lol. Anyways, thanks for all the help guys.
 
It seems that everything is arithmetically correct, just that the answer is outputted in hex, which i guess is ok. I'm extremely new to assembly and i'm not sure if it's even possible for a decimal number to be represented in a SPIM register. I'm gonna go ahead and just assume that this is ok enough because i'm starting to get a headache lol. Anyways, thanks for all the help guys.
Sorry there, must've misinterpreted on my part. Though, it does seem odd... what sort of compiler are you using?
 
PCSpim MIPS Simulator
Hmm, your original code seems fine to me... after spending some time learning how to use this, lol - took me a bit of time, since I never used a compiler when I worked with MIPS, all handwritten.

Usually, I always use hex when dealing with assembly, so that what I'm looking at corresponds with what I type.
 

Mabef

Banned
I don't know Java, but I don't think your code there could cause that error. That's a divide-by-zero error, but you aren't doing any division. The issue is caused by something that's in your real program, but not in what you've typed out here.
Haha.

Yep.
Code:
//further down...
count[0] = tempTotal / count[0];
Thanks for the help.
 

jokkir

Member
First time I'm trying to use Modules in Perl. What am I doing wrong exactly?

Code:
#!/usr/bin/perl

use BingoCard;

print "Content-Type: text/html\n\n";
print "<!DOCTYPE html>";
print "<html>";
print "	<head>";
print "		<title>Bingo</title>";
print "	</head>";
print "	<body>";
			makeBingoCard();
print "	</body>";
print "</html>";

BingoCard Module:
Code:
#!/usr/bin/perl

package BingoCard;

#use BingoRandomizer;

use Exporter;
our @ISA = qw( Exporter );
our @EXPORT = qw( &makeBingoCard );

sub makeBingoCard{
	my $rows = 5;
	my $columns = 5;

	print "<table>";
		for($i = 0; $i <= $rows; $i++){
			print "<tr>";
			for($j = 0; $j <= $columns; $j++){
				if($i == 3 && $j == 3){ #Check to see if the middle of the bingo card for free space square
					print "<td> Free Space! </td>";
				}else{
					print "<td> entry $j</td>";
				}
			}
			print "</tr>";
		}
	print "</table>";
}

I'm trying my hand at making a Bingo card generator for GAF lol. I'll port it to PHP after I finish this since I have a midterm for this class next week. I thought making a Bingo card would help me study.

Also, what are easier ways to create HTML pages in Perl? I tried the:

print "Content-type: text/html\n\n";
print <<HTML
<!DOCTYPE html>
<html>
<head>
<title>NeoGAF Bingo</title>
</head>
<body>
Test
</body>
</html>
HTML
exit;

method but that didn't seem to work. Also, what is a way to get useful errors than just the 500 internal server error? Thanks!
 

Onemic

Member
You want to repeat a process until a certain condition is met. Therefore you should use a while loop.

Code:
scanf("%d", &SINnum);
while (SINnum != 0) {
  ...
  scanf("%d", &SINnum);
}

or

Code:
while (true) {
  scanf("%d", &SINnum);
  if (SINnum == 0) break;
  ...
}

or if you care about compactness, you can do the same thing with a for loop


Code:
for(scanf("%d", &SINnum); SINnum != 0; scanf("%d", &SINnum)) {
  ...
}

Thanks, I'll try this

Since player1Score and gamesPlayed are still ints, they get evaluated as such.
You could cast within the calculation
Code:
        score1 = ((double)player1Score / gamesPlayed) * 100;
or if an int score would be sufficient just calculate as
Code:
        score1 = (player1Score * 100) / gamesPlayed;

Worked perfectly, thanks.
 
Hmm, your original code seems fine to me... after spending some time learning how to use this, lol - took me a bit of time, since I never used a compiler when I worked with MIPS, all handwritten.

Usually, I always use hex when dealing with assembly, so that what I'm looking at corresponds with what I type.

Ya I guess it just threw me off haha bc i was completely unfamiliar with this until yesterday
 

arit

Member
You might want to take a look at MARS as an alternative to SPIM, at least to me it was easier to use. Though there are some differences in the emulator specific build in OP-codes, that extend the normal MIPS instruction set, so asking a tutor about it could be necessary.
 

Zoe

Member
Need a little guidance from people who are more book-smart in CS... bf might apply for a position that is said to have interviews heavy on data structure and algorithms. What does that entail? Coming from an electrical engineering background, he's not sure whether he really learned much of that.
 

Tamanon

Banned
Fall break is coming up, so I ordered an actual legitimate book, Beginning Ruby, instead of all my PDFs and e-books. I think part of the reason I keep getting distracted is that just alt-tabbing between kindle/IDE is tempting me to just surf the internet. Been trying to get into Python, but it's been tough sledding.

And, right now I'm learning Ruby because it seems to have a wider berth of possibilities when I finish school in two years. My degree will be in Industrial Technology(Networking/Security concentration),but I know it's really useful for scripting. Still pondering if I'm going to change to a Comp Sci degree after transferring this Spring to a 4-year college. I know it'd add another year onto my time there, weighing if I can just learn on my own and use that as a backstop for networking.
 

poweld

Member
Need a little guidance from people who are more book-smart in CS... bf might apply for a position that is said to have interviews heavy on data structure and algorithms. What does that entail? Coming from an electrical engineering background, he's not sure whether he really learned much of that.

Knowing data structures is pretty straightforward. He should probably know in-and-out the usage and how to implement (not applicable for array, really) the most important ones. Here's a list I'd like a candidate to be knowledgeable on:
  • Array
  • Linked List (singly and doubly linked)
  • Stack
  • Queue
  • HashMap
  • Binary Tree
He should be able to give an example of when you'd use each, and have an idea of the average and worst case performance in Big-O notation for insertion, deletion, and search for each.

As far as algorithms go, it's not really something that you can "know". Writing a lot of code and knowing design patterns helps, but they're just going to ask him to solve some problems on a whiteboard and see how he attempts to solve it.

Sometimes the algorithms they will have you implement are very difficult, and they are really looking for insight on his thought process more than whether the correct answer is found.
 

tokkun

Member
Need a little guidance from people who are more book-smart in CS... bf might apply for a position that is said to have interviews heavy on data structure and algorithms. What does that entail? Coming from an electrical engineering background, he's not sure whether he really learned much of that.

I got my BS in EE, and did not learn most of that stuff in the degree program. I also applied and got hired at high-profile software company with that sort of interview process. In order to prep for the interview, I spent about a month reading books on algorithms and languages and I also did a lot of the archived competition questions from TopCoder and read the commentary on the solutions.

Here are a few things for your boyfriend to consider to judge where he is at in terms of his knowledge:

-Can you determine the asymptotic ("Big O") complexity of an algorithm? For example, determine the complexity of merge-sort.
-Can you write algorithms to traverse the major data structures? For example do a breadth-first search in a graph or determine if an item exists in a binary search tree.
-For a given program that must store and access data, can you evaluate the tradeoffs of storing the data in an array vs a linked-list vs a tree vs a hash table? For example, if I told you that I wanted to a data structure to store an English Dictionary, what would you choose and why? Under what situations would your choice be a bad decision?
-Do you understand how to use techniques like Divide-and-Conquer and Dynamic Programming to solve problems efficiently? You can find sample problems for these online.
 

moka

Member
We've recently started learning about Haskell at university and I'm getting really into it. Functional programming is pretty cool and in Haskell 'a function is a first-class citizen'.

Been defining loads of weird functions by recursion, something I never really got the hang of with Java.
 
I have a little school assignment in java which includes reading from ini file. I have tried googling how reading ini files work in java work but couldn't really find what I was after.

The ini file includes has section which have keys. And user has to pick one of the sections and their keys and the program will output the key's value.

I think all you're trying to do is read from a file. If so, look at: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/Reader.html

If you just want to read all the lines from a file and store them in a List<String>, there is a method in java.nio.files, Files.readAllLines(Path, Charset) that does all that for you in one go. It's a lot more convenient than having to mess around with a FileReader and a File object and what have you. I don't like the old Java File API very much. It's almost admirable how overengineered it is while still requiring you to read one character at a time like you would in C. Luckily, there's a lot of convenience methods in java.nio.
 

Atruvius

Member
If you just want to read all the lines from a file and store them in a List<String>, there is a method in java.nio.files, Files.readAllLines(Path, Charset) that does all that for you in one go. It's a lot more convenient than having to mess around with a FileReader and a File object and what have you. I don't like the old Java File API very much. It's almost admirable how overengineered it is while still requiring you to read one character at a time like you would in C. Luckily, there's a lot of convenience methods in java.nio.

Thanks for the responses, guys!

I'm pretty new to Java so I don't really know this stuff all that well.
 

iapetus

Scary Euro Man
Need a little guidance from people who are more book-smart in CS... bf might apply for a position that is said to have interviews heavy on data structure and algorithms. What does that entail? Coming from an electrical engineering background, he's not sure whether he really learned much of that.

Is it Google by any chance? I know they tend to be big on those areas - and rigorous enough that you can't really cram or fake it...
 

Zoe

Member
Is it Google by any chance? I know they tend to be big on those areas - and rigorous enough that you can't really cram or fake it...
Nah, it's a place headquartered in Austin. Tokkun's post kind of scared him off, but apparently we know someone else who works there who will send some sample questions.
 

Godslay

Banned
Nah, it's a place headquartered in Austin. Tokkun's post kind of scared him off, but apparently we know someone else who works there who will send some sample questions.

Tokkun's stuff is pretty run of the mill if you've spent some time with ds &algos. What is even more fun is implementing them in front of interviewer on a white board. Stuff of nightmares literally.
 

tokkun

Member
Nah, it's a place headquartered in Austin. Tokkun's post kind of scared him off, but apparently we know someone else who works there who will send some sample questions.

My intention was not to scare him off, but rather to motivate him to spend a little time studying before the interview as I did.

In my personal opinion, this stuff is easier than what you need to do to get an EE degree. That said, it is a different body of knowledge with its own terminology and paradigms, and you can't expect to be able to do it all intuitively without any study.

Fact is, a lot of the people I knew who were hardware guys have gone through this process of accumulating more CS-related knowledge for the job market. Software Engineering is simply one of the best job markets to be in these days, so it's worth investing in some extra education, even if he doesn't end up getting this specific job.
 

Meier

Member
Not sure if this is the right thread to ask this or not, but I'm using an htaccess to forward to a new URL for a website at my work. I used a generator for the code and it works great for ensuring people go to the new page but it is also preventing me from hotlinking to an image at the old URL. Is there a way to ONLY redirect when someone goes to a particular URL?
 

diaspora

Member
So... I need a hand with C++ again since I don't know what I'm doing.

VS2012 is telling me that the bolded is undefined. How do I make those if statements call the functions in the class?

Code:
#include<iostream>
#include<string>

using namespace std;

class utility
{
	float K, P;

	public:
	utility(float *K, float *P);
	float KtoP();
	float PtoK();
};

float utility::KtoP()
{
	cout << "Enter mass in kg: ";
	cin >> K;
	cout << endl;

	P = K*2.205;
	return P;
}

float utility::PtoK()
{
	cout << "Enter mass in pounds: ";
	cin >> P;
	cout << endl;

	K = P/2.205;
	return K;
}

int main()
{
	int choice;
	{
		cout << "Press 1 to convert from lbs to kg or press 2 to convert from kg to lbs: ";
		cin >> choice;

		if(choice == 1)
		{
			[B]PtoK();[/B]
		}
		else if(choice == 2)
		{
			[B]KtoP();[/B]
		}
	}
	return 0;
}
 
Gotta declare a class object. Each function is only apart of the class and are undefined elsewhere so you need to call it [object].[function()]

Also it won't do what you want. It'll calculate it but you don't have any way of accessing the values of K or P when the function returns.

And get rid of the brackets after int choice. Your main should look like this

Code:
int main()
{
	int choice;
        [class] [declaration]
	cout << "Press 1 to convert from lbs to kg or press 2 to convert from kg to lbs: ";
	cin >> choice;

	if(choice == 1)
	{
		PtoK();
	}
	else if(choice == 2)
	{
		KtoP();
	}
	return 0;
}
 

diaspora

Member
Amazing, that's... quite a bit more elegant than the changes I made to fix it.

Code:
#include<iostream>
#include<string>

using namespace std;

class utility
{
	public:
	static float KtoP(void)
	{
		float K, P;
		
		cout << "Enter mass in kg: ";
		cin >> K;
		cout << endl;

		P = K*2.205;
		cout << K << " kg is " << P << " lbs" << endl;
		return P;
	}
	
	static float PtoK(void)
	{
		float K, P;
		
		cout << "Enter mass in pounds: ";
		cin >> P;
		cout << endl;

		K = P/2.205;
		cout << P << " lbs is " << K << " kg" << endl;
		return K;
	}
};

/* int main()
{
	cout << "Convert Kilograms to pounds?";

	utility::KtoP();
	utility::PtoK();
}
*/
int main()
{
	int choice;
	for(;;)
	{
		cout << "Press 1 to convert kg to lbs or press 2 to convert lbs to kg, or anything else to exit: ";
		cin >> choice;

		if(choice == 1)
		{
			utility::KtoP();
		}
		else if(choice == 2)
		{
			utility::PtoK();
		}
		else
		{
			break;
		}
	}
	return 0;
}
 

usea

Member
Not sure if this is the right thread to ask this or not, but I'm using an htaccess to forward to a new URL for a website at my work. I used a generator for the code and it works great for ensuring people go to the new page but it is also preventing me from hotlinking to an image at the old URL. Is there a way to ONLY redirect when someone goes to a particular URL?
I don't know htaccess stuff (apache mod rewrite thingamajig?) but I think you can find some good info by googling: htaccess redirect specific url

I don't know enough about your circumstances to recommend a specific result. Like, whether you want a 301 redirect, whether you need parameters to go also, etc. I recommend checking stackoverflow results over others, but that's not always the case.

BTW this post is not meant to be condescending. This is literally how I solve problems at my job in an area I have very little knowledge in.
 
A couple of things:

-You don't need string library since you aren't doing anything with strings (except outputing some text but you don't need the library)
-Why the for loop? How many times are you needing to run it? As it stands right now, it will run forever.

So for example your class could be cut down to this:

Code:
class Utility
{
    public:
        float mass
        float KtoP()
        {
             //enter your output text and get mass,
             mass = mass * 2.205;
            //return mass or print out the result;
         }
         float PtoK()
         {
              //insert your code for this one
              //return mass or print out the result;
          }
};

(You can just take a single variable, manipulate it, and save it as the same variable and that will be completely legal. The computer will read as: 2.205 * mass = mass. You take the original value and multiply it by the 2.205, and save it. It's really convenient and saves space if you're dealing with a lot of variables and it's easier to manage if you're always saving things to their original name instead of jumping to a new variable every time you want to do some manipulation)

With me so far? So if you are intent on returning the value then what you're doing is returning to MAIN with the value you just calculated. Think of it like an algebraic function: f(x) = [some equation or some logic you do] but the computer can't do anything if you just leave it like that. So either declare a float variable to receive the return value (value = function();) or just print it out directly (cout << function();)

Now what I want you to do is throw out everything you have in main. Start over. You have the right idea to begin with though: Get a choice from the user and then use that choice to decide which function to call. Great. Let's start with that. Now when you go to call the functions like your previous example, the compiler will return an undefined for each function call. Why? Because they are apart of the class Utility, and only apart of the class. They will not be visible anywhere else, so according to the compiler they don't exist outside of Utility. So how do we fix that? By creating a Utility class object. That object will "see" the functions and allow you to interact with them. These objects are created just like normal variables, like integers, floats, doubles, etc. but instead of those, you declare it with your class name, in this case, your class Utility: Utility [utility variable name] is how you declare that.

So lets see what main looks like now:

Code:
int main()
{
	int choice;
        Utility [name]
	//get input here

	if (choice == 1)
	{
		//call function
	}
	else if(choice == 2)
	{
		//call other function
	}
	else
	{
		//check for any invalid input and do whatever you want
	}
	return 0;
}

Instead of [name] just call it whatever you want. Great! So how do we call the functions? Remember they are only visible to the Utility class, and ONLY the utility class, so you need to access them through the class. How do we do that? Using dot notation. You should have your Class object(variable) already declared. In that object is a link to everything associated with that class (class variables, class functions etc). That's how you interface with the class outside of it.

In order to do that, you must use your object dot whatever you want to access. So in your case: object.function() which is saying "I want to use my class object to access class item function().

So with your Utility class:

Code:
object.KtoP();

or

Code:
object.PtoK();
 

tokkun

Member
Why would you want to create a Utility object?

The original static class approach seems better to me. Functions in a utility namespace would be my choice, though.
 
Why would you want to create a Utility object?

The original static class approach seems better to me. Functions in a utility namespace would be my choice, though.

I was going by his original example and expanding on my original post. I figured I'd explain why he was close to being correct and why he kept getting errors he was getting with his original code.

But yeah that would probably best.
 

Godslay

Banned

Milchjon

Member
I read through this at some point awhile back, good book not specific to a vendor. It is a tome though. Relatively cheap too, I'd say good for beginners.

http://www.amazon.com/Database-Design-Mere-Mortals-Relational/dp/0321884493/ref=sr_1_1?ie=UTF8&qid=1381844628&sr=8-1&keywords=database+design+for+mere+mortals

Also if you have Safari Books Online, it's available there as well.

Thanks, my university's library actually carries that. I'll check it out.

Not sure I have the time and drive for 700 pages though :-D
 
Anyone mind helping me with something admittedly simple yet I'm still having trouble with it? Have to call methods from another class to calculate areas for a triangle, circle, and rectangle after I ask for it in the other class (have that part written out already). I'm just having trouble with calling those methods into the other class that prints out the areas. Do I have to have them in the same package? I'm not entirely sure since the assignment says "Next, write a driver program titled "YourLastName_Driver" to test the geometry class", so I'm not sure if they're supposed to be in separate packages or not.

Any help with this would be much appreciated, thanks! :)
 
Anyone mind helping me with something admittedly simple yet I'm still having trouble with it? Have to call methods from another class to calculate areas for a triangle, circle, and rectangle after I ask for it in the other class (have that part written out already). I'm just having trouble with calling those methods into the other class that prints out the areas. Do I have to have them in the same package? I'm not entirely sure since the assignment says "Next, write a driver program titled "YourLastName_Driver" to test the geometry class", so I'm not sure if they're supposed to be in separate packages or not.

Any help with this would be much appreciated, thanks! :)

Since you mention packages, I assume Java? I'm not entirely sure I understand your question. Let me see if this is what you're doing:

Class A - Contains methods for calculating areas
Class B - Does something else, but depends on the methods in Class A

Does Class B contain an object of type A? What specific problems are you running into? A sample of your code and any errors you're getting would be helpful.

To call methods from Class A from within an object of type B, Class B would need to contain an object of type A. I don't know much Java, but in C++ it would be something like this:

Code:
class A {
  public:
     // Methods for your calculations
    int calc_rect(int rect) {
        // Calc the value of a rectangle
    }
};

class B {
  public:
     A *aInstance = new A();  
};

int doThings() {
    // Somewhere you've defined an object called "rect" with dimensions for a rectange
    B *bInstance = new B();
    B->aInstance->calc_rect(rect);
}

However, I'm not entirely sure what you are doing, and what the problems are, so that might not be helpful.


Also, hello Programming-GAF! First time in this thread, but have been programming for some time. Good fun it is.
 
Since you mention packages, I assume Java? I'm not entirely sure I understand your question. Let me see if this is what you're doing:

Class A - Contains methods for calculating areas
Class B - Does something else, but depends on the methods in Class A

Does Class B contain an object of type A? What specific problems are you running into? A sample of your code and any errors you're getting would be helpful.

To call methods from Class A from within an object of type B, Class B would need to contain an object of type A. I don't know much Java, but in C++ it would be something like this:

Code:
class A {
  public:
     // Methods for your calculations
    int calc_rect(int rect) {
        // Calc the value of a rectangle
    }
};

class B {
  public:
     A *aInstance = new A();  
};

int doThings() {
    // Somewhere you've defined an object called "rect" with dimensions for a rectange
    B *bInstance = new B();
    B->aInstance->calc_rect(rect);
}

However, I'm not entirely sure what you are doing, and what the problems are, so that might not be helpful.


Also, hello Programming-GAF! First time in this thread, but have been programming for some time. Good fun it is.

Yup, this is in Java.

And sorry about the vagueness of my question >.< Trying to find the best way to describe it and I'm not good at it, lol.

I'll quote a few pieces from both my classes to show what I'm doing/what I need:

Class A:

public static double Circle(double radius, double areaCircle) {

radius = radius;

areaCircle = Math.PI * radius * radius;

return areaCircle;
}

Class B:

public static void main(String[] args) {

int input;

Scanner keyboard = new Scanner(System.in);

System.out.println("Geometry Calculator");
System.out.println("1. Calculate the Area of a Circle");
System.out.println("2. Calculate the Area of a Rectangle");
System.out.println("3. Calculate the Area of a Triangle");
System.out.println("4. Exit\n");
System.out.println("Enter your choice (1-4):");

input = keyboard.nextInt();

switch (input) {

case 1:
System.out.println("Enter the radius of the circle: ");
input = keyboard.nextInt();
if(input < 0) {
System.out.println("Please enter a positive number.");
} else {
System.out.println("The area of the circle is: " + );
break;
}

Just included the parts for the circle, I'm missing some point where I just need to call that Circle method from the first class so it can print the area, and that's just what I'm missing.
 
Yup, this is in Java.

And sorry about the vagueness of my question >.< Trying to find the best way to describe it and I'm not good at it, lol.

No worries, the more you ask questions about programming the better you get at it. =)

I'll quote a few pieces from both my classes to show what I'm doing/what I need:

Just included the parts for the circle, I'm missing some point where I just need to call that Circle method from the first class so it can print the area, and that's just what I'm missing.

Is your "Circle" function actually within a class, or is it just on its own? If it's just out on its own, you just need to call that function with the input you're getting from the user. Also, I think your parameter list is a bit off. You're asking for a variable called "areaCircle", but that's the value you're returning not what you're asking for.

Code:
// Should only need one parameter
public static double Circle(double radius) {
    // Code
}


Anyway, you should be able to just call that function with the input you received:

Code:
double area = Circle(input);
System.out.println("The area of the circle is: " + area);

If it actually IS inside of a class, you need to be instantiating an object of that type within main before you can call the method on that object. (main isn't a class, BTW, just your main method. [Okay, everything in Java is technically an object, but main isn't part of any class that you define.])

From what I can see though, I'm thinking that your "Circle" function isn't inside of a class. So you should be able to call it with just "Circle(radius)".

(BTW, when posting code online for help, it's good practice if you indent the code so that it's easier for others to read.)

I think you may be a tad confused on what a class is. If you haven't gone over object oriented programming yet, then you shouldn't have to worry about classes at this point. I would just refer to both of those as functions.

EDIT: Something like this should do the trick:

Code:
// Calling it "circle" instead of "Circle" - classes are generally defined with capital letters, and functions with lowercase
public static double circle(double radius) {
    return Math.PI * radius * radius; // You can calculate and return the value on one line
}


public static void main(String[] args) {
     // Snip - your code for getting user input here

    switch (input) {
        case 1:
            System.out.println("Enter the radius of the circle: ");
            input = keyboard.nextInt();
            if(input < 0) {
                System.out.println("Please enter a positive number.");
            } else {
                double area = circle(input); // <---- This is where you're getting the area
                System.out.println("The area of the circle is: " + area);
            }
            break;
   }
   // Whatever other code you have
}
 
No worries, the more you ask questions about programming the better you get at it. =)



Is your "Circle" function actually within a class, or is it just on its own? If it's just out on its own, you just need to call that function with the input you're getting from the user. Also, I think your parameter list is a bit off. You're asking for a variable called "areaCircle", but that's the value you're returning not what you're asking for.

Code:
// Should only need one parameter
public static double Circle(double radius) {
    // Code
}


Anyway, you should be able to just call that function with the input you received:

Code:
double area = Circle(input);
System.out.println("The area of the circle is: " + area);

If it actually IS inside of a class, you need to be instantiating an object of that type within main before you can call the method on that object. (main isn't a class, BTW, just your main method. [Okay, everything in Java is technically an object, but main isn't part of any class that you define.])

From what I can see though, I'm thinking that your "Circle" function isn't inside of a class. So you should be able to call it with just "Circle(radius)".

(BTW, when posting code online for help, it's good practice if you indent the code so that it's easier for others to read.)

I think you may be a tad confused on what a class is. If you haven't gone over object oriented programming yet, then you shouldn't have to worry about classes at this point. I would just refer to both of those as functions.

Circle is a method within a class called Geometry. The second class, Class B, is the Driver class as its called.

"You're asking for a variable called "areaCircle", but that's the value you're returning not what you're asking for."

I'm not 100% sure what you're asking here if you could elaborate a bit? If I get rid of areaCircle in my method creation it returns errors... Fake edit: Never mind, Netbeans gave me a suggestion that worked >.>

And yeah, the Circle method is just a method in Class A, not the whole of Class A or anything.

Is that second code you put what I should use that'll get my program to work/print?

Also, apologies for the lack of indentation, should've done it but I goofed up as is obvious >.>

Thanks for the help by the way!
 
Circle is a method within a class called Geometry. The second class, Class B, is the Driver class as its called.

Okay, gotcha, sorry for my misunderstanding.

I'm not 100% sure what you're asking here if you could elaborate a bit? If I get rid of areaCircle in my method creation it returns errors... Fake edit: Never mind, Netbeans gave me a suggestion that worked >.>

You were probably getting the area because you were using a variable called "areaCircle" within that method that you were only first declaring as a double in the parameter list. You would want to take out "areaCircle" from the parameters, and declare it as "double areaCircle" in the actual method (or use the one liner I posted above).

And yeah, the Circle method is just a method in Class A, not the whole of Class A or anything.

Is that second code you put what I should use that'll get my program to work/print?

Since Circle is a member method of "Geometry" you need to instantiate a "Geometry" object first. Has that already been done somewhere else in the code? If not, something like this should do it:

Code:
myGeometry = new Geometry(); // If Geometry has parameters, pass them in here

// Then later, call your circle method like this:
double area = myGeometry.Circle(input);

I hope that makes sense.
 
Okay, gotcha, sorry for my misunderstanding.



You were probably getting the area because you were using a variable called "areaCircle" within that method that you were only first declaring as a double in the parameter list. You would want to take out "areaCircle" from the parameters, and declare it as "double areaCircle" in the actual method (or use the one liner I posted above).



Since Circle is a member method of "Geometry" you need to instantiate a "Geometry" object first. Has that already been done somewhere else in the code? If not, something like this should do it:

Code:
myGeometry = new Geometry(); // If Geometry has parameters, pass them in here

// Then later, call your circle method like this:
double area = myGeometry.Circle(input);

I hope that makes sense.

Yeah, that was what I ended up changing just then in Netbeans.

As for instantiating a Geometry object, I did:

myGeometry = new Geometry(double Circle, double Rectangle, double Triangle)

and I get an error saying it can't find the symbol... so I'm probably doing it wrong, I'm guessing? I'm putting that in before the main method, if that makes any difference.
 
Yeah, that was what I ended up changing just then in Netbeans.

As for instantiating a Geometry object, I did:

myGeometry = new Geometry(double Circle, double Rectangle, double Triangle)

and I get an error saying it can't find the symbol... so I'm probably doing it wrong, I'm guessing? I'm putting that in before the main method, if that makes any difference.

Does your Geometry class take parameters? You're passing in an undefined Circle, Rectangle, and Triangle to it when creating myGeometry. If I'm guessing right, I'm pretty sure you just need to do this:

Code:
myGeometry = new Geometry();

...but that depends on what Geometry is looking for. Could you post your Geometry constructor? (Should be what looks like a method within the Geometry class, but has the name "Geometry", and no return value. If that doesn't exist, it should definitely be what I posted above.)

Also, it's hard for me to know exactly what things should be without seeing all the code, but I'm guessing you'll want to instantiate your myGeometry object WITHIN main.
 
Does your Geometry class take parameters? You're passing in an undefined Circle, Rectangle, and Triangle to it when creating myGeometry. If I'm guessing right, I'm pretty sure you just need to do this:

Code:
myGeometry = new Geometry();

...but that depends on what Geometry is looking for. Could you post your Geometry constructor? (Should be what looks like a method within the Geometry class, but has the name "Geometry", and no return value. If that doesn't exist, it should definitely be what I posted above.)

Also, it's hard for me to know exactly what things should be without seeing all the code, but I'm guessing you'll want to instantiate your myGeometry object WITHIN main.

Ok, according to a friend, apparently I had to put them both in one package... which is apparently where most of my issues are coming from... I'm going to test that out and something she used to see if that works before trying this out. Thanks for the help! And sorry about potentially wasting your time, didn't know we had to do this for this assignment >.<
 
Ok, according to a friend, apparently I had to put them both in one package... which is apparently where most of my issues are coming from... I'm going to test that out and something she used to see if that works before trying this out. Thanks for the help! And sorry about potentially wasting your time, didn't know we had to do this for this assignment >.<

No worries, good luck with it! I haven't programmed much in Java at all, so sorry for not thinking of the package thing.
 
Top Bottom