Jump to content


Check out our Community Blogs

Sinipull

Member Since 14 Jun 2009
Offline Last Active Oct 08 2018 11:51 PM
-----

#630867 Very Simple Payroll System In Java (Dos Base)

Posted by Sinipull on 30 May 2012 - 03:07 PM

You don't understand. There's no procedural programming style in Java. Java is fully object oriented.
If you are distributing your code to others under the title of "Tutorial", then it's your responsibility to make it at least follow the Java convention.

Classes should be written UpperCamelCase
Methods/Variables/Fields should be written lowerCamelCase
  • 1


#610692 Back to the basics: Having trouble with Swtich Case Statement

Posted by Sinipull on 06 October 2011 - 10:17 AM

This is correct, because space is not a vowel, which means you have 6 non-vowels.

a e i o u as vowels
and between them
_ _ _ _ _ f as non-vowels
  • -1


#574463 why does this work, why would you do it.

Posted by Sinipull on 24 September 2010 - 02:05 PM

Yes, the main method creates an instance of a class it belongs to. I don't know why this is considered good approach, but it eliminates the need for static access. One (very experienced) of my Java teachers used to do it too.
  • 1


#572453 Accessing an ArrayList from a different class

Posted by Sinipull on 04 September 2010 - 10:11 PM

You need to have a reference to the Question class inside your WWTBAMJFrameForm, and the Question class must allow the access to the ArrayList - which must be "public", or Question class could have getRandomQuestions() method, which gives you the reference to the List.

for example:
import java.util.ArrayList;

public class Test{
    public static void main(String[] args) {
        Question q = new Question();
        
        // ACCESS THE ARRAYLIST.
        ArrayList<Question> questions = q.getQuestionList();
        
    }    
}


class Question{
    private ArrayList<Question> randomQuestions = new ArrayList<Question>();
    
    public ArrayList<Question> getQuestionList(){
        return randomQuestions;
    }
}


  • 1


#568870 Java applet JButton - strange behaviour

Posted by Sinipull on 11 August 2010 - 12:35 PM

You need to use panels and layout styles. Right now you have no definition how the buttons should be displayed, so no wonder they look like this.

for example:
     JPanel buttonPanel = new JPanel(new FlowLayout());
     buttonPanel.add(button1);
     buttonPanel.add(button2);
     getContentPane.add(buttonPanel);

I've learned, that nicest layouts can be created using a mix of GridLayout and FlowLayout.
More about layouts: A Visual Guide to Layout Managers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Laying Out Components Within a Container)
  • -1


#552130 Help me with J# please.

Posted by Sinipull on 18 April 2010 - 01:02 AM

words.add(st);
You realize you are adding the st(StringTokenizer) object to the Vector object? You are not taking Strings out of the st Object, but you are adding the object itself.
I think StringTokenizer has a method that should get you the next String.
Something like this:
words.add(st.nextToken());
also, you should use generics, so such mistake could never happen:
instead of:
Vector words = new Vector();
try:
Vector<String> words = new Vector<String>();

  • -1


#545010 Robot class

Posted by Sinipull on 03 March 2010 - 12:00 PM

This tutorial is about java Robot class. (java.awt.Robot)

I will quote Sun here:

"This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The

primary purpose of Robot is to facilitate automated testing of Java platform implementations."


So, basically this gives the low-level input control over your mouse and keyboard to your java program. Note, that you are still able to control your mouse and keyboard when the robot is running (in case of correct coding).

IMPORTANT: The Robot class gives your program as much power, as you have over your computer. It can do EVERYTHING you can do with your mouse and keyboard. The program has even ability to write it's own code, while running and these kind of programs should be written very carefully. (Not because Skynet is probable to evolve, but it can wreck something on your computer).

Ok, let's see how to start using the Robot class.
First we need to import the Robot class:

import java.awt.Robot;

Then we will need to make a Robot object:

Robot r = new Robot();

Now we have access to our Robot methods. (The complete list of methods and javadoc can be found here)

MOUSE:

r.mouseMove(x, y);
which moves your cursor instantly to the specified location.
Note, that x = 0 is located in the left of your screen and y = 0 is located at the top of your screen.
The largest values, where your cursor can move, is your screen resolution - 1. On my 1680x1050, it is x = 1679 and y = 1049.
If you tell the cursor to move out of the screen area, it will just slam against the respective wall.

r.mousePress(buttons);
r.mouseRelease(buttons);
Presses and instantly releases your specified button.
IMPORTANT: Never forget to release the button after pressing. (Can mess up something on your computer as a result, if lot of that is done)

the mousePress() and mouseRelease() takes int as an argument, which should be selected from amongst the constants in the InputEvent(java.awt.event.InputEvent) class:

those are the constants:
InputEvent.BUTTON1_MASK  //left button
InputEvent.BUTTON2_MASK  //middle button
InputEvent.BUTTON3_MASK  //right button

(I'm not sure, how they depend on the mouse, platform, configuration, etc, so you should check them out yourself.)


r.mouseWheel(wheelAmt);
This scrolls your mousewheel, if you have one. The wheelAmt argument is an int and should be positive or negative int value, depending how much or which way do you want to scroll the mouse.

KEYBOARD:

r.keyPress(key);
r.keyRelease(key);

Presses the specified key and releases it after.
IMPORTANT: Never forget to release the key after pressing. I actually had to restart my computer to fix the damage, that was caused by this mistake. Restarting just Eclipse didn't help.

The "key" argument is again int and should be selected as a constant from KeyEvent(java.awt.event.KeyEvent) class. Now, there are too many constants to copy them all here, so i'll just show you how they look:

r.keyPress(KeyEvent.VK_A); // press A-key
r.keyRelease(KeyEvent.VK_A); // release A-key

If you use proper IDE, you are able to find them all easily.


OTHER:

Robot class can also make screenshots or get the pixel color on screen:

r.createScreenCapture(new Rectangle(0, 0, 100, 100));
Creating screenshot requires Rectangle (java.awt.Rectangle) object as an argument, as this is the specified area, from where the screenshot is taken.
The result is BufferedImage (java.awt.image.BufferedImage) which can then be handeled properly (analyzed, saved or whatever needs to be done).

r.getPixelColor(x, y);
Gets you the pixel color as Color(java.awt.Color) object.

r.delay(ms);
Sleeps the specified amount of milliseconds. Is very useful when writing a Robot program. Is pretty much interchanceable with Thread.sleep(ms).

USEFUL STUFF TO KNOW WHEN WRITING A ROBOT

Get current screen resolution:
Toolkit.getDefaultToolkit().getScreenSize();
returns a Dimenson(java.awt.Dimension)

Get current mouse position
MouseInfo.getPointerInfo().getLocation();
returns a Point(java.awt.Point)


---

Again, beware of writing programs that take over your mouse and keyboard without sleeping. The only possible way to stop it, is the restart of the computer, from the physical button.
It's easy to stop the program from task manager, if only your mouse is stuck somewhere, but if you keyboard is being used too, then you are pretty much forced to plug off your computer.
Therefore, loops are dangerous, if not used properly!

Posted Image


The Robot class may not work on some platforms, as Sun has written:

Note that some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects.


Have fun ;)
  • 0


#509404 Abstract meaning(s) / Super --- " " ---.

Posted by Sinipull on 19 September 2009 - 01:34 PM

When you are making a class abstract, then it cannot be instantiated, this object cannot be created. This is useful, when you have general classes, like "Car", which has subclasses, that extend from it, like "Ferrari".... so "Car" cannot be created by calling "new Car();" but Ferrari can be created, if it's not abstract. Example:
public class Test {	 
	 public static void main(String[] args) throws IOException {
		 Car c1 = new Car(); // doesn't let to compile
		 Ferrari c2 = new Ferrari(); // compiles
	 }  
	 
} 

abstract class Car{
	
}

class Ferrari extends Car{
	
}

super calls a method or field from object's parent class.
like this:

public class Test {	 
	 public static void main(String[] args) throws IOException {
		 
		 Ferrari c2 = new Ferrari(); 
		 c2.getPower();
	 }  
	 
} 

abstract class Car{
	int motorPower = 20;
}

class Ferrari extends Car{
	int motorPower = 50;
	
	public void getPower(){
		System.out.println("This car's power is: "+motorPower+", but regular car's power is "+super.motorPower);
	}
	
}
Even though i override the "motorPower" field in the Ferrari class, i'm still able to access the original.
this prints: "This car's power is: 50, but regular car's power is 20"
  • -1


#507662 Upcasting, downcasting

Posted by Sinipull on 11 September 2009 - 07:35 AM

Upcasting and downcasting are important part of Java, which allow us to build complicated programs using simple syntax, and gives us great advantages, like Polymorphism or grouping different objects. Java permits an object of a subclass type to be treated as an object of any superclass type. This is called upcasting. Upcasting is done automatically, while downcasting must be manually done by the programmer, and i'm going to give my best to explain why is that so.

Upcasting and downcasting are NOT like casting primitives from one to other, and i believe that's what causes a lot of confusion, when programmer starts to learn casting objects.

Throughout this tutorial i'm going to use Animal hierarchy to explain how class hierarchy works.

Inheritance

images.jpg

What we have here, is a simplified version of an Animal Hierarchy. You can see, that Cat and Dog are both Mammals, which extends from Animal, which silently extends from Object. By silently, i mean, that Java automatically extends every class from Object class, which isn't extended from something else, so everything is an Object (except primitives).

Now, if you ask - is Cat an Object - It doesn't extend Object, it extends Mammal?
By inheritance Cat gets all the properties its ancestors have. Object is Cat's grandgrandparent, which means Cat is also an Object. Cat is also an Animal and a Mammal, which logically means - if Mammals possess mammary glands and Animals are living beings, then Cat also has mammary glands and is living being.

 

Basic JTable and Netbeans

What this means for a programmer, is that we don't need to write for every possible Animal, that it has health. We just need to write it once, and every Animal gets it through inheritance.
Consider the following example:
 

class Animal {
int health = 100;
}

class Mammal extends Animal { }

class Cat extends Mammal { }

class Dog extends Mammal { }

public class Test {
public static void main(String[] args) {
Cat c = new Cat();
System.out.println(c.health);
Dog d = new Dog();
System.out.println(d.health);
}
}

When running the Test class, it will print "100" and "100" to the console, because both, Cat and Dog inherited the "health" from Animal class.

Upcasting and downcasting

First, you must understand, that by casting you are not actually changing the object itself, you are just labeling it differently.
For example, if you create a Cat and upcast it to Animal, then the object doesn't stop from being a Cat. It's still a Cat, but it's just treated as any other Animal and it's Cat properties are hidden until it's downcasted to a Cat again.
Let's look at object's code before and after upcasting:

Cat c = new Cat();
System.out.println(c);
Mammal m = c; // upcasting
System.out.println(m);

/*
This printed:
Cat@a90653
Cat@a90653
*/

As you can see, Cat is still exactly the same Cat after upcasting, it didn't change to a Mammal, it's just being labeled Mammal right now. This is allowed, because Cat is a Mammal.

Note that, even though they are both Mammals, Cat cannot be cast to a Dog. Following picture might make it a bit more clear.

 

download.jpg

Although there's no need to for programmer to upcast manually, it's allowed to do.
Consider the following example:
 

Mammal m = (Mammal)new Cat();

is equal to
 

Mammal m = new Cat();

But downcasting must always be done manually:
 

Cat c1 = new Cat();
Animal a = c1; //automatic upcasting to Animal
Cat c2 = (Cat) a; //manual downcasting back to a Cat

Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException.

 

Double buffering, movement, and collision detection

This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.
Consider the following example:
 

Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");
Cat c2 = (Cat)a;
}

Note, that casting can't always be done in both ways. If you are creating a Mammal, by calling "new Mammal()", you a creating a Object that is a Mammal, but it cannot be downcasted to Dog or Cat, because it's neither of them.
For example:

Mammal m = new Mammal();
Cat c = (Cat)m;

Such code passes compiling, but throws "java.lang.ClassCastException: Mammal cannot be cast to Cat" exception during running, because im trying to cast a Mammal, which is not a Cat, to a Cat.

General idea behind casting, is that, which object is which. You should ask, is Cat a Mammal? Yes, it is - that means, it can be cast.
Is Mammal a Cat? No it isn't - it cannot be cast.
Is Cat a Dog? No, it cannot be cast.
Important: Do not confuse variables with instances here. Cat from Mammal Variable can be cast to a Cat, but Mammal from Mammal variable cannot be cast to a Cat.

 

Creating an Executable Jar File

Cats cant purr, while being labeled something else
If you upcast an object, it will lose all it's properties, which were inherited from below it's current position. For example, if you cast a Cat to an Animal, it will lose properties inherited from Mammal and Cat. Note, that data will not be lost, you just can't use it, until you downcast the object to the right level.
Why is it like that? If you have a group of Animals, then you can't be sure which ones can meow() and which ones can bark(). That is why you can't make Animal do things, that are only specific for Dogs or Cats.

 

dont know.jpg

However the problem above is not an obstacle, if you choose to use polymorphism. Polymorphism uses automatic downcast during method calls. I'm not going to go into details with this one, so i'm referring to Polymorphism tutorial by Turk4n: http://forum.codecal...lymorphism.html
updown5.png

Upcasting during method calling

The beauty of casting is that programmer can make general methods, which can take a lot of different classes as an argument.
For example:
 

public static void stroke(Animal a){
System.out.println("you stroke the "+a);
}

This method can have what ever Animal or it's subclass as an argument. For example calling:
 

Cat c = new Cat();
Dog d = new Dog();
stroke(c); // automatic upcast to an Animal
stroke(d); // automatic upcast to an Animal

..is a correct code.

updown3.png

however, if you have a Cat, that is currently being held by Animal variable, then this variable cannot be argument for a method, that expects only Cats, even though we currently have a instance of Cat - manual downcasting must be done before that.

updown4.png

About variables

Variables can hold instance of objects that are equal or are hierarchically below them. For example Cat c; can hold instances of Cat and anything that is extended from a Cat. Animal can hold Animal, Mammal, etc..
Remember, that instances will always be upcasted to the variable level.

"I really need to make a Dog out of my Cat!"

Well, you can't do it by casting. However, objects are nothing else, but few methods and fields. That means, you can make a new dog out of your Cat's data.

Let's say you have a Cat class:
 

class Cat extends Mammal {
Color furColor;
int numberOfLives;
int speed;
int balance;
int kittens = 0;

Cat(Color f, int n, int s, int B){
this.furColor = f;
this.numberOfLives = n;
this.speed = s;
this.balance = b;
}
}

and a Dog class.
 

class Dog extends Mammal {
Color furColor;
int speed;
int barkVolume;
int puppies = 0;

Dog(Color f, int n, int s, int B){
this.furColor = f;
this.speed = s;
this.barkVolume = b;
}
}

and you want to make a Dog out of the Cat. All you need to do, is, place a method inside of the Cat class, that converts the fields and returns a new Dog based on that.
 

public Dog toDog(int barkVolume){
Dog d = new Dog(furColor, speed, barkVolume);
d.puppies = kittens;
return d;
}

As you can see, they don't match that well, so some fields were inconvertible, and some data had to be made from scratch. Notice, that numberOfLives and Balance were not converted, and barkVolume was completely new data. If you have 2 Classes, that match perfectly, then hurray, but it rarely happens.
conversion can now be called from where ever you need:
 

Cat c = new Cat(Color.black, 9, 20, 40);
Dog d = c.toDog(50);

Thanks for reading.

 

Looking for some more related topics?

About casting/downcasting

Polymorphism help ..!!

Inherritance or Interfaces

 

 

Attached Thumbnails

  • arrayf.png
  • pointer.png
  • upcast downcast.jpg

  • 12


#505205 Java: Word Counter

Posted by Sinipull on 02 September 2009 - 03:48 AM

You should write it as a function, so it could be easily integrated into a program. Anyway, i tried it too, i hope you don't mind if i add it here.

    public static int count(String s){    	    	
    	for(int i = 0; i < s.length(); i++){
    		if(!(checkChar(s.substring(i, i+1)) || checkApostrophesDashes(s.substring(i, i+1)))){    			
    			s = s.replace(s.substring(i, i+1), " ");
    		}    		
    	}
    	String str[] = s.split(" ");    	
    	int count = 0;
    	for(int i =0; i <str.length; i++){
    		if(!str[i].equals("") && !checkApostrophesDashes(str[i])) count++;
    	}
    	return count;
    }
    
    public static boolean checkChar(String c){ // expecting only 1 character
    	if(!c.toUpperCase().equals(c) || !c.toLowerCase().equals(c)) return true; // it's a char
    	else return false; // it's not a char
    }
    
    public static boolean checkApostrophesDashes(String c){ // expecting only 1 character
    	if(c.equals("'") || c.equals("-")) return true; // it's dash or apostrophe
    	else return false;
    }

  • 1


#496013 Java: Random Name Generator

Posted by Sinipull on 05 August 2009 - 04:43 AM

Description: This class generates random names from syllables, and provides programmer a simple way to set a group of rules for generator to avoid unpronounceable and bizarre names.

SYLLABLE FILE REQUIREMENTS/FORMAT:
1) all syllables are separated by line break.
2) Syllable should not contain or start with whitespace, as this character is ignored and only first part of the syllable is read.
3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results.
4) Empty lines are ignored.

SYLLABLE CLASSIFICATION:
Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix.
To declare syllable a prefix in the file, insert "-" as a first character of the line.
To declare syllable a suffix in the file, insert "+" as a first character of the line.
everything else is read as middle part.

NUMBER OF SYLLABLES:
Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix.
In case of 1 syllable, name will be chosen from amongst the prefixes.
In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix.

ASSIGNING RULES:

I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important.

RULES:

1) +v means that next syllable must definitely start with a wovel.
2) +c means that next syllable must definitely start with a consonant.
3) -v means that this syllable can only added to another syllable, that ends with a wovel.
4) -c means that this syllable can only added to another syllable, that ends with a consonant.
So, our example: "aad +v -c" means that "aad" can only be after consonant and next syllable must start with wovel.
Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only wovels, which will be detected and RuntimeException will be thrown.

TO START:
Create a new NameGenerator object, provide the syllable file, and create names using compose() method.

EXAMPLE SYLLABLE FILE (Roman Names):
-a
-al
-au +c
-an
-ba
-be
-bi
-br +v
-da
-di
-do
-du
-e
-eu +c
-fa
bi
be
bo
bu
nul +v
gu
da
au +c -c
fri
gus
+tus
+lus
+lius
+nus
+es
+ius -c
+cus
+tor
+cio
+tin
and results:

Aubicio
Bebecus
Batin
Baes
Alboes
Dubilius
Banus
Alcus
Beguslius
Dinules
Dubecio
Beguses
Belus
Bibinus
Dibilius
Dacus
Antin
Braulius
Dobotor
Eucio
Dutus
EXAMPLE SYLLABLE FILE (Elven Names):
-Ael
-Aer
-af
-ah
-am
-ama
-an
-ang +v
-ansr +v
-cael
-dae +c
-dho
-eir
-fi
-fir
-la
-seh
-sel
-ev
-fis
-hu
-ha
-gar
-gil
-ka
-kan
-ya
-za
-zy
-mara
-mai +c
-lue +c
-ny
-she
-sum
-syl
ae +c -c
ael -c
dar
deth +v
dre -v
drim -v
dul
ean -c
el
emar
hal
iat -c
mah
ten
que -v +c
ria
rail
ther
thus
thi
san
+ael -c
+dar
+deth
+dre
+drim
+dul
+ean -c
+el
+emar
+nes
+nin
+oth
+hal
+iat
+mah
+ten
+ther
+thus
+thi
+ran
+ath
+ess
+san
+yth
+las
+lian
+evar
and results:
Amaelran
Kaemaroth
Shedul
Kathi
Aftenlas
Ansraellas
Angevar
Aerten
Caeltennes
Ladreevar
Aerlas
Evel
Maiquelian
Evraildar
Ahlas
Zyran
Ahsanten
Shethernes
Sylsan
Sheran
Hutenmah
Fimahlian
Nyoth
Kanael
Luedullian
Fiemardeth
Syldul
Seldar
And here's the code. Enjoy :)
package ee.joonas;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

/**
 * This class is released under GNU general public license
 * 
 * Description: This class generates random names from syllables, and provides programmer a 
 * simple way to set a group of rules for generator to avoid unpronounceable and bizarre names. 
 * 
 * SYLLABLE FILE REQUIREMENTS/FORMAT: 
 * 1) all syllables are separated by line break. 
 * 2) Syllable should not contain or start with whitespace, as this character is ignored and only first part of the syllable is read. 
 * 3) + and - characters are used to set rules, and using them in other way, may result in unpredictable results.
 * 4) Empty lines are ignored.
 * 
 * SYLLABLE CLASSIFICATION:
 * Name is usually composed from 3 different class of syllables, which include prefix, middle part and suffix. 
 * To declare syllable as a prefix in the file, insert "-" as a first character of the line.  
 * To declare syllable as a suffix in the file, insert "+" as a first character of the line.  
 * everything else is read as a middle part.
 * 
 * NUMBER OF SYLLABLES: 
 * Names may have any positive number of syllables. In case of 2 syllables, name will be composed from prefix and suffix. 
 * In case of 1 syllable, name will be chosen from amongst the prefixes.
 * In case of 3 and more syllables, name will begin with prefix, is filled with middle parts and ended with suffix.
 * 
 * ASSIGNING RULES:
 * I included a way to set 4 kind of rules for every syllable. To add rules to the syllables, write them right after the 
 * syllable and SEPARATE WITH WHITESPACE. (example: "aad +v -c"). The order of rules is not important.
 * 
 * RULES:
 * 1) +v means that next syllable must definitely start with a Vowel.
 * 2) +c means that next syllable must definitely start with a consonant.
 * 3) -v means that this syllable can only be added to another syllable, that ends with a Vowel.
 * 4) -c means that this syllable can only be added to another syllable, that ends with a consonant.
 * So, our example: "aad +v -c" means that "aad" can only be after consonant and next syllable must start with Vowel.
 * Beware of creating logical mistakes, like providing only syllables ending with consonants, but expecting only Vowels, which will be detected 
 * and RuntimeException will be thrown.
 * 
 * TO START:
 * Create a new NameGenerator object, provide the syllable file, and create names using compose() method.
 * 
 *
 */
public class NameGenerator {
    ArrayList<String> pre = new ArrayList<String>();
    ArrayList<String> mid = new ArrayList<String>();
    ArrayList<String> sur = new ArrayList<String>();
    
    final private static char[] Vowels = {'a', 'e', 'i', 'o', 'u', 'ä', 'ö', 'õ', 'ü', 'y'};
    final private static char[] consonants = {'b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p',    'q', 'r', 's', 't', 'v', 'w', 'x', 'y'};
    
    private String fileName;
    
    /**
     * Create new random name generator object. refresh() is automatically called.
     * @param fileName insert file name, where syllables are located
     * @throws IOException
     */
    public NameGenerator(String fileName) throws IOException{
        this.fileName = fileName;
        refresh();
    }
    
    /**
     * Change the file. refresh() is automatically called during the process.
     * @param fileName insert the file name, where syllables are located.
     * @throws IOException
     */
    public void changeFile(String fileName) throws IOException{
        if(fileName == null) throw new IOException("File name cannot be null");
        this.fileName = fileName;
        refresh();
    }
    
    /**
     * Refresh names from file. No need to call that method, if you are not changing the file during the operation of program, as this method
     * is called every time file name is changed or new NameGenerator object created.
     * @throws IOException
     */
    public void refresh() throws IOException{
        
        FileReader input = null;
        BufferedReader bufRead;
        String line;
        
        input = new FileReader(fileName);
        
        bufRead = new BufferedReader(input);
        line="";   
              
        while(line != null){        
            line = bufRead.readLine();        
            if(line != null && !line.equals("")){
                if(line.charAt(0) == '-'){
                    pre.add(line.substring(1).toLowerCase());                    
                }
                else if(line.charAt(0) == '+'){
                    sur.add(line.substring(1).toLowerCase());                    
                }
                else{ 
                    mid.add(line.toLowerCase());                    
                }
            }
        }        
        bufRead.close();
    }
        
    private String upper(String s){
        return s.substring(0,1).toUpperCase().concat(s.substring(1));
    }
    
    private boolean containsConsFirst(ArrayList<String> array){
        for(String s: array){
            if(consonantFirst(s)) return true;
        }
        return false;
    }
    
    private boolean containsVocFirst(ArrayList<String> array){
        for(String s: array){
            if(VowelFirst(s)) return true;
        }
        return false;
    }
    
    private boolean allowCons(ArrayList<String> array){
        for(String s: array){
            if(hatesPreviousVowels(s) || hatesPreviousConsonants(s) == false) return true;
        }
        return false;
    }
    
    private boolean allowVocs(ArrayList<String> array){
        for(String s: array){
            if(hatesPreviousConsonants(s) || hatesPreviousVowels(s) == false) return true;
        }
        return false;
    }
    
    private boolean expectsVowel(String s){
        if(s.substring(1).contains("+v")) return true;
        else return false;
    }
    private boolean expectsConsonant(String s){
        if(s.substring(1).contains("+c")) return true;
        else return false;        
    }
    private boolean hatesPreviousVowels(String s){
        if(s.substring(1).contains("-c")) return true;
        else return false;
    }
    private boolean hatesPreviousConsonants(String s){
        if(s.substring(1).contains("-v")) return true;
        else return false;        
    }    
    
    private String pureSyl(String s){
        s = s.trim();
        if(s.charAt(0) == '+' || s.charAt(0) == '-') s = s.substring(1);
        return s.split(" ")[0];
    }
    
    private boolean VowelFirst(String s){
        return (String.copyValueOf(Vowels).contains(String.valueOf(s.charAt(0)).toLowerCase()));        
    }
    
    private boolean consonantFirst(String s){
        return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(0)).toLowerCase()));        
    }
    
    private boolean VowelLast(String s){
        return (String.copyValueOf(Vowels).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase()));        
    }
    
    private boolean consonantLast(String s){
        return (String.copyValueOf(consonants).contains(String.valueOf(s.charAt(s.length()-1)).toLowerCase()));        
    }
    
    
    /**
     * Compose a new name.
     * @param syls The number of syllables used in name.
     * @return Returns composed name as a String
     * @throws RuntimeException when logical mistakes are detected inside chosen file, and program is unable to complete the name.
     */
    public String compose(int syls){
        if(syls > 2 && mid.size() == 0) throw new RuntimeException("You are trying to create a name with more than 3 parts, which requires middle parts, " +
                "which you have none in the file "+fileName+". You should add some. Every word, which doesn't have + or - for a prefix is counted as a middle part.");
        if(pre.size() == 0) throw new RuntimeException("You have no prefixes to start creating a name. add some and use \"-\" prefix, to identify it as a prefix for a name. (example: -asd)");
        if(sur.size() == 0) throw new RuntimeException("You have no suffixes to end a name. add some and use \"+\" prefix, to identify it as a suffix for a name. (example: +asd)");
        if(syls < 1) throw new RuntimeException("compose(int syls) can't have less than 1 syllable");
        int expecting = 0; // 1 for Vowel, 2 for consonant
        int last = 0; // 1 for Vowel, 2 for consonant
        String name;
        int a = (int)(Math.random() * pre.size());
        
        if(VowelLast(pureSyl(pre.get(a)))) last = 1;
        else last = 2;
        
        if(syls > 2){
            if(expectsVowel(pre.get(a))){ 
                expecting = 1;                
                if(containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with Vowel, " +
                        "but there is none. You should add one, or remove requirement for one.. "); 
            }
            if(expectsConsonant(pre.get(a))){ 
                expecting = 2;                
                if(containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. "); 
            }
        }
        else{
            if(expectsVowel(pre.get(a))){ 
                expecting = 1;                
                if(containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with Vowel, " +
                        "but there is none. You should add one, or remove requirement for one.. "); 
            }
            if(expectsConsonant(pre.get(a))){ 
                expecting = 2;                
                if(containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. "); 
            }
        }
        if(VowelLast(pureSyl(pre.get(a))) && allowVocs(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a Vowel, " +
        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" +
        "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all.");
        
        if(consonantLast(pureSyl(pre.get(a))) && allowCons(mid) == false) throw new RuntimeException("Expecting \"middle\" part that allows last character of prefix to be a consonant, " +
        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the prefix used, was : \""+pre.get(a)+"\", which" +
        "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all.");
        
        int b[] = new int[syls];
        for(int i = 0; i<b.length-2; i++){
                        
            do{
                b[i] = (int)(Math.random() * mid.size());
                //System.out.println("exp " +expecting+" VowelF:"+VowelFirst(mid.get(b[i]))+" syl: "+mid.get(b[i]));
            }            
            while(expecting == 1 && VowelFirst(pureSyl(mid.get(b[i]))) == false || expecting == 2 && consonantFirst(pureSyl(mid.get(b[i]))) == false 
                    || last == 1 && hatesPreviousVowels(mid.get(b[i])) || last == 2 && hatesPreviousConsonants(mid.get(b[i])));
            
            expecting = 0;
            if(expectsVowel(mid.get(b[i]))){ 
                expecting = 1;                
                if(i < b.length-3 && containsVocFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with Vowel, " +
                        "but there is none. You should add one, or remove requirement for one.. "); 
                if(i == b.length-3 && containsVocFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with Vowel, " +
                "but there is none. You should add one, or remove requirement for one.. "); 
            }
            if(expectsConsonant(mid.get(b[i]))){ 
                expecting = 2;                
                if(i < b.length-3 && containsConsFirst(mid) == false) throw new RuntimeException("Expecting \"middle\" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. "); 
                if(i == b.length-3 && containsConsFirst(sur) == false) throw new RuntimeException("Expecting \"suffix\" part starting with consonant, " +
                "but there is none. You should add one, or remove requirement for one.. "); 
            }
            if(VowelLast(pureSyl(mid.get(b[i]))) && allowVocs(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a Vowel, " +
                    "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +
                    "means there should be a part available, that has \"-v\" requirement or no requirements for previous syllables at all."); 
                    
            if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(mid) == false && syls > 3) throw new RuntimeException("Expecting \"middle\" part that allows last character of last syllable to be a consonant, " +
                    "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +
                    "means there should be a part available, that has \"-c\" requirement or no requirements for previous syllables at all.");
            if(i == b.length-3){                
                if(VowelLast(pureSyl(mid.get(b[i]))) && allowVocs(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a Vowel, " +
                        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +
                        "means there should be a suffix available, that has \"-v\" requirement or no requirements for previous syllables at all."); 
                        
                if(consonantLast(pureSyl(mid.get(b[i]))) && allowCons(sur) == false) throw new RuntimeException("Expecting \"suffix\" part that allows last character of last syllable to be a consonant, " +
                        "but there is none. You should add one, or remove requirements that cannot be fulfilled.. the part used, was : \""+mid.get(b[i])+"\", which " +
                        "means there should be a suffix available, that has \"-c\" requirement or no requirements for previous syllables at all.");
            }
            if(VowelLast(pureSyl(mid.get(b[i])))) last = 1;
            else last = 2;
        }        
        
        int c;
        do{
            c = (int)(Math.random() * sur.size());                    
        }            
        while(expecting == 1 && VowelFirst(pureSyl(sur.get(c))) == false || expecting == 2 && consonantFirst(pureSyl(sur.get(c))) == false 
                || last == 1 && hatesPreviousVowels(sur.get(c)) || last == 2 && hatesPreviousConsonants(sur.get(c)));
        
        name = upper(pureSyl(pre.get(a).toLowerCase()));        
        for(int i = 0; i<b.length-2; i++){
            name = name.concat(pureSyl(mid.get(b[i]).toLowerCase()));            
        }
        if(syls > 1)
            name = name.concat(pureSyl(sur.get(c).toLowerCase()));
        return name;        
    }    
}
Download:
UPLOAD.EE - Download NameGenerator.java

EDIT: Fixed a bug, that caused program to think suffixes and prefixes starting with c or v were rules.
  • 1


#479987 deleteRepeats() method in a char array

Posted by Sinipull on 05 July 2009 - 05:19 AM

I think i finally understood what you want.

public class Test {
    
    public static void main(String[] args) {
    	
    	char [] a=new char[10];
    	a[0]='a';
    	a[1]='b';
    	a[2]='c';
    	a[3]='c';
    	a[4]='c';
    	a[5]='d';

    	
    	
    	int newSize=deleteRepeats(a, 3);
    	System.out.println(newSize);
    	
    	
    }
    
    public static int deleteRepeats(char[]array, int size){
    	int count=0;
    	
    	char arrayTemp[] = new char[array.length];

    	// lets make a copy of the array, so we won't change it.
    	for(int i=0; i<size; i++){
    		arrayTemp[i] = array[i];
    	}
    	
    	
    	//clear all slots with repeating chars
    	for(int i=0; i<size; i++){
    		for(int j=i+1; j<size; j++){
    			if(arrayTemp[j] == arrayTemp[i]) arrayTemp[j] = 0;
    		}
    	}
    	
    	//lets "cut" the caps inside of the array
    	char [] a=new char[arrayTemp.length];
    	int charcount=0;
    	for(int i=0; i<size; i++){
    		if(arrayTemp[i] != 0){
    			a[charcount] = arrayTemp[i];
    			charcount++;
    		}
    	}
    	for(int i=0; i<arrayTemp.length; i++){
    		arrayTemp[i] = a[i];    		
    	}
    	
    	
    	// count the chars left
    	for(int i=0; i<size; i++){
    		if(arrayTemp[i] != 0 ) count++;
    	}
    	
    	return count;	
    }
}

  • -1


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