ForumsProgramming ForumJava Shenanigans

28 13676
snowguy13
offline
snowguy13
2,159 posts
Nomad

Whoo! I finally deem myself worthy of posting here!

I've been messing around with Java--yeah, it's not ActionScript, sorry--and I want to share my random creations here, and collaborate with others who love programming!
=====================================================================
First, to kick things off, here's a random program I wrote that converts base-ten integers to hexadecimal format!

This is the first class that creates an object. The object created has a method that allow it to be converted.

/**
* This class will eventually be able to
* convert among hexadecimal, binary,
* base-ten, and possibly systems with
* other bases.
*/

import java.lang.*;

public class Converter
{

String[] hexValues = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"};

long baseTenValue;

long helper;

String hexadecimal = "";

public Converter(long bTenVal)
{

baseTenValue = bTenVal;

}

public Converter()
{
}

public void setNumber(long num)
{

baseTenValue = num;

}

public String toHexadecimal()
{

hexadecimal = "";

final int STARTING_POWER = 100;

byte[] numericalPlaceValue = new byte[STARTING_POWER + 1];

String[] stringPlaceValue = new String[STARTING_POWER + 1];

helper = baseTenValue;

int p;

//Find what numerical values should go in each place (hexadecimal goes up to 15)

for(p = STARTING_POWER; p >= 0; p--) {

numericalPlaceValue[p] = (byte)(helper / (Math.pow(16, p)));
helper -= numericalPlaceValue[p] * (Math.pow(16, p));

}

//Convert the values from above into strings, and to letters if necessary (ie, 15 -> F)

for(p = STARTING_POWER; p >= 0; p--) {

stringPlaceValue[p] = hexValues[numericalPlaceValue[p]];

}

//Combine the values from above into one long string, which is the hexadecimal value

for(p = STARTING_POWER; p >= 0; p--) {

hexadecimal += stringPlaceValue[p];

}

//Cut off any zeros that precede the first value

while(hexadecimal.charAt(0) == '0' {

hexadecimal = hexadecimal.substring(1);

}

return hexadecimal;
}
}

----------

This class uses the class above by creating an instance, and then converting that instance. It also asks if another number should be converted, after converting and displaying the first one.
import javax.swing.JOptionPane;

public class ToHexTest
{

public static void main(String[] args)
{

Converter test = new Converter();

long number;

String help;

byte choice = 0;

while(choice == 0) {

help = JOptionPane.showInputDialog(
null,
"Input an integer to convert to hexadecimal format.",
"What to convert?",
JOptionPane.QUESTION_MESSAGE);

number = Long.parseLong(help);

test.setNumber(number);

JOptionPane.showMessageDialog(
null,
"Your number, " + number + ", in hexadecimal format is " + test.toHexadecimal() + ".",
"Result",
JOptionPane.INFORMATION_MESSAGE);

choice = (byte)JOptionPane.showConfirmDialog(
null,
"Evaulate another number?",
"Continue?",
JOptionPane.YES_NO_OPTION);
}
}
}

=====================================================================
I'd like to know what others think!
  • 28 Replies
snowguy13
offline
snowguy13
2,159 posts
Nomad

Oh, whoops; forgot to ask: when you say...

it would, probably be wise to overload the method

...do you mean create multiple methods with the same name that do the same thing except they accept different data types? So, for example:
public static String toHex(long helper){
/*Put code here*/
}

public static String toHex(int helper){
/*Put same code here*/
}

public static String toHex(short helper){
/*Put same code here*/
}

public static String toHex(byte helper){
/*Put same code here*/
}


And then for the empty argument exception:

public static String toHex(){
return null;
}
Graellic
offline
Graellic
4 posts
Jester

Exactly

Graellic
offline
Graellic
4 posts
Jester

Oh, regarding that (sorry, didn't think to add this until after I posted the "Exactly&quot, you do not need to duplicate the code (i.e. where you typed "Put same code here&quot

Instead try:

public static String toHex(long helper){
** Put code here to convert an long to hex **}

Then, put code in overloaded methods to call the method for converting from a long and send it the argument cast as a long **

As an example:
public static String toHex(byte helper){
return toHex( (long)helper&0xFF );
}

public static String toHex(int helper){
return toHex( helper );
} **Note that an int should not need a cast as it should promote automatically, it's demoting that is usually an issue.

And so on. This way you're only doing the work in one method and just using the overloaded methods to convert to that data type. Of course, you'll need to decide which data types are actually in the scope of your methods (i.e. do you really need to be able to convert floats, longs, doubles, etc.?)

snowguy13
offline
snowguy13
2,159 posts
Nomad

@Graellic

Now that I think about it, I should actually only have to make one method. I do not intend to convert doubles, as I do not plan to devote any time attempting to understand hexadecimal-decimals (heh, decimal-decimals); and bytes, shorts, and ints are all within the range of long (therefore I shouldn't have to convert anything).

What I mean is that in Java, this code is acceptable:

int number;
long otherNumber;

otherNumber = number;


Because long has a wider range than int, there is no error storing an int in a long variable.
Graellic
offline
Graellic
4 posts
Jester

That is correct so that you understand you may receive a &quotossible loss of precision" error or possibly some other error (e.g. some type of data overflow) with, using your example:

number = otherNumber;

since you are demoting this way and promoting in your example. However, with your final input being String, I don't know of any reason that you would ever need to demote.

The only reason I would, possibly, overload the method would be if you were to have a generic "utility" class of your own design that you import regularly for some of your more favorite functions. Then, the next time you're need to take something to hex, you may be wanting to come from another data type. Of course, this is up to your individual programming style and, truthfully, would probably apply more to some other type of function that may have a wider incoming selection of variables. For example, a data reading class accepting a File as an argument that brings in any data type and converts it to ASCII, etc.

For this, though, it sounds like you've got it worked out.

lol. I'm now up to 4 posts on these forums... all in this thread.

snowguy13
offline
snowguy13
2,159 posts
Nomad

@Graellic

Yeah! Thanks for your help!

I just realized that my code from before:

int number;
long otherNumber;

otherNumber = number;


would result in an error because number has not yet been initialized. xD I can picture the error now:

"variable 'number' may not have been initialized"


:P

=====================================================================

In other news, I have about four more player actions to program into my game, and then it's on to the enemy's intelligence! > I finally made it to the fun part!
snowguy13
offline
snowguy13
2,159 posts
Nomad

I have one more player action left to program, and then I can begin working on the enemy's intelligence. This is where things will get tricky (but very fun).

How I think I want to go through with this is by first making a list of what is most important to the enemy's survival (ie, first check if health is low and attempt to counteract that). Also, I have considered adding natures for enemies; ie, aggressive (will attack more) or wise (will heal before other actions).

Does anyone have any thoughts or suggestions?

snowguy13
offline
snowguy13
2,159 posts
Nomad

Hmm... Now that I think about this, I could have the enemy's intelligence keep track of the average damage it receives each turn, the average damage its physical attacks do, the average damage its magical attacks do, the number of times the player raise his/her stats, the number of times the player lowers the enemy stats, etc.

I could use things like that to get the enemy to actually, in a way, *think* about what it should be doing. For example, if the player attacks a lot (average damage taken per turn would be higher), I could make the enemy adopt a more aggressive strategy, or perhaps a more healing-based one as well.

Again, does anyone have any suggestions (especially if you want to offer a suggestion for an if-statement hierarchy)?

snowguy13
offline
snowguy13
2,159 posts
Nomad

I think I'm going to take a break from the battle game for now; my interest seems to have bottomed-out for now...

So, instead, I'm going to learn more about Java GUI's; including JFrames, JPanels, JButtons, etc.

However, just now (literally five minutes ago), I had an idea to try a one-directional motion simulator involving hills. What I mean is to simulate where an object will be over time on a straight track that may contain hills (so it would only deal with one direction of motion, but varying speeds). I have an idea to start this, using a slope field map and my recently groomed understanding of acceleration and motion.

snowguy13
offline
snowguy13
2,159 posts
Nomad

I just created this pretty awesome math class! It finds the factors and prime factorization of two numbers, and their greatest common factor and least common multiple!

The code for it is here!

I'm reeeeaaallly excited about this!

Smokeshow
offline
Smokeshow
69 posts
Peasant

I dont understand nothing :O

snowguy13
offline
snowguy13
2,159 posts
Nomad

I dont understand nothing :O

Of the code I linked to above? If you want an explanation, you can copy and paste a part of it into a post (please not all of it at once; that's a lot of code), and I'll explain it.
snowguy13
offline
snowguy13
2,159 posts
Nomad

I haven't posted here in quite a while! :P

But now I'm working on a large project that is (so far) coming along quite nicely!

I'm creating a tournament manager for the NCAA March Madness prediction tournament my family does (mostly everyone creates his/her own "bracket" predicting who will win, and a correct prediction of a game gets that person points; person with most points at end wins pool of money).

Right now I've created part of the main GUI, the new tournament GUI, and some other objects. The program also creates its own data files and reads them (right now just for simple settings like asking the user if he/she really wants to exit when he/she clicks "Exit", and the last open tournament).

So my task at the moment is finishing some object programming so that I can make a tournament object. This object will display the bracket and manage most of the tournament.

I'm so excited with how much progress I'm making!!!

Showing 16-28 of 28