Omnimaga

General Discussion => Technology and Development => Computer Programming => Topic started by: Yeong on December 09, 2010, 09:42:30 pm

Title: Random simple java programs that actually do something useful.
Post by: Yeong on December 09, 2010, 09:42:30 pm
I made it for my homework. You have to compile it first.
You type the sentence and it converts the sentence into piglatin!
Code: [Select]

import java.util.*;
import java.lang.*;
public class Prog508a
{
    public static Scanner k=new Scanner(System.in);
    public static int yesorno=1;
    public static String YN="";
    public static int yncheck(String YesOrNo)
    {
        if(YN.equals("Yes"))
         yesorno=1;
        else if(YN.equals("No"))
         yesorno=0;
       
        else if( !(YN.equals("Yes") || YN.equals("No")) && (YN.equalsIgnoreCase("yes") || YN.equalsIgnoreCase("no")))
        {
            System.out.print("Capitalization is important Yes or No? ");
            YN=k.nextLine();
            yncheck(YN);
        }
        else
        {System.out.print("You must answer either Yes or No? ");
            YN=k.nextLine();
            yncheck(YN);
        }
        return yesorno;
    }
      public static void main(String args[])
    {       
        String str="",str2="",str3="";
        while(yesorno==1){
        System.out.println();
        System.out.print("Enter a sentence: ");
        str=k.nextLine();
        String[] sarray = str.split(" ");
        int len = sarray.length;
        for(int i=0;i<len;i++)
        {
            char[] word = sarray[i].toCharArray();
            char firstletter = word[0];
            int len3=word.length;
            int len4=len3-1;
            if(firstletter!='a' && firstletter!='e' && firstletter!='i' && firstletter!='o' && firstletter!='u' && firstletter!='A' && firstletter!='E' && firstletter!='I' && firstletter!='O' && firstletter!='U')
            {
                for(int j=0;j<=len4-1;j++)
                {
                    word[j]=word[j+1];
                }
                word[len3-1]=firstletter;
            }           
            for(int l=0;l<=len3-1;l++)
            {
                str2=str2+word[l];
            }
            str3=str3+str2+" ";
            str2="";
        }       
        str3=str3.replace(" ","ay ");
        System.out.println(str3);
        str3="";
        System.out.print("Do you wish to convert another sentence? (Yes/No) ");
        YN=k.nextLine();
        yncheck(YN);   
       }
    }
}

 */
Optimizing comments thnx
Title: Re: java piglatin converter?
Post by: nemo on December 09, 2010, 09:57:47 pm
interesting. you know what i just thought of doing? censoring a string to take out all the swear words

edit: just finished it. it will change something like this:
Spoiler For language:
You fucking ass.
into
You endearing unicorn.

Code: [Select]
import java.util.*;

public class Censor{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter a string to censor: ");
String evilness = reader.nextLine();
System.out.println("Your string in a more holy format: \n" + censor(evilness));
System.out.print("\nAgain? (y/n) ");
if(reader.nextLine().equalsIgnoreCase("y"))
main(null);                                    //recursive calls to main? i think yes.
}

public static String censor(String evilness){
String[] badWords = {"fuck","shit","damn","ass","FUCK","SHIT","DAMN","ASS"}; //yes, i know there are more swear words. this covers the basics.
String[] replacementWords = {"apple","magical","unicorn","fairies","endear","renowned","butterflies","sugar"};
Random r = new Random();
for(int i = 0; i < badWords.length; i++){
int indexOfBadWord = evilness.indexOf(badWords[i]);
if(indexOfBadWord != -1){
String begin = evilness.substring(0,indexOfBadWord);
String replacement = replacementWords[r.nextInt(replacementWords.length)];
String end = evilness.substring(indexOfBadWord + badWords[i].length());
evilness = begin + replacement + end;
i = -1;
}
}
return evilness;      //now holy.
}
}
Title: Re: java piglatin converter?
Post by: Yeong on December 09, 2010, 10:14:01 pm
woot :w00t:
Spoiler For Spoiler:
you butterfliesing butterflies
Title: Re: Random simple java programs that actually do something useful.
Post by: jnesselr on December 09, 2010, 10:24:57 pm
Lol, "apple this magical unicorn". Interesting program, nemo. I love the comment on that return statement.

EDIT: What would be really funny, is to analyze the sentence, and get a new version that was "prettier" so that everyone talked pretty.

So "Hey, I think your program is a fail" becomes "I think your program is missing some butterflies, but other than that, I think the unicorns were happy."
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 09, 2010, 10:44:52 pm
Lol, "apple this magical unicorn". Interesting program, nemo. I love the comment on that return statement.

EDIT: What would be really funny, is to analyze the sentence, and get a new version that was "prettier" so that everyone talked pretty.

So "Hey, I think your program is a fail" becomes "I think your program is missing some butterflies, but other than that, I think the unicorns were happy."

i think that's a little beyond my word processing abilities. it'd be cool if i made an advanced library to process strings, though.

also, if you want, you can just copy/paste my source code and add words. if you want to add the swear words list to include "snow" for some reason, you can do that. you can also add replacement words, if you wanted to replace snow with honey.

 maybe i could make a function that, when a certain word is spotted, it will always replace it with a certain other word...
Title: Re: Random simple java programs that actually do something useful.
Post by: jnesselr on December 09, 2010, 10:51:40 pm
Lol, "apple this magical unicorn". Interesting program, nemo. I love the comment on that return statement.

EDIT: What would be really funny, is to analyze the sentence, and get a new version that was "prettier" so that everyone talked pretty.

So "Hey, I think your program is a fail" becomes "I think your program is missing some butterflies, but other than that, I think the unicorns were happy."

i think that's a little beyond my word processing abilities. it'd be cool if i made an advanced library to process strings, though.

also, if you want, you can just copy/paste my source code and add words. if you want to add the swear words list to include "snow" for some reason, you can do that. you can also add replacement words, if you wanted to replace snow with honey.

 maybe i could make a function that, when a certain word is spotted, it will always replace it with a certain other word...
I'm sure you are referring to replacing Game with Lost, right?
Title: Re: Random simple java programs that actually do something useful.
Post by: Happybobjr on December 09, 2010, 10:56:35 pm
I wouldn't censor the game. When you see anything censored, you will assume and lose the game.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 10, 2010, 02:13:38 am
interesting. you know what i just thought of doing? censoring a string to take out all the swear words

edit: just finished it. it will change something like this:
Spoiler For language:
You fucking ass.
into
You endearing unicorn.

Code: [Select]
import java.util.*;

public class Censor{
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.print("Enter a string to censor: ");
String evilness = reader.nextLine();
System.out.println("Your string in a more holy format: \n" + censor(evilness));
System.out.print("\nAgain? (y/n) ");
if(reader.nextLine().equalsIgnoreCase("y"))
main(null);                                    //recursive calls to main? i think yes.
}

public static String censor(String evilness){
String[] badWords = {"fuck","shit","damn","ass","FUCK","SHIT","DAMN","ASS"}; //yes, i know there are more swear words. this covers the basics.
String[] replacementWords = {"apple","magical","unicorn","fairies","endear","renowned","butterflies","sugar"};
Random r = new Random();
for(int i = 0; i < badWords.length; i++){
int indexOfBadWord = evilness.indexOf(badWords[i]);
if(indexOfBadWord != -1){
String begin = evilness.substring(0,indexOfBadWord);
String replacement = replacementWords[r.nextInt(replacementWords.length)];
String end = evilness.substring(indexOfBadWord + badWords[i].length());
evilness = begin + replacement + end;
i = -1;
}
}
return evilness;      //now holy.
}
}
Haha this is awesome. ;D
Title: Re: Random simple java programs that actually do something useful.
Post by: AngelFish on December 10, 2010, 02:15:29 am
interesting. you know what i just thought of doing? censoring a string to take out all the swear words

edit: just finished it. it will change something like this:
Spoiler For language:
You fucking ass.
into
You endearing unicorn.

Brilliant. IRC should have this so we can fool around with it.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 10, 2010, 02:17:54 am
Not public commands, though. Earlier I had to mute the IRC channel (disable it completely) to stop a spam fest because no one would listen. Imagine with bot commands, now. X.x
Title: Re: Random simple java programs that actually do something useful.
Post by: AngelFish on December 10, 2010, 02:19:05 am
Not public commands, though. Earlier I had to mute the IRC channel (disable it completely) to stop a spam fest because no one would listen. Imagine with bot commands, now. X.x

The quote spamming? I was one of the ones devoiced, DJ :P

It'd still be awesome for us human bots.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 10, 2010, 02:19:50 am
Ah right you were on. But still, I don,t want this to turn into a spam fest. That kind of bot should be kept for other channels.
Title: Re: Random simple java programs that actually do something useful.
Post by: AngelFish on December 10, 2010, 02:20:52 am
Yeah, right before you devoiced everyone I was telling you how I probably wasn't going to release Black for the z80.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 10, 2010, 02:36:08 am
Ah, right. I wish you released the source or something, though, in case someone wanted to take over. :(
Title: Re: Random simple java programs that actually do something useful.
Post by: Builderboy on December 10, 2010, 02:37:36 am
Methinks you might have found String.replace(String original,String replacement) helpful :)
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 10, 2010, 02:39:08 am
I remember some mods we had installed on the old Omnimaga boards were just replacing some code, CSS properties and words using javascript. It was a strange way to do it but it kinda did the job. I guess it was inevitable since Invisionfree did not let us install PHP mods.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 10, 2010, 05:52:42 pm
yeongJIN_COOL's random calc generator
have fun
I got...
Spoiler For Spoiler:
TI-MICROWAVE

Code: [Select]
import java.util.*;
public class randomcalc
{
   public static void main(String args[])
   {
       Random generator = new Random();
       int r = generator.nextInt(20);
       System.out.println("yeongJIN_COOL's random calc gen");
       System.out.println("You get...");//WHAT YOU'RE GONNA GET?
       switch(r)
       {
          case 0: System.out.println("TI-81");break;
          case 1: System.out.println("TI-83+");break;
          case 2: System.out.println("TI-84+");break;
          case 3: System.out.println("TI-83+ SE");break;
          case 4: System.out.println("TI-84+ SE");break;
          case 5: System.out.println("TI-86");break;
          case 6: System.out.println("TI-89");break;
          case 7: System.out.println("TI-89 Titanium");break;
          case 8: System.out.println("TI-92");break;
          case 9: System.out.println("Voyage 200");break;
          case 10: System.out.println("TI-32 stuff");break;
          case 11: System.out.println("f(x)-9750g");break;
          case 12: System.out.println("cf(x)-9750g");break;//AT LEAST, IT HAS COLOR
          case 13: System.out.println("TI-MICROWAVE");break;//ROFL
          case 14: System.out.println("CASIO PRIZM");break;
          case 15: System.out.println("TI-nSPIRE with Clickpad");break;
          case 16: System.out.println("TI-nSPIRE with Touchpad");break;
          case 17: System.out.println("TI-nSPIRE CAS");break;
          case 18: System.out.println("Wabbitemu");break;
          case 19: System.out.println("Nothing");break;//TOO BAD FOR YOU
       }
}
}

Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 10, 2010, 10:27:16 pm
nice, yeong!


next java mini-project i'm working on: linear equation solver (via rref).
done. here's the code, it's fairly obfuscated.... so good luck if you want to understand it.

Code: [Select]
import java.util.Scanner;

public class Solve{
static double[][] matrix;
public static void main(String[] args){
Scanner reader = new Scanner(System.in);
System.out.print("# of variables: ");
int vars = reader.nextInt();
inputValues(vars,vars+1);
for(int col = 0; col < vars; col++){
for(int row = 0; row < vars; row++){
if(row==0)
matrix[col] = rowDiv(matrix[col],matrix[col][col]);
if(row!=col)
matrix[row] = rowAdd(rowDiv(matrix[col],-1/matrix[row][col]),matrix[row]);

}
}
for(int i = 0; i < vars; i++)
System.out.println("xyzuvw".substring(i,i+1) + "= " + Math.round(matrix[i][vars]*1000)/1000.0);

}

public static void inputValues(int rows, int columns){
String equ = "Ax+By+Cz+Du+Ev+Fw".substring(0,rows*3-1) + "=" + "ABCDEFG".substring(rows,rows+1);
matrix = new double[rows][columns];
Scanner reader = new Scanner(System.in);
for(int r = 0; r < rows; r++){
System.out.println("Enter equation " + (r+1) + ": \n" + equ);
for(int c = 0; c < columns; c++){//C++
System.out.print("ABCDEFG".substring(c,c+1)+"= ");
matrix[r][c] = reader.nextInt();
}
System.out.println();
}
}

public static double[] rowDiv(double[] r, double c ){
double[] temp = new double[r.length];
for(int p = 0; p < r.length; p++)
temp[p] = r[p] / c;
return temp;
}

public static double[] rowAdd(double[] i, double[] j){
double[] temp = new double[i.length];
for(int p = 0; p < i.length; p++)
temp[p] = i[p] + j[p];
return temp;
}
}

it can take up to 6 variables, but as far as i know if i modified it a little, it could take an infinite number. it returns numbers to the thousandth decimal place. oh, and it will not tell you if there are no solutions/infinite solutions. it will likely do one of the following things in either of these scenarios:
-tell you that all the variables are 0.
-tell you that all the variables are NaN (not a number)
-tell you that all the variables are either -Infinity or Infinity.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 11, 2010, 01:20:47 am
Lol nice stuff guys XD
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 11, 2010, 11:09:03 am
@nemo: I remember we had to do the linear equation solver 7 weeks ago in APCS.
Looks good! Yours have more feature.
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 11, 2010, 04:29:03 pm
it was fun to make. i don't know what i want to make next though.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 12, 2010, 02:49:39 pm
Port Reuben Quest 1 and 2 to java! ;D
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 12, 2010, 08:10:27 pm
lol that's not simple :P
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:14:17 am
I don't even know how to put graphic on java...
 :(
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 13, 2010, 05:05:41 pm
lol that's not simple :P
Aww, ok then D:
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 05:09:26 pm
I don't even know how to put graphic on java...
 :(

do you want an example program? it isn't too difficult, i could make an overly-commented program where you move a ball around with the arrow keys if you want.

by the way, what IDE do you program in?
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 06:47:29 pm
sure!
I use BlueJ if that's what you're asking
Title: Re: Random simple java programs that actually do something useful.
Post by: FinaleTI on December 13, 2010, 07:14:20 pm
I don't even know how to put graphic on java...
 :(
Me too.
I'd appreciate the example as well.

I'm using BlueJ too, but that's because what my AP Comp Sci class has to use. It really annoys me at times, though it's much less annoying since I figured out the keyboard shortcut for auto-indenting your class.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 07:15:40 pm
I use BlueJ because I AM in APCS
only shortcut I learned in there was ctrl+k, which was compiling
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 07:17:51 pm
i'm in APCS as well, i use JCreator Lite. my teacher got the free version before it started costing money.
i'll have some code up in a sec. do you guys know what a JFrame or JPanel are or should i comment the basic elements too?
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 07:18:38 pm
isn't JPanel and JFrame Applet stuff?
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 07:19:29 pm
isn't JPanel and JFrame Applet stuff?

nope, it's called Swing. it allows you to have little windows on your computer. i think i should give multiple examples....
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 07:20:52 pm
oh
Mah Savitch book gives me a example about those but it was always in the applet section.
Title: Re: Random simple java programs that actually do something useful.
Post by: FinaleTI on December 13, 2010, 07:27:31 pm
Ooh, I didn't know that one.

I like Ctrl+Shift+I, because it auto-indents your code, which can be really helpful sometimes.
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 07:34:16 pm
Code: [Select]
//program: makes an empty window you can move around, minimize. whatever.
import javax.swing.*;

public class Example1{
public static void main(String[] args){
JFrame frame = new JFrame("Omnimaga."); //makes a new window with the title "Omnimaga." in memory.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes it so when you press the red X, the program exits.
frame.setSize(300,400); //300 pixels wide by 400 tall.
frame.setResizable(true); //it's resizable by default, but if you ever want to make it not-resizable, you know how.
frame.setVisible(true); //yay! it's visible!
}
}

example numero one.

Code: [Select]
//program: makes an empty window with a panel, which has a black background.
import javax.swing.*;  //for JPanel, JFrame
import java.awt.*; // for Color, and Container pane

public class Example2{
public static void main(String[] args){
JFrame frame = new JFrame("Omnimaga."); //makes a new window with the title "Omnimaga." in memory.
Container pane = frame.getContentPane(); //this is what organizes buttons, text boxes, panels, etc.
JPanel panel = new JPanel(); //you can draw on this! yay!
panel.setBackground(Color.BLACK); //make the background color black
pane.add(panel); //add it to the panel!
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes it so when you press the red X, the program exits.
frame.setSize(300,400); //300 pixels wide by 400 tall.
frame.setResizable(true); //it's resizable by default, but if you ever want to make it not-resizable, you know how.
frame.setVisible(true); //yay! it's visible!
}
}

example nummer zwei.


3 is on its way. they're starting to get more complex.

Code: [Select]
//program: makes an empty window with a panel. oh, and the panel has a red circle in the center. yay.
import javax.swing.*;  //for JPanel, JFrame
import java.awt.*; // for Color, and Container pane
import java.awt.Graphics; //idk why, but my IDE needs this whenever i use graphics. BlueJ may not.

public class Example3{
public static void main(String[] args){
JFrame frame = new JFrame("Omnimaga."); //makes a new window with the title "Omnimaga." in memory.
Container pane = frame.getContentPane(); //this is what organizes buttons, text boxes, panels, etc.
MagicPanel panel = new MagicPanel(); //you can draw on this! yay!
pane.add(panel); //add it to the panel!
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes it so when you press the red X, the program exits.
frame.setSize(300,400); //300 pixels wide by 400 tall.
frame.setResizable(true); //it's resizable by default, but if you ever want to make it not-resizable, you know how.
frame.setVisible(true); //yay! it's visible!
}
}

class MagicPanel extends JPanel{ //it's like a jpanel... but magic...

public void paintComponent(Graphics g){
g.setColor(Color.BLACK); //everything painted is black
g.fillRect(getX() , getY() , getWidth(), getHeight() );
g.setColor(Color.RED); //everything you paint will be red now.
g.fillOval(getWidth() / 2 ,getHeight() / 2, 50,50);  //oval upper-left X position is the panel's width / 2,
// y position is the panel's height / 2
//width is 50 pixels, and then height is 50 pixels.
}

}
numeri tres! you'll notice that the red circle isn't *completely* in the center of the panel. that's because of the edges of the window. if you're in XP, the extra height is +34 and the extra width is +4.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 07:57:35 pm
@nemo: question: how do i view applet?
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 07:58:02 pm
i don't know. i don't work with applets.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:11:46 pm
modified your example 3 a bit  :)
Code: [Select]
//program: makes an empty window with a panel. oh, and the panel has a red circle in the center. yay.
import javax.swing.*;  //for JPanel, JFrame
import java.awt.*; // for Color, and Container pane
import java.awt.Graphics; //idk why, but my IDE needs this whenever i use graphics. BlueJ may not.

public class Example3{
public static void main(String[] args){
JFrame frame = new JFrame("Omnimaga."); //makes a new window with the title "Omnimaga." in memory.
Container pane = frame.getContentPane(); //this is what organizes buttons, text boxes, panels, etc.
MagicPanel panel = new MagicPanel(); //you can draw on this! yay!
pane.add(panel); //add it to the panel!
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes it so when you press the red X, the program exits.
frame.setSize(500,500); //300 pixels wide by 400 tall.
frame.setResizable(true); //it's resizable by default, but if you ever want to make it not-resizable, you know how.
frame.setVisible(true); //yay! it's visible!
}
}

class MagicPanel extends JPanel{ //it's like a jpanel... but magic...

public void paintComponent(Graphics g){
g.setColor(Color.BLACK); //everything painted is black
g.fillRect(getX() , getY() , getWidth(), getHeight() );
g.setColor(Color.RED); //everything you paint will be red now.
g.drawOval(100,50,200,200);
                         g.fillOval(155,100,10,20);
                         g.fillOval(230,100,10,20);
                          g.drawArc(150,160,100,50,180,180); // Draw smile :)
}

}
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 08:15:26 pm
lol a smilie. nice. here's example four. it's pretty.. badly coded. everything is declared static  <_< i wish main didn't have to be static. it's a very inelegant solution to modifier problem, but the concepts are shown.

Code: [Select]
//program: makes an empty window with a panel. oh, and the panel has a red circle in the center. yay.
import javax.swing.*;  //for JPanel, JFrame
import java.awt.*; // for Color, and Container pane
import java.awt.event.*; //needed for the key movement
import java.awt.Graphics; //idk why, but my IDE needs this whenever i use graphics. BlueJ may not.

public class Example4{
static boolean isMovingLeft = false;
static boolean isMovingRight = false;
static boolean isMovingUp = false;
static boolean isMovingDown = false;
static int x = 0, y = 0;
static Timer t; //for timed events. like every 100 milliseconds do this action
static MagicPanel panel;
public static void main(String[] args){
JFrame frame = new JFrame("Omnimaga."); //makes a new window with the title "Omnimaga." in memory.
Container pane = frame.getContentPane(); //this is what organizes buttons, text boxes, panels, etc.
panel = new MagicPanel(); //you can draw on this! yay!
InputMap i = panel.getInputMap(); //this allows you to define keystrokes the panel should recognize.
ActionMap a = panel.getActionMap(); //this allows you to transfer those keystrokes into actions.
i.put(KeyStroke.getKeyStroke("LEFT"),"move left!"); //maps the pressed key "LEFT" (left arrow key) to the string "move left!"
i.put(KeyStroke.getKeyStroke("RIGHT"),"move right!"); //like above..
i.put(KeyStroke.getKeyStroke("UP"),"move up!");
i.put(KeyStroke.getKeyStroke("DOWN"),"move down!");
i.put(KeyStroke.getKeyStroke("released LEFT"),"stop moving left!"); //maps the released key "LEFT" (left arrow key) to the string "stop moving left!"
i.put(KeyStroke.getKeyStroke("released RIGHT"),"stop moving right!");
i.put(KeyStroke.getKeyStroke("released UP"),"stop moving up!");
i.put(KeyStroke.getKeyStroke("released DOWN"),"stop moving down!");
a.put("move left!",moveLeft); //maps the string in the InputMap "move left!" to the action moveLeft.
a.put("move right!",moveRight);//like above..
a.put("move up!",moveUp);
a.put("move down!",moveDown);
a.put("stop moving left!",stopMovingLeft);
a.put("stop moving right!",stopMovingRight);
a.put("stop moving up!",stopMovingUp);
a.put("stop moving down!",stopMovingDown);
panel.setFocusable(true); //allows the panel to intercept key presses.
pane.add(panel); //add it to the panel!
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes it so when you press the red X, the program exits.
frame.setSize(300,400); //300 pixels wide by 400 tall.
frame.setResizable(true); //it's resizable by default, but if you ever want to make it not-resizable, you know how.
frame.setVisible(true); //yay! it's visible!
t = new Timer(1,update); //do action update every 1 millisecond
t.start(); //start the timer
while(true){
panel.repaint();
}
}

static Action update = new AbstractAction(){ //timer's action
public void actionPerformed(ActionEvent e){
panel.updateCoordinates(x,y);
if(isMovingLeft)
x--;
if(isMovingRight)
x++;
if(isMovingUp)
y--;
if(isMovingDown)
y++;
}
};

static Action moveLeft = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingLeft = true;
}
};
static Action moveRight = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingRight = true;
}
};
static Action moveUp = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingUp = true;
}
};
static Action moveDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingDown = true;
}
};
static Action stopMovingLeft = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingLeft = false;
}
};
static Action stopMovingRight = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingRight = false;
}
};
static Action stopMovingUp = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingUp = false;
}
};
static Action stopMovingDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingDown = false;
}
};

}

class MagicPanel extends JPanel{ //it's like a jpanel... but magic...
private int x,y; //where the circle would be placed

public void updateCoordinates(int xPos, int yPos){
x = xPos;
y = yPos;
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK); //everything painted is black
g.fillRect(getX() , getY() , getWidth(), getHeight() );
g.setColor(Color.RED); //everything you paint will be red now.
g.fillOval(x ,y, 50,50);
}

}
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:16:41 pm
 :w00t:moving circle :w00t:
EDIT: What is the "move left!", "move right!" thingy? is it supposed to display?
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 08:21:25 pm
yeah it was a headache to write  :banghead:

i haven't built the framework for keypresses in so long. i kept having to refer back to my game Juggernaut (http://ourl.ca/8192).
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:22:32 pm
oh it doesn't let you move multiple objects
Yeong had tried to make the same smile move
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 08:23:25 pm
no, they aren't supposed to display. the panel has two instance objects called the InputMap and the ActionMap. the inputmap is basically a bunch of strings that each correspond to a specificy keyStroke. the actionmap reads the inputmap's strings and maps the strings onto a bunch of Action objects, which run that code whenever you press the keyStroke in the inputmap.

and yes it should, if you make the smile's x and y positions be based upon x and y variables.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:25:54 pm
like this?
Code: [Select]
//program: makes an empty window with a panel. oh, and the panel has a red circle in the center. yay.
import javax.swing.*;  //for JPanel, JFrame
import java.awt.*; // for Color, and Container pane
import java.awt.event.*; //needed for the key movement
import java.awt.Graphics; //idk why, but my IDE needs this whenever i use graphics. BlueJ may not.

public class Example4{
static boolean isMovingLeft = false;
static boolean isMovingRight = false;
static boolean isMovingUp = false;
static boolean isMovingDown = false;
static int x = 0, y = 0;
static Timer t; //for timed events. like every 100 milliseconds do this action
static MagicPanel panel;
public static void main(String[] args){
JFrame frame = new JFrame("Omnimaga."); //makes a new window with the title "Omnimaga." in memory.
Container pane = frame.getContentPane(); //this is what organizes buttons, text boxes, panels, etc.
panel = new MagicPanel(); //you can draw on this! yay!
InputMap i = panel.getInputMap(); //this allows you to define keystrokes the panel should recognize.
ActionMap a = panel.getActionMap(); //this allows you to transfer those keystrokes into actions.
i.put(KeyStroke.getKeyStroke("LEFT"),"move left!"); //maps the pressed key "LEFT" (left arrow key) to the string "move left!"
i.put(KeyStroke.getKeyStroke("RIGHT"),"move right!"); //like above..
i.put(KeyStroke.getKeyStroke("UP"),"move up!");
i.put(KeyStroke.getKeyStroke("DOWN"),"move down!");
i.put(KeyStroke.getKeyStroke("released LEFT"),"stop moving left!"); //maps the released key "LEFT" (left arrow key) to the string "stop moving left!"
i.put(KeyStroke.getKeyStroke("released RIGHT"),"stop moving right!");
i.put(KeyStroke.getKeyStroke("released UP"),"stop moving up!");
i.put(KeyStroke.getKeyStroke("released DOWN"),"stop moving down!");
a.put("move left!",moveLeft); //maps the string in the InputMap "move left!" to the action moveLeft.
a.put("move right!",moveRight);//like above..
a.put("move up!",moveUp);
a.put("move down!",moveDown);
a.put("stop moving left!",stopMovingLeft);
a.put("stop moving right!",stopMovingRight);
a.put("stop moving up!",stopMovingUp);
a.put("stop moving down!",stopMovingDown);
panel.setFocusable(true); //allows the panel to intercept key presses.
pane.add(panel); //add it to the panel!
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes it so when you press the red X, the program exits.
frame.setSize(300,400); //300 pixels wide by 400 tall.
frame.setResizable(true); //it's resizable by default, but if you ever want to make it not-resizable, you know how.
frame.setVisible(true); //yay! it's visible!
t = new Timer(1,update); //do action update every 1 millisecond
t.start(); //start the timer
while(true){
panel.repaint();
}
}

static Action update = new AbstractAction(){ //timer's action
public void actionPerformed(ActionEvent e){
panel.updateCoordinates(x,y);
if(isMovingLeft)
x--;
if(isMovingRight)
x++;
if(isMovingUp)
y--;
if(isMovingDown)
y++;
}
};

static Action moveLeft = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingLeft = true;
}
};
static Action moveRight = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingRight = true;
}
};
static Action moveUp = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingUp = true;
}
};
static Action moveDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingDown = true;
}
};
static Action stopMovingLeft = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingLeft = false;
}
};
static Action stopMovingRight = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingRight = false;
}
};
static Action stopMovingUp = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingUp = false;
}
};
static Action stopMovingDown = new AbstractAction(){
public void actionPerformed(ActionEvent e){
isMovingDown = false;
}
};

}

class MagicPanel extends JPanel{ //it's like a jpanel... but magic...
private int x,y; //where the circle would be placed

public void updateCoordinates(int xPos, int yPos){
x = xPos;
y = yPos;
}
public void paintComponent(Graphics g){
g.setColor(Color.BLACK); //everything painted is black
g.fillRect(getX() , getY() , getWidth(), getHeight() );
g.setColor(Color.RED); //everything you paint will be red now.
g.drawOval(x,y,200,200);
g.fillOval(x+55,y+50,10,20);
g.fillOval(x+130,y+50,10,20);
g.drawArc(x+50,y+110,100,50,180,180); // smile :D

}

}
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 08:27:09 pm
yep, that should do the trick.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:32:09 pm
now how do I display text on JPanel?
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 08:34:24 pm
Do you know what the API (http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html) is? in general, they'll give methods for you to do most anything you can do in java. i'm not explaining how and just giving you a link to be rude, it's so that everytime you want to do something new in java, you can look at the API to see if there's a method that does what you want.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 13, 2010, 08:37:46 pm
thank you for the link.
I won't bother you no more.... :D
Spoiler For Spoiler:
bother bother  >:D
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 13, 2010, 08:38:51 pm
lol you aren't bothering me! if you can't find something in the API i'd be glad to help. like if you want to display an image, and then after that you want to rotate it. and after that you want to make a racing game that scrolls. i can help you along there  :)
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 15, 2010, 10:00:28 pm
"encoding" and "decoding" a string. you really aren't... for example, does this look recognizable?
Code: [Select]
{0171,0157,0165,040,0150,0141,0166,0145,040,0154,0157,0163,0164,040,0164,0150,0145,040,0147,0141,0155,0145,056}

i bet this does though:
Code: (translation) [Select]
you have lost the game.

to encode:

Code: [Select]

import java.util.*;

public class Array{

public static void main(String[] args){
Scanner reader = new Scanner(System.in);
String str = reader.nextLine();
String obfuscation = "{";
for(int i = 0; i < str.length(); i++){
obfuscation += "0" + Integer.toOctalString((int)str.charAt(i));
if(i + 1 != str.length())
obfuscation += ",";
}
obfuscation += "}";
System.out.println("encoded: " + obfuscation);
}

}

to decode:
Code: [Select]
public class Array2{

public static void main(String[] args){
int[] ints = <output from first program>;
for(int i: ints)
System.out.print((char)i);
}

}
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 16, 2010, 04:54:51 am
Damnit I lost D:<

Nice code, though.
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 18, 2010, 09:01:41 pm
insult generator! they're actually pretty lame.. i tried.

Code: [Select]
import java.util.*;

public class Insult{
static Random r = new Random();
public static void main(String[] args){
System.out.println(randomStart() + randomAdj() + randomNoun() + "you " + randomPersonAdj() + randomInsult() + ". " + randomEnd());
Scanner reader = new Scanner(System.in);
System.out.println("Want another opinion? (y/n)");
if(reader.nextLine().equalsIgnoreCase("y"))
main(null);
}

public static String randomStart(){
String[] starts = {"What is this ","Why would you leave this ",};
return starts[r.nextInt(2)];
}
public static String randomAdj(){
String[] adj = {"stupid ","blatant ","moronic ","abominable "};
return adj[r.nextInt(4)];
}
public static String randomNoun(){
String[] noun = {"piece of garbage ","filth ","waste "};
return noun[r.nextInt(3)];
}
public static String randomPersonAdj(){
String[] adj = {"deficient ","senseless ","rash ","puerile ","nonsensical ","thick headed ","fat ","pointless ","obtuse "};
return adj[r.nextInt(9)];
}
public static String randomInsult(){
String[] insults = {"crud of the gene pool","failure","waste of breath","imbecile","incompetent monkey"};
return insults[r.nextInt(5)];
}
public static String randomEnd(){
String[] ends = {"Get lost.","Go climb a mountain.","Why don't you leave?","Just stop. Stop it now.","Seriously? Vamoose.","The Game."};
return ends[r.nextInt(6)];
}
}

for example:
Why would you leave this blatant piece of garbage you thick headed failure. Go climb a mountain.
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 18, 2010, 09:41:13 pm
Lol XD
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 19, 2010, 03:43:20 pm
Someone was mentioning JFrame programs, right?

Code: [Select]
import javax.swing.*;

public class HelloWorldSwing
{
public static void main(String args[])
{
JFrame frame = new JFrame("Hello");
JLabel label = new JLabel("Hello, Swing World");
frame.getContentPane().add(label);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

I coded a bit of JFrame yesterday, I'll post a JFrame numbar generator later :)
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 19, 2010, 03:51:10 pm
What's JFrame? Is it a derivative of java or is it a library, like JQuery for JS?
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 19, 2010, 03:53:57 pm
What's JFrame? Is it a derivative of java or is it a library, like JQuery for JS?

It's like wxPython for python :) Or Tkinter for Python :)
Title: Re: Random simple java programs that actually do something useful.
Post by: calcdude84se on December 19, 2010, 03:55:36 pm
JFrame is a standard part of Java and it isn't a library.
It's used to created frames. (Hence its name)
Edit: ninja'd
Title: Re: Random simple java programs that actually do something useful.
Post by: DJ Omnimaga on December 19, 2010, 04:05:28 pm
I see, thanks for the info. :D
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 19, 2010, 04:52:20 pm
The syntax is the same as Java, but it has more functions/commands to help you making GUI :)
Title: Re: Random simple java programs that actually do something useful.
Post by: calcdude84se on December 19, 2010, 05:01:54 pm
Swing is a standard part of Java, actually ;)
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 19, 2010, 05:03:04 pm
you can also use AWT. Java has two GUI packages. Swing generally being preferred over AWT.
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 19, 2010, 06:40:53 pm
you can also use AWT. Java has two GUI packages. Swing generally being preferred over AWT.

I've always used JFrame, so never heard of others.
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 19, 2010, 07:31:50 pm
simple program that allows you to move a square around a 10 x 10 map. it's about 200 lines of code so i didn't post it here. don't be scared though, 60 lines of the 200 are just keyboard action events. you'll need to download the images and put them in the same directory as the source.
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 19, 2010, 07:32:34 pm
simple program that allows you to move a square around a 10 x 10 map. it's about 200 lines of code so i didn't post it here. don't be scared though, 60 lines of the 200 are just keyboard action events. you'll need to download the images and put them in the same directory as the source.

Needs compiling, right?
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 19, 2010, 07:33:00 pm
simple program that allows you to move a square around a 10 x 10 map. it's about 200 lines of code so i didn't post it here. don't be scared though, 60 lines of the 200 are just keyboard action events. you'll need to download the images and put them in the same directory as the source.

Needs compiling, right?

yes. but i can attach an executable jar if you want
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 20, 2010, 03:15:32 pm
I thought that that random number generator was weak and made a new one, much more attractive. Attached is a .jar file and here is a screenshot and the code:

(http://img.removedfromgame.com/imgs/RandomNumberGeneratorTwo.png)

Code: [Select]
// Imports
import javax.swing.*;
import java.util.Random;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Main {
    public static void main(String[] args) {
JFrame frame= new JFrame("Random Number generator");
                JPanel panel=new JPanel();
                final Random generator = new Random();
                final int randomNumber = generator.nextInt();
                final JTextArea textArea = new JTextArea(""+randomNumber,5,20);
                JLabel title = new JLabel("Random Number generator");
                JLabel empty = new JLabel("                                   "
                        + "                     "
                        + "                  ");
                JLabel programBy = new JLabel("                                                               by David Gomes");

                JButton generate = new JButton("Generate");
                generate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                    final Random generator = new Random();
                    final int randomNumber = generator.nextInt();
                    textArea.setText(""+randomNumber);
                }
                });

                JButton quitButton = new JButton("Quit");

                quitButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                    System.exit(1);
                }
                });
               

               

                frame.add(panel);
                panel.add(title);
               
                panel.add(textArea);
                panel.add(generate);
                panel.add(quitButton);
                panel.add(empty);
                panel.add(programBy);
                frame.setSize(300,220);
                frame.setVisible(true);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
    }
}

Tell me what you think of it :)
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 27, 2010, 08:09:38 am
awesome! I'm keep learning... :)
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 27, 2010, 08:28:36 am
awesome! I'm keep learning... :)

Do you like Java?
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on December 27, 2010, 08:29:45 am
Yes, I do.
In fact I'm learning it right now(APCS)
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on December 27, 2010, 10:35:21 am
Yes, I do.
In fact I'm learning it right now(APCS)

That's great. Thanks for waking up this post :)
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 30, 2010, 11:12:06 pm
ColorChooser! it has more range than MS Paint, which really isn't saying much because the actual color-oriented math is done by java. change the final int SIZE in ColorChooser to make the size larger.

here's the source:

Code: [Select]
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;;

public class ColorChooserTest extends JFrame{

public ColorChooserTest(){
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("hi");
ColorChooser panel = new ColorChooser();
getContentPane().add(panel);
setVisible(true);
while(true)
panel.repaint();
}
public static void main(String[] args){
new ColorChooserTest();
}
}

class ColorChooser extends JPanel implements MouseMotionListener,MouseListener{
private final int SIZE = 200;
private BufferedImage gradient = new BufferedImage(SIZE, SIZE, BufferedImage.TYPE_4BYTE_ABGR);
private BufferedImage hueStrip = new BufferedImage(15, SIZE, BufferedImage.TYPE_4BYTE_ABGR);
private Rectangle hueRect = new Rectangle(SIZE + 20,10,15,SIZE);
private Rectangle gradientRect = new Rectangle(10,10,SIZE,SIZE);
private float hue = 0;
private Color selectedColor = Color.RED;
public ColorChooser(){
addMouseListener(this);
addMouseMotionListener(this);
setFocusable(true);
generateHueStrip();
}
public void paintComponent(Graphics g){
Graphics2D g2d = (Graphics2D) g;
generateGradient();
g2d.drawImage(gradient,null,10,10);
g2d.drawImage(hueStrip,null,SIZE + 20,10);
g2d.setColor(selectedColor);
g2d.fillRect(10,SIZE+20,30,30);
}

private void generateHueStrip(){
for(int i = 0; i < SIZE; i++){
Color hsb = Color.getHSBColor((float)(i/(double)SIZE),(float) 1.0,(float) 1);
for(int k = 0; k < 15; k++)
hueStrip.setRGB(k,i,hsb.getRGB());
}
}
private void generateGradient(){
for(int saturation = SIZE-1; saturation >= 0; saturation--){
for(int value = SIZE-1; value >= 0; value--){
Color hsb = Color.getHSBColor(hue, (float) saturation / SIZE, (float) value / SIZE);
gradient.setRGB(value, SIZE - 1 -saturation, hsb.getRGB());
}
}
}
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
if(hueRect.contains(x,y)){
x -= SIZE + 20;
y -= 10;
Color rgb = new Color(hueStrip.getRGB(x,y));
int red = rgb.getRed();
int blue = rgb.getBlue();
int green = rgb.getGreen();
hue = Color.RGBtoHSB(red, green, blue, null)[0];
}
else
if(gradientRect.contains(x,y))
selectedColor = new Color(gradient.getRGB(x-10,y-10));

}
public void mouseDragged(MouseEvent e) {
mouseClicked(e);
}
public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e){}
}
Title: Re: Random simple java programs that actually do something useful.
Post by: Binder News on December 30, 2010, 11:56:53 pm
I love everything about Java, except that the source is VERY insecure.
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on December 31, 2010, 12:12:44 am
I love everything about Java, except that the source is VERY insecure.

you can always just bundle everything up in a couple meaningless wrapper classes, have one-letter var names, method names and classes. and make all your classes implement random interfaces completely off-base to their real purpose. define a final constant True as 0, and False as 1. write comments that lie. of course this really just bloats your code and makes it unmaintainable.. BUT, no one's going to pick through it.
Title: Re: Random simple java programs that actually do something useful.
Post by: jnesselr on December 31, 2010, 05:07:31 pm
I love everything about Java, except that the source is VERY insecure.

you can always just bundle everything up in a couple meaningless wrapper classes, have one-letter var names, method names and classes. and make all your classes implement random interfaces completely off-base to their real purpose. define a final constant True as 0, and False as 1. write comments that lie. of course this really just bloats your code and makes it unmaintainable.. BUT, no one's going to pick through it.
True, or you could write classes that are like the programs that read their own source code, but instead, they decrypt themselves into a program that compiles the real program that then runs. It only takes 10 days to run a hello world program, but hey, it's secure, right? ;-)

But seriously, Java has it's uses and I like it for quite a few things. The fact that I can always get the source of a jar file within two clicks is one of them.
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 10, 2011, 01:58:56 pm
Code: [Select]
package javaapplication1;

import java.awt.Color;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * NewJFrame.java
 *
 * Created on 10/Fev/2011, 0:01:33
 */

/**
 *
 * @author david
 */
public class NewJFrame extends javax.swing.JFrame {

    /** Creates new form NewJFrame */
    public NewJFrame() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jColorChooser1 = new javax.swing.JColorChooser();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Text Editor");

        jTextField2.setForeground(jColorChooser1.getColor());

        jButton1.setText("UPDATE");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        jMenuItem1.setText("New");
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jColorChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1))
                    .addComponent(jColorChooser1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        this.jTextField2.setText("");
        this.jTextField2.setForeground(this.jColorChooser1.getColor());
)
    }                                       

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
               
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JColorChooser jColorChooser1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration

}

Code: [Select]
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package javaapplication1;

public class Main {
   
    public static void main(String[] args) {
        NewJFrame form = new NewJFrame();
        form.setVisible(true);

       
    }

}

The second one is Main.java and the first one is NewJFrame.java.

The thing is I'm using Color Chooser under Swing Windows, it's automatic.
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 20, 2011, 02:47:58 pm
Code: [Select]
package randomnumbergame;

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter difficulty (from 0 to 1000): ");
        Scanner difficulty = new Scanner(System.in);
        int difficultyLevel = difficulty.nextInt();
        if (difficultyLevel<0 || difficultyLevel>1000)
        {
            System.out.println("Invalid Difficulty");
        }
        System.out.println(difficulty.nextLine());
        Random generator = new Random();
        int randomNumber = generator.nextInt(difficultyLevel);
        boolean gotIt = false;
        while (gotIt == false)
        {
            Scanner attempt = new Scanner(System.in);
            int attemptNumber = attempt.nextInt();
            if (attemptNumber == randomNumber)
            {
                gotIt = true;
            }
            else
            {
                if (attemptNumber > randomNumber)
                {
                    System.out.println("The secret number is smaller... ");
                }
                else
                {
                    System.out.println("The secret number is highter... ");
                }
            }
        }
        System.out.println("You won!");
    }

}

Random Number Game :)
Title: Re: Random simple java programs that actually do something useful.
Post by: broooom on February 20, 2011, 02:49:31 pm
I'd avoid creating a scanner each and every time you need to read something - once is enough. :)
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 20, 2011, 02:50:18 pm
I'd avoid creating a scanner each and every time you need to read something - once is enough. :)

Oh yeah, I just need to call it again ;D
Title: Re: Random simple java programs that actually do something useful.
Post by: Ashbad on February 20, 2011, 02:50:47 pm
Hello, I want to use java at home, and I'm trying to download eclipse right now, unless if you guys think netbeans is better :P

anyways, I suck at knowing all of these things how to install libraries and such, anyone know of a simple graphics library that can do 3D, and is easy to install?
Title: Re: Random simple java programs that actually do something useful.
Post by: Deep Toaster on February 20, 2011, 02:50:52 pm
Yeah, just use the same Scanner each time. Otherwise it can quickly eat up the JVM.
Title: Re: Random simple java programs that actually do something useful.
Post by: broooom on February 20, 2011, 02:51:37 pm
Hello, I want to use java at home, and I'm trying to download eclipse right now, unless if you guys think netbeans is better :P

anyways, I suck at knowing all of these things how to install libraries and such, anyone know of a simple graphics library that can do 3D, and is easy to install?
You shouldn't be using Java for anything 3D - it's just too slow/memory-intensive for that. That's my opinion though.
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 20, 2011, 02:52:00 pm
Code: [Select]
package randomnumbergame;

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter difficulty (from 0 to 1000): ");
        Scanner inputScanner = new Scanner(System.in);
        int difficultyLevel = inputScanner.nextInt();
        if (difficultyLevel<0 || difficultyLevel>1000)
        {
            System.out.println("Invalid Difficulty");
        }
        System.out.println(inputScanner.nextLine());
        Random generator = new Random();
        int randomNumber = generator.nextInt(difficultyLevel);
        boolean gotIt = false;
        while (gotIt == false)
        {
            int attemptNumber = inputScanner.nextInt();
            if (attemptNumber == randomNumber)
            {
                gotIt = true;
            }
            else
            {
                if (attemptNumber > randomNumber)
                {
                    System.out.println("The secret number is smaller... ");
                }
                else
                {
                    System.out.println("The secret number is highter... ");
                }
            }
        }
        System.out.println("You won!");
    }

}

Would this work, then?
Title: Re: Random simple java programs that actually do something useful.
Post by: broooom on February 20, 2011, 02:52:59 pm
One more thing: when the difficulty input is invalid, the program says so, but doesn't actually do anything - it just continues with the invalid input. :)
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 20, 2011, 02:53:59 pm
Code: [Select]
package randomnumbergame;

import java.util.Random;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        System.out.println("Enter difficulty (from 0 to 1000): ");
        Scanner inputScanner = new Scanner(System.in);
        int difficultyLevel = inputScanner.nextInt();
        if (difficultyLevel<0 || difficultyLevel>1000)
        {
            System.out.println("Invalid Difficulty");
            sys.exit(0);
        }
        System.out.println(inputScanner.nextLine());
        Random generator = new Random();
        int randomNumber = generator.nextInt(difficultyLevel);
        boolean gotIt = false;
        while (gotIt == false)
        {
            int attemptNumber = inputScanner.nextInt();
            if (attemptNumber == randomNumber)
            {
                gotIt = true;
            }
            else
            {
                if (attemptNumber > randomNumber)
                {
                    System.out.println("The secret number is smaller... ");
                }
                else
                {
                    System.out.println("The secret number is highter... ");
                }
            }
        }
        System.out.println("You won!");
    }

}

Fixed.
Title: Re: Random simple java programs that actually do something useful.
Post by: Ashbad on February 20, 2011, 02:54:14 pm
Hello, I want to use java at home, and I'm trying to download eclipse right now, unless if you guys think netbeans is better :P

anyways, I suck at knowing all of these things how to install libraries and such, anyone know of a simple graphics library that can do 3D, and is easy to install?
You shouldn't be using Java for anything 3D - it's just too slow/memory-intensive for that. That's my opinion though.

well, I'm talking simple 3D, like minecraft 3D.
Title: Re: Random simple java programs that actually do something useful.
Post by: broooom on February 20, 2011, 02:55:52 pm
I'd do:

Code: [Select]
        int difficultyLevel = inputScanner.nextInt();
        while (difficultyLevel<0 || difficultyLevel>1000)
        {
            System.out.println("Invalid Difficulty");
            difficultyLevel = inputScanner.nextInt();
        }
:)
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 20, 2011, 02:55:55 pm
Hello, I want to use java at home, and I'm trying to download eclipse right now, unless if you guys think netbeans is better :P

anyways, I suck at knowing all of these things how to install libraries and such, anyone know of a simple graphics library that can do 3D, and is easy to install?
You shouldn't be using Java for anything 3D - it's just too slow/memory-intensive for that. That's my opinion though.

well, I'm talking simple 3D, like minecraft 3D.

Even though... It's just so complicated, you shouldn't start with it, never.
Title: Re: Random simple java programs that actually do something useful.
Post by: broooom on February 20, 2011, 02:56:25 pm
Hello, I want to use java at home, and I'm trying to download eclipse right now, unless if you guys think netbeans is better :P

anyways, I suck at knowing all of these things how to install libraries and such, anyone know of a simple graphics library that can do 3D, and is easy to install?
You shouldn't be using Java for anything 3D - it's just too slow/memory-intensive for that. That's my opinion though.

well, I'm talking simple 3D, like minecraft 3D.
Well, still - you'd better be off learning C++ IMO. ;)
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on February 20, 2011, 02:56:45 pm
I'd do:

Code: [Select]
        int difficultyLevel = inputScanner.nextInt();
        while (difficultyLevel<0 || difficultyLevel>1000)
        {
            System.out.println("Invalid Difficulty");
            difficultyLevel = inputScanner.nextInt();
        }
:)

The user can also be too dumb to fix the error and make a valid difficulty. But it doens't matter.
Title: Re: Random simple java programs that actually do something useful.
Post by: Ashbad on February 20, 2011, 02:57:56 pm
Hello, I want to use java at home, and I'm trying to download eclipse right now, unless if you guys think netbeans is better :P

anyways, I suck at knowing all of these things how to install libraries and such, anyone know of a simple graphics library that can do 3D, and is easy to install?
You shouldn't be using Java for anything 3D - it's just too slow/memory-intensive for that. That's my opinion though.

well, I'm talking simple 3D, like minecraft 3D.

Even though... It's just so complicated, you shouldn't start with it, never.

I'm not starting with it, I definately know how to do java, just test me if you need to ;)

I tried openGL with C++ before, but that's the hardest way to use 3D I found out x.x  I just need to know a good library that's easy to install.
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on March 25, 2011, 05:52:00 pm
Well, this is the java code that lets u convert decimal to binary ~ 36-base number.
Code: [Select]
import java.util.*;
public class Convert
{
    public static String convertbase(int n, int base) {
       // special case
       if (n == 0) return "0";

       String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       String s = "";
       while (n > 0) {
          int d = n % base;
          s = digits.charAt(d) + s;
          n = n / base;
       }
       return s;
    }
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the number base 10 to convert:  ");
        int original = keyboard.nextInt();
        System.out.print("Enter the new base: ");
        int base = keyboard.nextInt();
        String answer = convertbase(original,base);
        System.out.println("The number "+original+"[base 10] = "+answer+"[base "+base+"]");
    }
}
Title: Re: Random simple java programs that actually do something useful.
Post by: Munchor on March 25, 2011, 05:59:46 pm
Code: [Select]
import java.util.*;
public class Convert
{
    public static String convertbase(int n, int base) {
       // special case
       if (n == 0) return "0";

       String digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
       String s = "";
       while (n > 0) {
          int d = n % base;
          s = digits.charAt(d) + s;
          n = n / base;
       }
       return s;
    }
    public static void main(String[] args)
    {
        Scanner keyboard = new Scanner(System.in);
        System.out.print("Enter the number base 10 to convert:  ");
        int original = keyboard.nextInt();
        System.out.print("Enter the new base: ");
        int base = keyboard.nextInt();
        String answer = convertbase(original,base);
        System.out.println("The number "+original+"[base 10] = "+answer+"[base "+base+"]");
    }
}

This is looking good. It seems like it supports all bases.

Here's how it works for me:
Code: [Select]
david@DavidPC:~/Documentos/Java$ javac Convert.java
david@DavidPC:~/Documentos/Java$ java Convert
Enter the number base 10 to convert:  65535
Enter the new base: 16
The number 65535[base 10] = FFFF[base 16]
david@DavidPC:~/Documentos/Java$ java Convert
Enter the number base 10 to convert:  255
Enter the new base: 2
The number 255[base 10] = 11111111[base 2]
Title: Re: Random simple java programs that actually do something useful.
Post by: Yeong on March 25, 2011, 06:14:38 pm
Well, that's what supposed to look like.  :)
BTW, don't try incredibly huge number or it will go overflow XD
Title: Re: Random simple java programs that actually do something useful.
Post by: nemo on March 26, 2011, 03:49:09 pm
then to go from any base to another...

Code: [Select]
import java.util.Scanner;
public class Test{
public static void main(String[] args){
Scanner intRead = new Scanner(System.in);
Scanner strRead = new Scanner(System.in);
System.out.print("Enter a number to convert: ");
String src = strRead.nextLine();
System.out.print("Enter the number's base: ");
int oldBase = intRead.nextInt();
System.out.print("Enter the desired base: ");
int newBase = intRead.nextInt();
String ans = Integer.toString(Integer.valueOf(src, oldBase), newBase);
System.out.println(src + " in base " + oldBase + " is " + ans + " in base " + newBase);
}
}