Jump to content


Check out our Community Blogs

Turk4n

Member Since 13 May 2008
Offline Last Active Dec 03 2013 10:12 PM
-----

#457826 Java Textbooks/Tutorials

Posted by Turk4n on 01 May 2009 - 09:29 AM

Visit these if you like e-learning and tutorials :)

The Java™ Tutorials
JeLSIM - Java eLearning and Simulation
Online Java eLearning Training Certification Training
Java Script - Javascript Tutorial - Java

Cheers :D !
  • 1


#445992 100 ways to print out "Hello CodeCall"

Posted by Turk4n on 22 March 2009 - 03:13 AM

#41
Java
public class CodeCallHello {
	public static void main(String arg[]) {
		
		String[][] CodeCall = new String[2][2];
		
		CodeCall[0][0] = "Hello";
		CodeCall[1][1] = "CodeCall";
		System.out.println(CodeCall[0][0]+" "+CodeCall[1][1]);
	}
}

  • 1


#437930 Encryption

Posted by Turk4n on 01 March 2009 - 08:40 AM

I really liked it so I just added things useful for people that just wants it to work !

Cheers mate !
import java.io.*;
import java.util.Random;
import java.util.Scanner;
public class encrypt {
	static Scanner sc = new Scanner(System.in);
	private static Random generator = new Random(5);
	
	public static void main(String[]args) throws Exception {
		InputStreamReader keyReader = new InputStreamReader(System.in);
		BufferedReader keyInput = new BufferedReader(keyReader);
		String passWord = "";
		int passWordLength = 0;
		String EncryptedFilePath = ""; 
		int originalByte = 0;
		int encryptedByte = 0;
		int mask = 0;
		int counter = 0;
		
		System.out.print("Input filename: ");
		String inputFilePath = keyInput.readLine();;
		File inFile = new File(inputFilePath);
		
		if (inFile.exists()){
			FileInputStream reader = new FileInputStream(inFile);
			
			System.out.print("Output filename: ");
			EncryptedFilePath = keyInput.readLine();
			FileOutputStream writer = new FileOutputStream(EncryptedFilePath);

			System.out.print("Please enter a password: ");
			passWord = keyInput.readLine();
			passWordLength = passWord.length();


			for (int i = 0; i<inFile.length(); i++) {
				originalByte = reader.read();          
		 		mask = loopNum((int)passWord.charAt(counter)); 
		 		encryptedByte = mask ^ originalByte;
				writer.write(encryptedByte);
				counter++;
				
				if(counter >= passWordLength) {
					counter=0;
				}	
			}
			writer.close();	
		}
		else if(!inFile.exists()) {
			System.out.println("Source file was not found.");
			Thread.sleep(500);
			System.out.println("Would you like to create the file?\n1.Yes\n2.No");
			int NewFile = sc.nextInt();
			
			if(NewFile == 1) {
				System.out.println("Where would you like the source to be created?");
				String NewLocation = sc.next();
				PrintWriter PW = new PrintWriter(new FileWriter(NewLocation));
				PW.close();
				FileInputStream reader = new FileInputStream(NewLocation);
				
				System.out.print("Output filename: ");
				EncryptedFilePath = keyInput.readLine();
				FileOutputStream writer = new FileOutputStream(EncryptedFilePath);

				System.out.print("Please enter a password: ");
				passWord = keyInput.readLine();
				passWordLength = passWord.length();


				for (int i = 0; i<inFile.length(); i++) {
					originalByte = reader.read();          
			 		mask = loopNum((int)passWord.charAt(counter)); 
			 		encryptedByte = mask ^ originalByte;
					writer.write(encryptedByte);
					counter++;
					
					if(counter >= passWordLength) {
						counter=0;
					}	
				}
				writer.close();	
			}
			else if(NewFile == 2) {
				System.out.println("Your loss...");
				Thread.sleep(1000, 500);
			}
			else
				System.out.println("Bugged part :D");
		}	
	}
public static int loopNum(int loopEnd) {
		for (int i = 0; i<= loopEnd; i++) {
			 generator.nextInt(256);
		}
		return generator.nextInt(256);
	}
}

Credits goes to TALucas
  • 1


#435226 100 ways to print out "Hello CodeCall"

Posted by Turk4n on 18 February 2009 - 10:20 PM

Lies! C# just uses .NET's CLR. You can completely replace it or never even use it (not much point to the last one) This is how the couple of hobby OS projects are able to use C# as their programming language. They use a middle-man native compiler to produce code for a standard x86.

LSL

default
{
    state_entry()
    {
        llOwnerSay("Hello Codecall");
    }
}


Remarks are nice but stay on topic :)

Lua with standard IO lib.

io.write("Hello Codecall\n");


Forgotten the #number?
:)

#29

Java
import java.io.*;
public class Cowsay	{
	
	String cowsay;
	String dashLength="";
	BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
	
	public void askInput() throws IOException	{
		cowsay=stdin.readLine();
		for(int i=0;i<cowsay.length();i++)	{
			dashLength=dashLength+("-");
		}
	}
public void printCow()	{
		
		System.out.println("-"+dashLength+"-");
		System.out.println("< "+cowsay+" >");
		System.out.println("-"+dashLength+"-");
        System.out.println("  |  ^__^");
        System.out.println("   - (oo)|______");
        System.out.println("     (__)|       )/|/|_");
        System.out.println("         ||----w |");
        System.out.println("         ||     ||");
	}	
	public static void main(String[] args) throws IOException	{
		Cowsay c1 = new Cowsay();
		c1.askInput();
		c1.printCow();
	}
}
*Typing in Hello CodeCall*
Output
  ---------------
<  Hello CodeCall >
  ---------------
  |  ^__^
   - (oo)|______
     (__)|       )/|/|_
         ||----w |
         ||     ||

  • 1


#433742 100 ways to print out "Hello CodeCall"

Posted by Turk4n on 13 February 2009 - 01:07 PM

Hey everyone in CodeCall !

Long time members, new commoners welcome to another CodeCall programming game !

To participate in the game you will need to write a program that will print out following, "Hello CodeCall"*, the goal with the game is to reach 100 ways to print out the message...*

So...

Rules
#1 - Always before pasting in the code, type in "Number #X", X is the increasing number of how many ways we can do it...
#2 - Try not to do the same code over and over, avoid to do an identically code which someone else has posted
#3 - double post, triple post or quad and etc...
#4 - Any programming language is welcome, however try to avoid using markup languages,you 'CAN' do it if we are losing...
#5 - DO not post spam or garbage message !

So GLHF !

First to contribute !
Number #1
public class HelloCodeCall {
public static void main(String[] arg) {
System.out.println("Hello CodeCall");
  }
}

  • 1


#433431 Java why does it not work??

Posted by Turk4n on 12 February 2009 - 11:00 AM

I will help you and listen please :D

First step.
Go and download Java JDK.
Second step.
Go download textpad.
Third step, follow my stupid tutorial for you...
Install JDK first and then textpad when java is done !
Fourth step, follow the picture tutorial !
Double click the icon...
Posted Image
Fifth step, follow the picture tutorial !
Posted Image
Sixth step, follow the picture tutorial !
Posted Image
Seventh step, follow the picture tutorial !
Posted Image
Eighth step, follow the picture tutorial !
Posted Image
Ninth step, follow the picture tutorial !
Posted Image
Tenth step, follow the picture tutorial !
Posted Image
Eleventh step, follow the picture tutorial !
Posted Image
Twelfth step, follow the picture tutorial !
Posted Image
Thirteenth step, follow the picture tutorial !
Posted Image

So there you go, enjoy and have fun "coding" !

P.S - +REP me PLEASE FOR THIS :D
  • -1


#430193 JComboBox - Simple Version !

Posted by Turk4n on 29 January 2009 - 03:12 PM

Hey C.C, I hope you enjoy tutorials since I enjoy to share knowledge with others hope you guys feel the same !

Today I will try to introduce you guys to JComboBox with Editable boxes, FUN !

So let's get started !

Since I presume people have worked around with the swing package so making this wouldn't/shouldn't be a bother for you guys to understand !
However I will do my best to make it understand able !

The imports
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
Here we are importing the parts needed to create our application !
Swing for the gui, awt for allowing us setting up layouts ! awt.event for allowing us to see changes/change/edit/listen !

The variables we need for our function !
JComboBox Answer = new JComboBox();
JLabel Welcome = new JLabel();

So here is our Box that we are going to use !
JComboBox is common used when making a text list, example, name list; type your name check in others just view it up !
JLabel is simple, a label containing just pure text !

Layout
public TestTest() {
		setLayout(new FlowLayout());
		add(new JLabel("What's your name?",JLabel.RIGHT));
		add(Answer);
		add(Welcome);
		Welcome.setHorizontalAlignment(JLabel.LEFT);
		Answer.setEditable(true);
		Answer.addActionListener(this);
		setSize(350,90);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
The public part is our constructor(since we need to create a layout it will always be done by our constructor !)
By applying a flowlayout we will be able to set a "flow" in the frame !
Hence we will be able to use the layout whenever we want, kinda dynamically.
By using Add we add them to our layout and after we have added we have to give them proper position !
As I have been talking about our box will be editable meaning we can enter how much information we want to and it will remember it.
Adding the ActionListener will allow us to view "changes" clicks,and movements !
setSize is no problem nor setVisible same goes with setDefaultCloseOperation !
Simple things that should be understood !

Our listener, while making applications and want to make it "do" something.
public void actionPerformed(ActionEvent e) {
		String Name = (String) Answer.getSelectedItem();
		Welcome.setText("Welcome "+Name+" to CodeCall!");
		Answer.addItem(Name);
	}
While we listing for event changes, while it happens it will add in our text to the box and print out a "welcome" phrase !

The Main
public static void main(String[] arg) {
		TestTest Test = new TestTest();
	}
}
So I hope you guys enjoy this tutorial as I did !

Also the whole code!
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
JComboBox Answer = new JComboBox();
JLabel Welcome = new JLabel();
public TestTest() {
		setLayout(new FlowLayout());
		add(new JLabel("What's your name?",JLabel.RIGHT));
		add(Answer);
		add(Welcome);
		Welcome.setHorizontalAlignment(JLabel.LEFT);
		Answer.setEditable(true);
		Answer.addActionListener(this);
		setSize(350,90);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
public void actionPerformed(ActionEvent e) {
		String Name = (String) Answer.getSelectedItem();
		Welcome.setText("Welcome "+Name+" to CodeCall!");
		Answer.addItem(Name);
	}
	public static void main(String[] arg) {
		TestTest Test = new TestTest();
	}
}
Screenie for you guys ;)
[ATTACH]1301[/ATTACH]

Attached Thumbnails

  • output.PNG

  • 1


#427272 Cowsays - Python !

Posted by Turk4n on 18 January 2009 - 01:40 AM

nice one .. a +rep from me too :)


Thanks :D
  • 1


#427215 Cowsays - Python !

Posted by Turk4n on 17 January 2009 - 01:54 PM

Credits goes to me !
This time I made a funny thing !
I have posted two other versions, java and c++ version.

Java Version
http://forum.codecal...035-cowsay.html
C++ Version
http://forum.codecal...-c-version.html

Python Version
import sys
if sys.argv[1] != "cowsay":
    print "Usage:\n 'cowsay string'"
    sys.exit(0)

cowsay = sys.argv[2]
lne0 = 2+len(cowsay)
line0 = "  "
line0 = line0+"_"*lne0
lne = 2+len(cowsay)
line = "-"*lne

cowtxt= line0+"\n\
 < "+cowsay+" > \n\
  "+line+" \n\
         \   ^__^ \n\
          \  (oo)\_______ \n\
             (__)\       )\/\ \n\
                 ||----w | \n\
                 ||     ||\
                     "
print cowtxt
Hope you guys like it and +rep me for creativity :P
Also the Java and C++ versions are NOT mine, so thank the rightful owners for them :)
  • 2


#425606 CodeCall's First Applet - Simple Version !

Posted by Turk4n on 14 January 2009 - 10:56 AM

Hey CodeCall, while reading C++ things I thought I have forgotten to show you guys about applets :)

So today I present you simple tutorial about how to create an applet(Java)!

So lets move on !

The library we will use for the applet !
import java.awt.*;
import javax.swing.*;
We will use the .awt.*; library, since we are going to create a simple interface why not use the library for it ;)

The base of the application !
public class CodeCallApplet extends JApplet {
public void init() {
Here are we making it clear for the application that we are gonna use the JApplets functions, i.o.w; we are going to inheritance its functions.

Our functions !
JLabel L = new JLabel("Welcome to CodeCall Applet !,JLabel.CENTER);
add(L);
L.setOpaque(true);
L.setBackground(Color.gray);
L.setForeground(Color.black);
L.setFont(new Font("SansSerif", Font.BOLD, 24));
}
}
There with out message and positioning it as well declaring no transparent background also what colours we will use and font :)

The whole code !
import java.awt.*;
import javax.swing.*;
public class CodeCallApplet extends JApplet {
public void init() {
JLabel L = new JLabel("Welcome to CodeCall Applet !,JLabel.CENTER);
add(L);
L.setOpaque(true);
L.setBackground(Color.white);
L.setForeground(Color.black);
L.setFont(new Font("Arial", Font.BOLD, 24));
}
}
However we are not done yet !
We didn't have main, oh noes, well we will let the browser do the job ;)

So let's create a html file to try out our applet !

The html file !
<html>
<head>
<title>CodeCall's first applet</title>
</head>
<body>
CodeCall Applet !
<br>
<applet code="TestApplet.class"
width="400"
height="150">
</applet>
<br>
</body>
</html>
So this code is basic html...

So I hope you guys enjoy this and will have some cool usage of it sometime in life :)

Cheers !

P.S - Have a screenshot, also pardon the black;"private things there nowdays.." :P
[ATTACH]1258[/ATTACH]

Attached Thumbnails

  • thetest.PNG

  • 5


#423512 ArrayList - Simple version !

Posted by Turk4n on 08 January 2009 - 01:44 PM

In edition to that quick note, to use an array list of any primitive data type (int, boolean, char, float, etc..) you have to use it's equivalent wrapper class. :)


Thanks for sharing ;)
  • -1


#422005 ArrayList - Simple version !

Posted by Turk4n on 03 January 2009 - 03:45 PM

Hey guys, today I thought I could show you guys what you can do with ArrayList, java's own build in Array+List :>, the ArrayList is in general slower than normal Arrays if used in larger codes and scales, however the usage of ArrayList comes in hand when you need to have a re-size able Array with implemented functions from a List.

So lets begin !

We start of by importing our packages and declare our class and main !
import static javax.swing.JOptionPane.*;
import javax.swing.*;
import java.util.*;

public class ArrayListTest {
public static void main(String [] arg) {

Now I chose to import the whole library than just one of the book(just a
metaphor)
To get only what we want to use, the import would look like this !
import java.util.ArrayList;
A small note !, when you import and close an import with ".*;" equals you
import the whole library.

Our ArrayList.
ArrayList<String> AL = new ArrayList<String>();
By using "ArrayList<String>" will every new Array be positioned and have a definition as a string ! So hence we will be working it strings, you could do Byte/Integer/Float/Double but not Char, due to not build in within ArrayList options !

So now let's go on with our options.
while(true){
String Choice= showInputDialog(null,"1.Add an element in the list"
+"\n2.Delete an element out of the list"
+"\n3.Show all elements in the list"
+"\n4.Delete all elements out of the list"
+"\n5.Sort"
+"\n6.Add an element in a free position"
+"\n7 Close");
if(Choice== null)
break;
This will force our user to make a choice :>

On with the first option !
else if(Choice.equals("1")){
String newElement = showInputDialog(null,"Add an element");
if(newElement == null) 
continue;
AL.add(newElement);
JOptionPane.showMessageDialog(null, "The element is now added !");
}

Here we will automatically add an element in the first position, so what did we do exactly?
AL.add(newElement);
Here we worked in by adding our element; but will this really work?
Indeed it will, due to it's a re-size able Array. Which will give the ability to add our element in the first position(0) and etc. However if you want to deiced what position it shall take, then you will have to do it like this.

How it is build when you want to deiced.
AL.add(Position,your element);
How it looks when we implement it in
AL.add(0,newElement);

So let's go on with our second option !
else if(Choice.equals("2")){
AL.size(); 
if(AL.size()<1) {
showMessageDialog(null,"You can't delete any elements there are non !");
continue;
}
String Del = showInputDialog("In what position? (0-"+(AL.size()-1)+")");
if(Del== null) continue;
while(true){
try{
int Number= Integer.parseInt(Del);
if(Number<0 || Number>= AL.size()) throw new Exception();
AL.remove(Number);
break;
} catch(Exception e){
Del = showInputDialog("You must chose between 0 and"+(AL.size()-1)+
"\nIn what position(0-"+(AL.size()-1)+")");
}
}
showMessageDialog(null, "Element is now deleted !");
}

Here is kind of a lot codes so let's make it simple and understandable !
We check our List if it contains anything, since we can't delete something with nothing in?
And that part is....
if(AL.size()<1) {
showMessageDialog(null,"You can't delete any elements there are non !");

Next thing to explain, this part
String Del = showInputDialog("In what position? (0-"+(AL.size()-1)+")");
if(Del== null) continue;
while(true){
Represents our real option since we want to delete "elements" when we have some in our list. So first by checking if it's there in our specific position.If nothing is typed in it will just continue and we will not delete anything !
However we want to delete so let's check it !
try{
int Number= Integer.parseInt(Del);
if(Number<0 || Number>= AL.size()) throw new Exception();
AL.remove(Number);
break;
} catch(Exception e){
Del = showInputDialog("You must chose between 0 and"+(AL.size()-1)+
"\nIn what position(0-"+(AL.size()-1)+")");
}
}
showMessageDialog(null, "Element is now deleted !");
By casting a try/catch we will be able to have a decent app that does not crash in the middle of it's work !
So by checking if the input was greater than 0 but still not less than AL's size then it shall throw all exceptions!
So that's it!

Third option !

else if(Choice.equals("3")){
if(AL.isEmpty()){ 
showMessageDialog(null,"There is nothing in the list !");
continue; 
}
for(int i=0; i<AL.size(); i++)
showMessageDialog(null,"These exists in the list"+AL.get(i));
}
So this part is our "eyes" to check if there is anything in our list, if there is nothing it will check and reply and continue the app, however if we do have things in our list it will print out every item and continue !

The fourth option !

else if(Choice.equals("4")){
if(AL.isEmpty()){
showMessageDialog(null, "The list is already empty !");
continue;
}
AL.clear();
showMessageDialog(null, "The list is now empty !");
}
Here we check if the list is empty and if so just reply and continue else not then clear everything and reply then continue !

The fifth option !

else if(Choice.equals("5")) {
Collections.sort(AL);
showMessageDialog(null,"Sorted "+AL);
}
This small task is really a neat thing about ArrayList, instead of creating an own or using someone else sorting algorithm we use the build in sorter!
*A small note !*
If you have imported only, java.util.ArrayList; then I suggest you add in
java.util.Collections; however if you imported the whole thing java.util.*; then you have nothing to worry with my notice.

Sixth option !

else if(Choice.equals("6")) {
String position = showInputDialog(null,"Type in position");
int pos = Integer.parseInt(position);
String NewElement= showInputDialog(null,"Type in an element");
AL.add(pos,NewElement);
}
This part allows us to add an element in whatever position we want to, can come in handy for does who are dandy !

Seventh option !

else if(Choice.equals("7")){
break;
}
Just closes itself nothing much.

Last part !
else
break;
}
}
}
The whole code !
import static javax.swing.JOptionPane.*;
import javax.swing.*;
import java.util.*;

public class ArrayList {
public static void main(String [] arg) {
while(true){
String Choice= showInputDialog(null,"1.Add an element in the list"
+"\n2.Delete an element out of the list"
+"\n3.Show all elements in the list"
+"\n4.Delete all elements out of the list"
+"\n5.Sort"
+"\n6.Add an element in a free position"
+"\n7 Close");

if(Choice== null)
break;
else if(Choice.equals("1")){
String newElement = showInputDialog(null,"Add an element");
if(newElement == null) 
continue;
AL.add(newElement);
JOptionPane.showMessageDialog(null, "The element is now added !");
}
else if(Choice.equals("2")){
AL.size(); 
if(AL.size()<1) {
showMessageDialog(null,"You can't delete any elements there are non !");
continue;
}
String Del = showInputDialog("In what position? (0-"+(AL.size()-1)+")");
if(Del== null) continue;
while(true){
try{
int Number= Integer.parseInt(Del);
if(Number<0 || Number>= AL.size()) throw new Exception();
AL.remove(Number);
break;
} catch(Exception e){
Del = showInputDialog("You must chose between 0 and"+(AL.size()-1)+
"\nIn what position(0-"+(AL.size()-1)+")");
}
}
showMessageDialog(null, "Element is now deleted !");
}
else if(Choice.equals("3")){
if(AL.isEmpty()){ 
showMessageDialog(null,"There is nothing in the list !");
continue; 
}
for(int i=0; i<AL.size(); i++)
showMessageDialog(null,"These exists in the list"+AL.get(i));
}
else if(Choice.equals("4")){
if(AL.isEmpty()){
showMessageDialog(null, "The list is already empty !");
continue;
}
AL.clear();
showMessageDialog(null, "The list is now empty !");
}
else if(Choice.equals("5")) {
Collections.sort(AL);
showMessageDialog(null,"Sorted "+AL);
}
String position = showInputDialog(null, "Type in position");
int pos = Integer.parseInt(position);
try {
String NewElement = showInputDialog(null, "Type in an element");
AL.add(pos, NewElement);
} catch (IndexOutOfBoundsException err) {
 showMessageDialog(null,"Index "+ pos +" is out of bounds.");
}
}
else if(Choice.equals("7")){
break;
}
else
break;
}
}
}

So hopefully you guys will learn something about ArrayLists :)
Peace out !
A picture of it at work !
[ATTACH]1213[/ATTACH]

Attached Thumbnails

  • test.PNG

  • 3


#419510 Game - stone,paper and scissor

Posted by Turk4n on 26 December 2008 - 01:50 PM

Hey there C.C, today am going to present you guys my simple template of the game called; stone,paper and scissor.


So it won't become something big or so, anyways let's get busy !


First part initialize our code and declaring it...
//Our packages we need to build up the template...
import static javax.swing.JOptionPane.*; 
//-note- importing a package statical will result;
every new line to be exact same "value & w/e", also note it is
for the JOptionPane part... so don't need to type it everytime :)
import java.util.*;

public class template {
   public static void main(String[] arg {

                ArrayList<String> Game = new ArrayList<String>();
		 Rule Play= new Rule(Game,Game);

We started off by building the main since it will take up more of 'my' time...
The ArrayList we are creating is a template to the constructor from our object that we will work on in the end to make the program work...
Afterward are we creating a bridge from object - main class...So we can have a great time with it ;)

Next step will be to make our options...
while(true) {
Play = new Rule(Game,Game); //Side note will tell why I did this...
String Choice = showInputDialog(null,"So what shall it be?\n1.Stone\n2.Paper
\n3.Scissors\n4.End Game");

if(Choice.equals("1")) {
      Play.al.set(0,"Stone");
            showMessageDialog(null,"Your choice was "+Play.al.get(0)+" the
computers choice was "+Play.AL.get(0));
if(Play.AL.get(0).equals(WinStone(Game))) {
    return;
    }
}
else if(Choice.equals("2")) {
      Play.al.set(1,"Paper");
            showMessageDialog(null,"Your choice was "+Play.al.get(1)+" the 
computers choice was "+Play.AL.get(1));
if(Play.AL.get(1).equals(WinPaper(Game))) { 
   return;
   }
}
else if(Choice.equals("3")) {
      Play.al.set(2,"Scissor")) {
            showMessageDialog(null,"Your choice was "+Play.al.get(2)+" the
computers choice was "+Play.AL.get(2));
if(Play.AL.get(2).equals(WinScissor(Game))) {
   return;
   }
}
else if(Choice.equals("4")) {
showMessageDialog(null,"The game has been terminated");
System.exit(0);
    }
}

We did a rather large code stripes, however this part was our game choices. As we do everytime a choice it will check for who wins and looses.
if(Play.AL.get(0).equals(WinStone(Game))) {
This is our method listener, which will check all the time with our methods criteria, we will soon go and have a look in our method.
To does you might have noticed that I every choice put...
Play.al.set(0,"Stone");
That is your choice in the arraylist we have in our object that I will return to...later on. However a small explanation; the 'Play' part is our "link" to the object that we have bridged together with the main and 'al' is our arraylist we have in the object. So by using 'set' we can decide what and where it should be in, this time the position and what it shall contain...side note we are using only ArrayList<String> so every position will contain an empty string, if you didn't declare or what so.

Let's dive into the method of our main :)

public static ArrayList<String> WinStone(ArrayList<String Game) {
         for(int i=0; i<Play.AL.size(); i++) {
          if(Play.AL.get(0).equals("Scissor")) {
  showMessageDialog(null,"You won !");
break;
}
          else if(Play.AL.get(0).equals("Stone")) {
  showMessageDialog(null,"It ended in a tie !");
break;
}
          else if(Play.AL.get(0).equals("Paper")) {
  showMessageDialog(null,"The computer won !");
break;
}
}
return null;
}
public static ArrayList<String> WinPaper(ArrayList<String> Game) {
        for(int j=0; j<Play.AL.size(); j++) {
          if(Play.AL.get(1).equals("Stone")) {
  showMessageDialog(null,"You won !");
break;
}
          else if(Play.AL.get(1).equals("Paper")) {
  showMessageDialog(null,"It ended in a tie !");
break;
}
          else if(Play.AL.get(1).equals("Scissor")) {
  showMessageDIalog(null,"The computer won !);
break;
}
}
return null;
}
public static ArrayList<String> WinScissor(ArrayList Game) {
         for(int k=0; k<Play.AL.size(); k++) {
          if(Play.AL.get(2).equals("Paper")) {
   showMessageDialog(null,"You won !");
break;
}
         else if(Play.AL.get(2).equals("Scissor")) {
  showMessageDialog(null,"It ended in a tie !");
break;
}
         else if(Play.AL.get(2).equals("Stone")) {
  showMessageDialog(null,"The computer won !");
break;
}
}
return null;
}
}

That was our rather large method to check our winners :)
To give you guys some info, when we want to check for our winner. I compared the positions and the info inside.
if(Play.Al.get(0).equals("Stone"))
And the user choose stone it will respond with the message...
showMessageDialog(null,"It ended in a tie");
However this is because we are looping through the whole list and checking with our criteria that in our first position contains 'stone' and the user chooses 'stone' it will end in a tie. Then how do the method knows what 'AL' is?
Simple as pie, we are creating a reference to it. I will tell you guys later on when we start making our object and our object won't be something big or so but something rather simple :)

Now let's begin with our object !
To start off I will explain why I did in this way. I found it simple and neat to have it this way and I will show it now...

Object...

import java.util.*;
class Rule {
static ArrayList<String> AL = new ArrayList<String>();
static ArrayList<String> al = new ArrayList<String>();

//Non given constructor
Rule() {
AL = null;
al = null;
}
//given constructor
public Leken(ArrayList<String> LA, ArrayList<String> la) {
//this part isn't really needed but incase you want to know
where and what your doing and going keep these :)
AL = LA;
al = la;

AL.add(0,"Stone");
AL.add(1,"Scissor");
AL.add(2,"Paper");
Collections.shuffle(AL);


//This part is the users non given anything, we will set the containing later
when we are running the main :)
al.add(0,"");
al.add(1,"");
al.add(2,"");
     }
}
This small object is what we could call "dumb" Al, well not really but I would consider it that.
The computers choice is automated and will be randomized everytime we want to use them.
The randomizer is java's build in component in util library...
Collections.shuffle(list<>);

Also now when we are here at the object, I will tell how we could mix with values in our mains method. By giving our objects variables a static value means following. If we didn't have static and used the variable it would complain, due to the value we have in our main isn't the same as in the object. But if we allow it to be statical the result would mean, every 5 created will be exactly the same. So 5 in main will equal the 5 in the object.

Main
import static javax.swing.JOptionPane.*;
import java.util.*;

public class template {
   public static void main(String[] arg {

                ArrayList<String> Game = new ArrayList<String>();
		 Rule Play= new Rule(Game,Game);

while(true) {
        Play = new Rule(Game,Game); //Side note will tell why I did this...
String Choice = showInputDialog(null,"So what shall it be?\n1.Stone\n2.Paper
\n3.Scissors\n4.End Game");

if(Choice.equals("1")) {
      Play.al.set(0,"Stone");
            showMessageDialog(null,"Your choice was "+Play.al.get(0)+" the
computers choice was "+Play.AL.get(0));
if(Play.AL.get(0).equals(WinStone(Game))) {
    return;
    }
}
else if(Choice.equals("2")) {
      Play.al.set(1,"Paper");
            showMessageDialog(null,"Your choice was "+Play.al.get(1)+" the 
computers choice was "+Play.AL.get(1));
if(Play.AL.get(1).equals(WinPaper(Game))) { 
   return;
   }
}
else if(Choice.equals("3")) {
      Play.al.set(2,"Scissor")) {
            showMessageDialog(null,"Your choice was "+Play.al.get(2)+" the
computers choice was "+Play.AL.get(2));
if(Play.AL.get(2).equals(WinScissor(Game))) {
   return;
   }
}
else if(Choice.equals("4")) {
showMessageDialog(null,"The game has been terminated");
System.exit(0);
    }
}
public static ArrayList<String> WinStone(ArrayList<String Game) {
         for(int i=0; i<Play.AL.size(); i++) {
          if(Play.AL.get(0).equals("Scissor")) {
  showMessageDialog(null,"You won !");
break;
}
          else if(Play.AL.get(0).equals("Stone")) {
  showMessageDialog(null,"It ended in a tie !");
break;
}
          else if(Play.AL.get(0).equals("Paper")) {
  showMessageDialog(null,"The computer won !");
break;
}
}
return null;
}
public static ArrayList<String> WinPaper(ArrayList<String> Game) {
        for(int j=0; j<Play.AL.size(); j++) {
          if(Play.AL.get(1).equals("Stone")) {
  showMessageDialog(null,"You won !");
break;
}
          else if(Play.AL.get(1).equals("Paper")) {
  showMessageDialog(null,"It ended in a tie !");
break;
}
          else if(Play.AL.get(1).equals("Scissor")) {
  showMessageDIalog(null,"The computer won !);
break;
}
}
return null;
}
public static ArrayList<String> WinScissor(ArrayList Game) {
         for(int k=0; k<Play.AL.size(); k++) {
          if(Play.AL.get(2).equals("Paper")) {
   showMessageDialog(null,"You won !");
break;
}
         else if(Play.AL.get(2).equals("Scissor")) {
  showMessageDialog(null,"It ended in a tie !");
break;
}
         else if(Play.AL.get(2).equals("Stone")) {
  showMessageDialog(null,"The computer won !");
break;
}
}
return null;
}
}
Object.
import java.util.*;
class Rule {

static ArrayList<String> AL = new ArrayList<String>();
static ArrayList<String> al = new ArrayList<String>();

Rule() {
AL = null;
al = null;
}
public Leken(ArrayList<String> LA, ArrayList<String> la) {
AL = LA;
al = la;

AL.add(0,"Stone");
AL.add(1,"Scissor");
AL.add(2,"Paper");
Collections.shuffle(AL);

al.add(0,"");
al.add(1,"");
al.add(2,"");
     }
}

This is pretty much the game template, hopefully you guys will understand my explanations of how things work and so here with this program and sorry if it's kinda bloated with text.
If you need some help or "extra" details of what I did and why also functions. I will gladly help and reply.
Cheers everyone !
  • 3


#418443 c# colors minigame

Posted by Turk4n on 22 December 2008 - 11:55 PM

Yes really. It's gonna be warm, don't worry - hot, even. Nice and hot, just the way you like it.


Is it hot coco?
  • 1


#418146 Java - Funny things with ArrayList

Posted by Turk4n on 22 December 2008 - 04:58 AM

Fun thing with java is the ArrayList, gotta love it, "when" it is "useful". I found this really amusing due to I couldn't count how much it would be by adding 1-100...
So made a simple program to solve it for me :)

BTW, I used java since I know it better than C++/C# and python...However I will train more in c++/c# and python when I have time :)

import java.util.ArrayList;
public class ArrayListArray {

  public static void main(String[] args) {

    ArrayList<Integer> al = new ArrayList<Integer>();

   
    for(int j=0; j<=100; j++) {
    	al.add(j);
    
    System.out.println("1-100: "+ al );
    Object ia[] = al.toArray();
    int sum = 0;
    
    for(int i=0;i<ia.length;i++) 
      sum+=((Integer)ia[i]).intValue();
    
    System.out.println("Sum av 1-100 :"+ sum);
    }
  }
}
Hope you guys can use it whenever you feel like it :)
  • 1




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download