Converting multiple strings into one - java

I'm trying to convert multiple strings into one simple dialogue from a NPC. Basically what I'm trying to do is make a list of all the skills a player has 200M experience in and output it into a NPC dialogue.
OLD
if (componentId == OPTION_4) {
sendNPCDialogue(npcId, 9827, "You can prestige: "+maxedSkills()+"");
}
private String maxedSkills() {
return ""+attackMax()+""+strengthMax()+""+defenceMax()+"";
}
public String attackMax() {
if (player.getSkills().getXp(Skills.ATTACK) == 200000000)
return "Attack, ";
else
return "";
}
public String strengthMax() {
if (player.getSkills().getXp(Skills.STRENGTH) == 200000000)
return "Strength, ";
else
return "";
}
public String defenceMax() {
if (player.getSkills().getXp(Skills.DEFENCE) == 200000000)
return "Defence, ";
else
return "";
}
With that code I have it working, but that is a lot of code to add due to there being 25 different skills. How would I create a way to make all of the skills be referenced into one? Here are all of the skill names:
public static final String[] SKILL_NAME = { "Attack", "Defence", "Strength", "Constitution", "Ranged", "Prayer",
"Magic", "Cooking", "Woodcutting", "Fletching", "Fishing", "Firemaking", "Crafting", "Smithing", "Mining",
"Herblore", "Agility", "Thieving", "Slayer", "Farming", "Runecrafting", "Hunter", "Construction",
"Summoning", "Dungeoneering" };
New and working (for attack/strength/defence):
public static final int[] SKILL_TYPE = {Skills.ATTACK, Skills.STRENGTH, Skills.DEFENCE};
public String maxedSkills() {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < SKILL_TYPE.length; i++) {
if (player.getSkills().getXp(i) == 200000000) {
if(sb.length()>0) sb.append(", ");
sb.append(Skills.SKILL_NAME[i]);
}
}
if(sb.length()>0) sb.append(".");
return sb.toString();
}

Simplest way would be to have a parameteried method that takes the Skill type as input. Here is how it would look like:
public String skillMax(Skills skill) {
if (player.getSkills().getXp(skill) == 200000000)
return skill.getName() + ", ";
else
return "";
}
The next thing to do is to provide a name to the skill in Skills enum. Something like this should work:
public enum Skills {
DEFENSE("Defense"), ...;
private String name;
Skills(String name) { this.name = name; }
String getName() { return this.name; }
}

Use a StringBuffer (thread safe) or a StringBuilder and do something like this.
....
public static final Skills[] SKILL_TYPE = {Skills.Attack, Skills.Defence, ...};
public String getBigString() {
StringBuffer sb = new StringBuffer();
int nSkills = 0, lSkill = 0;
for( int i = 0; i < SKILL_TYPE.length; i++ )
{
if( player.getSkills().getXp(SKILL_TYPE[i]) == K_SOMELEVEL ) {
if(nSkills > 0) sb.append(", ");
lSkill = sb.length(); // track position of last skill in string
nSkills += 1;
sb.append(SKILL_NAME[i]);
}
}
if( nSkills > 0 )
{
if( nSkills > 1 ) sb.insert( lSkill, "and ");
sb.append(".");
}
return sb.toString();
}

Related

how to select players join the game and start a game

I am a beginner in Java, and I've been creating a practicing project for a game. For this purpose, I've already put some features in this project, and I separate the entire project into three files: Nimsys, NimPlayer, NimGame.
I've created these features.
addplayer into playerList in the NimPlayer.
removeplayer
editplayer
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
What I did was trying to store the user data (addplayer) from the prompt input, and brought the game to be played (last part of the incomplete code).
import java.util.Scanner;
public class Nimsys {
public static String[] splitName(String inName) {
String[] splittedLine = inName.split(",");
String[] name = null;
if (splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
name = new String[3];
name[0] = userName;
name[1] = familyName;
name[2] = givenName;
}
return name;
}
public static String [] splitData(String dataIn) {
String[] splittedLine = dataIn.split(",");
String[] data = null;
if (splittedLine.length==4) {
String initialStone = splittedLine[0];
String stoneRemoval = splittedLine[1];
String player1 = splittedLine[2].trim();
String player2 = splittedLine[3].trim();
data = new String[4];
data[0] = initialStone;
data[1] = stoneRemoval;
data[2] = player1;
data[3] = player2;
}
return data;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (true) {
System.out.print('$');
String commandin = in.next();
if (commandin.equals("addplayer")) {
String inName = in.nextLine();
String[] name = splitName(inName);
//Make sure the vadality of in name
if (name!=null && name.length==3) {
for (int i = 0; i < NimPlayer.getId(); i ++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName();
if (userCheck.contains(name[0])) {
System.out.println("The player already exist");//Test if player has been created
}
}
NimPlayer.createPlayer(name[0], name[1], name[2]);
System.out.println("The player has been created.");
} else {
System.out.println("Not Valid! Please enter again!");
}
}
if (commandin.equals("removeplayer")) {
//cannot loop through the entire null array, would be NullPointerException
String removeUserName = in.nextLine().trim();
/*System.out.println("Are you sure you want to remove all players? (y/n) \n");
//System.out.print('$');
commandin = in.next();
if (commandin.equals("y")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove all the players");
}
} else {
System.out.print('$');
}*/
//commandin = in.next();
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName().trim();
if (removeUserName != null && userName.equals(removeUserName)) {
NimPlayer.getPlayer()[i] = null;
System.out.println("Remove successfully!");// A test to see if the code runs
} else {
System.out.println("The player does not exist");
}
}
}
if (commandin.equals("editplayer")) {
String inName = in.nextLine();
String[] splittedLine = inName.split(",");
if (splittedLine!=null && splittedLine.length==3) {
String userName = splittedLine[0].trim();
String familyName = splittedLine[1].trim();
String givenName = splittedLine[2].trim();
//System.out.println(userName+","+familyName+","+givenName);//Test if in name in the if loop
for (int i = 0; i < NimPlayer.getId(); i++) {
String userCheck = NimPlayer.getPlayer()[i].getUserName().trim();
if (userName != null && userCheck.equals(userName)) {
NimPlayer.getPlayer()[i].setFamilyName(familyName);
NimPlayer.getPlayer()[i].setGivenName(givenName);
System.out.println("Edit successfully");
} else {
System.out.println("The player does not exist.");
}
}
} else {
System.out.println("Invalid in! Please enter again.");
}
}
if (commandin.equals("displayplayer")) {
for (int i = 0; i < NimPlayer.getId(); i++) {
String userName = NimPlayer.getPlayer()[i].getUserName();
String familyName = NimPlayer.getPlayer()[i].getfamilyName();
String givenName = NimPlayer.getPlayer()[i].getGivenName();
System.out.println(userName+","+familyName+""+givenName);
}
}
if (commandin.equals("startgame")) {
String dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data.length==4 && data !=null) {
for (int i = 0; i < NimPlayer.getId(); i++) {
for (int j = i + 1; j < NimPlayer.getId(); j++) {
String player1 = NimPlayer.getPlayer()[i].getUserName();
String player2 = NimPlayer.getPlayer()[j].getUserName();
if (player1==null || player2==null) {
System.out.println("One of the players does not exist. Please enter again");
} else {
System.out.println("Data built successfully.Game starts!");
break;
}
}
}
dataIn = in.nextLine();
}
int dataStone = Integer.parseInt(data[0]);
int dataRemoval = Integer.parseInt(data[1]);
}
}}
//username, given name, family name, number of game played, number of games won
public class NimPlayer {
private String userName;
private String familyName;
private String givenName;
static NimPlayer[] playerList = new NimPlayer[10]; // set an array here
static int id;
//define NimPlayer data type
public NimPlayer(String userName,String surName, String givenName) {
this.userName = userName;
this.familyName = surName;
this.givenName = givenName;
}
// create new data using NimPlayer data type
public static void createPlayer(String userName, String familyName, String givenName) {
if (id<10) {
playerList[id++] = new NimPlayer(userName, familyName, givenName);
} else {
System.out.println("Cannot add more players.");
}
}
public static int getId() {
return id;
}
public static NimPlayer [] getPlayer() {
return playerList;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getUserName() {
return userName;
}
public String getfamilyName() {
return familyName;
}
public String getGivenName() {
return givenName;
}
}
Above are my Nimsys and NimPlayers class. So far, I have a question:
Is it wrong to manipulate the players in the Nimplayer?
Or it is better to create an object in Nimsys if I want to store the record and the times game played?
public class NimGame {
int stoneBalance;
int stars;
public int initializeStone(int startStones) {
stoneBalance = startStones;
return stoneBalance;
}
public void removeStones(int stonesTaken) {
int updatedBalance = stoneBalance - stonesTaken;
stoneBalance = updatedBalance;
}
public void printStar(int star) {
stars = star;
stars = stoneBalance;
for (int stars = 1; stars <= star; stars++) {
System.out.print(" *");
}
System.out.println();
}
Scanner in = new Scanner(System.in);
String playOrNot;
do {
System.out.println("Initial stone count: "+datastone);
System.out.println("Maximum stone removal: "+dataRemoval);
System.out.println("Player 1: "+player1.getUserName());
System.out.println("Player 2: "+player2.getUserName());
// while stoneBalance > 0, two players keep playing the game
while (stoneBalance > 0) {
System.out.print(initialStone + " stones left:");
printStar(initialStone);
// player1's turn and remove the stones; decision of winning
System.out.println(player1 + "'s turn - remove how many?\n");
int takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper "+
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone); //remove the stone
if (stoneBalance > 0) {
//show the remaining stones
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player2 + " wins!\n");
break;
}
// player2's turn and remove the stones; decision of winning
System.out.println(player2 + "'s turn - remove how many?\n");
takeStone = in.nextInt();
while (takeStone > dataRemoval || takeStone <= 0) {
System.out.println(
"Invalid, you need to remove stones under upper " +
"bound limit or above 0. \n Please enter again.");
takeStone = in.nextInt();
}
removeStones(takeStone);
if (stoneBalance > 0) {
System.out.print(stoneBalance + " stones left:");
printStar(stoneBalance);
} else if (stoneBalance <= 0) {
System.out.println("Game Over\n" + player1 + " wins!\n");
break;
}
}
// ask players to play again
in.nextLine();
System.out.println("Do you want to play again (Y/N):");
playOrNot = in.nextLine();
} while (playOrNot.equals("Y"));
}
And this above is my NimGame class. It's the process of the classical Nim game. What should I do to introduce the player? What I did in Nimsys is only to check if players are inside the playerList.
Thanks for taking the time to review my code. Any help is highly appreciated!
On a side note (because it won't affect the execution of the program), the name of an identifier should be self-explanatory e.g. your getPlayer method should be named as getPlayerList as it is returning the playerList, not a single player.
Your logic for startgame should be as follows:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[2])) {// Checking player1
player1 = players[i].getUserName();
break;
}
}
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(data[3])) {// Checking player2
player2 = players[i].getUserName();
break;
}
}
}
} while(player1 == null || player2 == null)
//...
}
You can put the repeated code in a function to make your program modular e.g.
String findPlayerByName(String name){
String player = null;
NimPlayer[] players = NimPlayer.getPlayerList();
for (int i = 0; i < players.length; i++) {
if(players[i].getUserName().equals(name)) {
player = players[i].getUserName();
break;
}
}
return player;
}
Then, the logic for startgame will reduce to:
if (commandin.equals("startgame")) {
String dataIn = null, player1 = null, player2 = null;
do {
dataIn = in.nextLine();
String [] data = splitData(dataIn);
//Check if player in the array
if (data !=null && data.length==4) {
player1 = findPlayerByName(data[2]);
player2 = findPlayerByName(data[3]);
}
} while(player1 == null || player2 == null)
//...
}
Another thing I would like you to understand is the problem with the following line:
if (data.length==4 && data !=null)
It should be
if (data !=null && data.length==4)
This way, if data is null, the condition, data.length==4 will not be checked because && operator allows to proceed further only if the condition on its left side evaluates to true.
The problem with your line is that if data is null, you will get the NullPointerException because you will be checking .length on a null reference.
Now, I want two of the players to join the game, and do the following:
Score record
The times the player has played.
Currently, you have userName, familyName, and givenName attributes in NimPlayer class. You need to create two more attributes, private int score and private int numbersOfGamesPlayed with their public getters and setters. You need to use these attributes to store the value of score and the numbers of time a player has played the game.

Compare RDD Objects - Apache Spark

I'm fairly new into the apache spark technology and I'm having some problems while trying to analyze data I'm pulling from my files.
I have big list of genes information, and I'm pulling that information to a RDD, so far so good.
JavaRDD<Gene> inputfile = sc.textFile(logFile).map(
new Function<String, Gene>() {
#Override
public Gene call(String line) throws Exception {
String[] values = line.split("\t");
Gene gen = null;
//We are only interested in genes;
if( values.length > 2 && values[2].equalsIgnoreCase("gene") && !line.contains("#")){
String[] infoGene = values[8].split(";");
String geneId = StringUtils.substringBetween(infoGene[0], "\"");
String geneType = StringUtils.substringBetween(infoGene[2], "\"");
String geneName = StringUtils.substringBetween(infoGene[4], "\"");
gen = new Gene(geneName,values[3],values[4]);
return gen;
}
return gen;
}
}
).filter(new Function<Gene, Boolean>() {
#Override
public Boolean call(Gene gene) throws Exception {
if(gene == null)
return false;
else
return true;
}
});
The Gene class:
public class Gene implements Serializable{
String firstBp;
String lastBp;
String name;
public Gene(String name, String firstBp, String lastBp) {
this.name = name;
this.firstBp = firstBp;
this.lastBp = lastBp;
}
public String getFirstBp() {
return firstBp;
}
public String getLastBp() {
return lastBp;
}
public String getName() {
return name;
}
public String toString(){
return name + " " + firstBp + " " + lastBp;
}}
The problem starts here, I need to analyze if 2 Genes overlay, and for that I've made this simple utility function:
public static Boolean isOverlay(Gene gene1, Gene gene2){
int gene1First = Integer.parseInt(gene1.getFirstBp());
int gene1Last = Integer.parseInt(gene1.getLastBp());
int gene2First = Integer.parseInt(gene2.getFirstBp());
int gene2Last = Integer.parseInt(gene2.getLastBp());
if(gene2First >= gene1First && gene2First <= gene1Last) // FirstBp - Gene2 inside
return true;
else if (gene2Last >= gene1First && gene2Last <= gene1Last) // LastBP - Gene2 inside
return true;
else if (gene1First >= gene2First && gene1First <= gene2Last) // FirstBp - Gene1 inside
return true;
else if (gene1Last >= gene2First && gene1Last <= gene2Last) // LastBP - Gene1 inside
return true;
else
return false;
}
Now what I'm doing and I think is wrong is transforming the RDD Object into a list by doing:
List<Gene> genesList = inputfile.collect();
And iterate over that list to check if there are overlays and save to the file the results which is taking ages because I'm not using spark.
List<OverlayPair> overlayPairList= new ArrayList<OverlayPair>();
List<String> visitedGenes = new ArrayList<String>();
for (Gene gene1 : genesList){
for (Gene gene2 : genesList) {
if (gene1.getName().equalsIgnoreCase(gene2.getName()) || visitedGenes.contains(gene2.getName())) {
continue;
}
if (isOverlay(gene1, gene2))
overlayPairList.add(new OverlayPair(gene1.getName(), gene2.getName()));
}
visitedGenes.add(gene1.getName());
}
JavaRDD<OverlayPair> overlayFile = sc.parallelize(overlayPairList);
//Export the results to the file
String outputDirectory = "/Users/joaoalmeida/Desktop/Dissertacao/sol/data/mitocondrias/feup-pp/project/data/output/overlays";
overlayFile.coalesce(1).saveAsTextFile(outputDirectory);
The Overlay pair is basically an object with the 2 genes name.
Is there anyway to do this 2nd part while taking advantage of spark? Because the time complexity of those 2 for's its to big for the amount of data I currently have.
Yes, there is, you have to use RDD.cartesian function to get all the pairs and then you can basically apply the function you wrote.

Java NoSuchMethodError

I am trying to understand stacks with Objects, so I typed this out, but the problem is that I am getting this really weird message that I can't make sense of. It says "Exception in thread "main" java.lang.NoSuchMethodError: Stack.push(Ljava/lang/Object;)V
at TestObjectStack.main(TestObjectStack.java:12)". I googled it, but I still can't figure out what I'm doing wrong. I redid the main method header, but that didn't fix it. Does anyone have any suggestions or insight that I am missing? Thanks a lot!:
public class TestObjectStack
{
public static void main(String[] args)
{
Object o;
Stack test = new Stack();
test.push("Fred");
test.push(20);
test.push(new ThingB("Barney", 42));
Stack copy = new Stack(test);
System.out.println("Stack test: " + test);
System.out.println(test.pop());
System.out.println("Stack test: " + test);
System.out.println("Stack copy: " + copy);
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a String");
if(test.isEmpty()) System.out.println("Empty");
o = test.pop();
System.out.println(o);
if(o instanceof String)
{
String s = (String) o;
System.out.println("String length = " + s.length());
}
else
System.out.println("Not a string");
if(test.isEmpty()) System.out.println("empty");
}
}
class ThingB
{
private String _name;
private int _ID;
public ThingB(String name, int ID)
{
_name = name;
_ID = ID;
}
public String toString()
{
return "Thing B - name - " + _name + " ID = " + _ID;
}
}
class Stack
{
private Object[] _store;
private int _top;
private static final int MAXSIZE = 50;
public Stack()
{
_store = new Object[MAXSIZE];
_top = 0;
}
public Stack(Stack other)
{
_store = new Object[other._store.length];
_top = other._top;
for(int i = 0; i < _top; ++i)
{
_store[i] = other._store[i];
}
}
public boolean isEmpty()
{
return (_top == 0);
}
public void push(Object item)
{
if(_top >= _store.length)
{
Object[] temp = new Object[_store.length+ MAXSIZE];
for(int i = 0; i < _top; ++i)
{
temp[i] = _store[i];
}
_store = temp;
}
_store[_top] = item;
++_top;
}
public Object pop()
{
if(_top == 0) return 0;
--_top;
return _store[_top];
}
public String toString()
{
String s = "";
s = s + "--Top--";
for(int i = _top-1; i >= 0; --i)
{
s = s + " " + _store[i];
}
s = s + "--Bottom--";
return s;
}
}
I executed your code in the IDE: IntelliJ IDEA. And I have the following result:
Stack test: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
Thing B - name - Barney ID = 42
Stack test: --Top-- 20 Fred--Bottom--
Stack copy: --Top-- Thing B - name - Barney ID = 42 20 Fred--Bottom--
20
Not a String
Fred
String length = 4
empty
Your source code is working fine, maybe you need to adjust your IDE parameters. Try with a simple "Hello World" program.
Best regards,
Alvaro

"Duplicate" entries in ArrayList?

i have this class thats going to fill a list with All employees that are pre made in an array. I can populate an ArrayList with employees but the only problem is that i get a few "Duplicate" entries, i use quotes cause they are not EXACTLY the same but they could share the same name or employee number but may not have the same hire year or salary ect.
heres the employee class :
public class Employee {
public String EmployeeName;
public String EmployeeNumber;
public int hireyear;
public double WeeklyEarning;
public Employee()
{
EmployeeName = null;
EmployeeNumber = null;
hireyear = 0;
WeeklyEarning = 0;
}
public static final String[] Empnum = new String[] {
"0001-A", "0002-B","0003-C","0004-D","0002-A",
"0003-B","0004-C","0005-D","0011-A", "0012-B",
"0013-C","0014-D","0121-A", "0122-B","0123-C",
"0321-A", "0312-B","1234-D","4321-C","1122-D"};
public static final String[] Ename = new String[] {
"Josh", "Alex", "Paul", "Jimmy", "Josh", "Gordan", "Neil", "Bob",
"Shiv", "James", "Jay", "Chris", "Michael", "Andrew", "Stuart",
"Dave","Benjamin","Dan","Brian","Michelle"};
public String getEmployeeName()
{
return this.EmployeeName;
}
public String getEmployeeNumber()
{
return this.EmployeeNumber;
}
public int gethireyear()
{
return this.hireyear;
}
public double getWeeklyEarning()
{
return this.WeeklyEarning;
}
public String setEmployeeName(String EName)
{
return this.EmployeeName = EName;
}
public String setEmployeeNumber(String ENumber)
{
return this.EmployeeNumber = ENumber;
}
public int setEmployeehireyear(int Ehireyear)
{
return this.hireyear = Ehireyear;
}
public double setEmployeeweeklyearning(double Eweeklyearning)
{
return this.WeeklyEarning = Eweeklyearning;
}
public String toString(){
String data = "\n Employee Name : " + EmployeeName + " \n Employee Number: " + EmployeeNumber + " \n Hire Year : " + hireyear + "\n Weekly Earnings : " + WeeklyEarning;
return data;
}
public boolean equals(Object o){
if(this == null){
return false;
}
if(this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
Employee temp = (Employee) o;
if(this.getEmployeeName().equals(temp.getEmployeeName())){
return true;
}
if(this.getEmployeeNumber().equals(temp.getEmployeeNumber())){
return true;
}
if(this.gethireyear() == temp.gethireyear()){
return true;
}
if(this.getWeeklyEarning() == temp.getWeeklyEarning()){
return true;
}
return false;
}
}
Heres the generateList method that will populate the list:
public ArrayList<Employee> generateEmpList(){
empList = new ArrayList <Employee>();
Random empPicker = new Random();
for(int i = 0; i < 20; i++){
int id = empPicker.nextInt(20);
if(id < 12) // roll for production worker
{
//System.out.println("Adding Production Worker");
ProductionWorker temp = new ProductionWorker();
temp = temp.generateProductionWorker();
prodWorker = temp;
empList.add(prodWorker);
}
else //roll for Shift supervisor
{
//System.out.println("Adding Shift supervisor");
ShiftSupervisor supervisor = new ShiftSupervisor();
supervisor = supervisor.generateShiftSupervisor();
shiftWorker = supervisor;
empList.add(shiftWorker);
}
}
Iterator iterator = empList.iterator();
while (iterator.hasNext()) {
System.out.println("");
System.out.println(iterator.next());
}
return empList;
}
and also which could be helpful is the "generateProductionWorker()" and shiftSupervisor methods - to keep it short ill only post prod worker method cause they are basically the same:
public ProductionWorker generateProductionWorker(){
Random rng = new Random();
int numberOfEmployeeNames = Ename.length;
ProductionWorker tempPworker = new ProductionWorker();
String employeeName = Ename[rng.nextInt(numberOfEmployeeNames)];
tempPworker.setEmployeeName(employeeName);
int numberOfEmployeeNumbers = Empnum.length;
String employeeNumber = Empnum[rng.nextInt(numberOfEmployeeNumbers)];
tempPworker.setEmployeeNumber(employeeNumber);
int yearHired = rng.nextInt(35) + 1980;
tempPworker.setEmployeehireyear(yearHired);
double weeklySalary = rng.nextInt((100) * 100);
tempPworker.setEmployeeweeklyearning(weeklySalary);
int hourlyRate = rng.nextInt(20) + 10;
tempPworker.setHourlyRate(hourlyRate);
return tempPworker;
}
I'm sure I'm missing something trivial but any ideas why i get similar entries when i have a list of 20 names and numbers?
ex:
empname - josh
empnum - 0000-A
hireyear - 1994
salary - 40,000
empname - josh
empnum - 0000-A
hireyear - 1999
salary - 60,500
any advice would help, Thanks!
Look at the equals method in your Employee class. If their name are the same, you return true, which means these are equals. The same is for the other attributes. You must replace your if statements.
I agree with Georgi, you equals method is the culprit.
Currently it is returning true after the first if statement at the line that reads
if(this.getEmployeeName().equals(temp.getEmployeeName())){
return true;
}
Because it is a return statement it stops the method from continuing to the other statements. You might try this:
public boolean equals(Object o){
if(this == null){
return false;
}
if(this == o){
return true;
}
if(!(o instanceof Employee)){
return false;
}
//set all the elements in the array to false and change to true when true.
boolean [] doesItMatch = new boolean[4];
doesItMatch[0] = false;
doesItMatch[1] = false;
doesItMatch[2] = false;
doesItMatch[3] = false;
Employee temp = (Employee) o;
if(this.getEmployeeName().equals(temp.getEmployeeName())){
doesItMatch[0] = true;
}
if(this.getEmployeeNumber().equals(temp.getEmployeeNumber())){
doesItMatch[1] = true;
}
if(this.gethireyear() == temp.gethireyear()){
doesItMatch[2] = true;
}
if(this.getWeeklyEarning() == temp.getWeeklyEarning()){
doesItMatch[3] = true;
}
int check = 0;
//Now that you have checked all the values, check the array. Using a simple counter.
for(int i = 0; i < doesItMatch.length; i++){
if(doesItMatch[i]){
check++;
} else {
check--;
}
}
//The counter should be 4 when the if statements above are all true. Anything else is false.
if(check == 4){
return true;
} else {
return false;
}
}
This method now checks each of the attributes in the Employee class. (Name, Number, Hire year and so on. If you create more attributes to the class it is easy to add more elements to the array just be sure to set them to false.)
Hope this helps
This also would take a little maintenance if you expanded the Employee class so you might want to find a way to make it a little easier on yourself.

Checking a number range with regular expressions

I'm using a regular expression to validate a certain format in a string. This string will become a rule for a game.
Example: "DX 3" is OK according to the rule, but "DX 14" could be OK too... I know how to look at the string and find one or more "numbers", so the problem is that the regex will match 34 too, and this number is out of "range" for the rule...
Am I missing something about the regex to do this? Or is this not possible at all?
Unfortunately there's no easy way to define ranges in regex. If you are to use the range 1-23 you'll end up with a regex like this:
([1-9]|1[0-9]|2[0-3])
Explanation:
Either the value is 1-9
or the value starts with 1 and is followed with a 0-9
or the value starts with 2 and is followed with a 0-3
It is not that short, and not flexible.
If you search for 1 to 19, you can search for "DX 1?[0-9]", for example, but if it doesn't end at a number boundary, it get's ugly pretty soon, and changing the rules is not flexible.
Splitting the String at the blank, and then using x > 0 and x < 24 is better to understand and more flexible.
You can use following format for writing a regular expression solving your problem.
Suppose your range is 0-15.
"^DX [0-9]|1[0-5]$"
You can even make it dynamic depending on your range by appending strings.
package dev.dump;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Collections;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by IntelliJ IDEA. User: User Date: 28.09.2007 Time: 9:46:47 To change this template use
* File | Settings | File Templates.
*/
class NumberDiapasone2RegExp {
private static final String invalidArgumentEmpty="Invalid argument \"{0}\" was found! {1}";
private static final Pattern pattern=Pattern.compile("^(\\d+)-(\\d+)?$");
private String src;
private String result="";
private Long left;
private Long right;
private boolean transform09ToD;
public NumberDiapasone2RegExp(final String src) {
this(src, false);
}
public NumberDiapasone2RegExp(final String src, final boolean transform09ToD) {
this.transform09ToD=transform09ToD;
if (src==null || src.trim().length()==0)
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It cannot be empty."));
if (src.indexOf("-")<0)
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It is supposed to have \"-\"."));
if (src.indexOf("-")!=src.lastIndexOf("-"))
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It is supposed to have only one \"-\"."));
Matcher syntaxChecker=pattern.matcher(src);
if (!syntaxChecker.find()){
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"It is supposed to be in format \"##-##\"."));
}
this.src=src;
parseAndCheck();
String theSameDigits="";
//the same digit goes towards result
if (left.toString().length()==right.toString().length()){
for (int i=0; i<left.toString().length(); i++){
if (i<right.toString().length() &&
left.toString().charAt(i)==right.toString().charAt(i)){
theSameDigits+=left.toString().charAt(i);
}
}
if (theSameDigits.length()>0){
this.src=this.src.replaceFirst(Pattern.quote(theSameDigits),"");
this.src=this.src.replaceFirst(Pattern.quote("-"+theSameDigits),"-");
parseAndCheck();
}
}
result=glueParts(compact(transform09ToD, toParts()));
Matcher m=secondCompact.matcher(result);
while (m.find()){
result=m.group(1).replace("(","").replace(")","")+"["+m.group(2).replaceAll("[\\[\\]]","")+m.group(3).replaceAll("[\\[\\]]","")+"][0-9]";
m.reset(result);
}
//compact squares again
StringBuffer sb=new StringBuffer();
Pattern squresP=Pattern.compile("(\\[(\\d|-)+\\])");
m=squresP.matcher(result);
while (m.find()) {
m.appendReplacement(sb, Matcher.quoteReplacement(compactSquares(m.group(1))));
}
m.appendTail(sb);
result=sb.toString();
result=result.replaceAll("\\[(\\d)-\\1\\]","$1");
result=result.replaceAll("\\[(\\d)\\]","$1");
result=result.replace("{1}","").replace("{0,1}","?");
if (result.indexOf("|")>=0) result=theSameDigits+"("+result+")";
else result=theSameDigits+result;
if (result.startsWith("(") && result.endsWith(")")) result=result.substring(1, result.length()-1);
}
private static Pattern secondCompact=Pattern.compile("(.*)(\\[\\d-?\\d\\]|\\d)\\[0-9\\]\\|(\\[\\d-?\\d\\]|\\d)\\[0-9\\]");
static List<String> compact(boolean transform09ToD, String... parts) {
Set<String> unique=new HashSet<String>();
List<String> result=new ArrayList<String>();
for (String part : parts){
if (part==null || part.length()==0) continue;
part=compactSquares(part);
part=part.replaceAll("\\[(\\d)\\]","$1");
if (part.indexOf("[0-9]")>=0){
if (transform09ToD) part=part.replace("[0-9]","\\d");
}
//[0-3][0-9]|4[0-9]=>[0-34][0-9]
//[023][0-9]|4[0-9]=>[0234][0-9]
//[02345789]=>[02-57-9]
Matcher m=secondCompact.matcher(part);
if (m.find()){
part=m.group(1).replace("(","").replace(")","")+"["+m.group(2).replaceAll("[\\[\\]]","")+m.group(3).replaceAll("[\\[\\]]","")+"][0-9]";
}
part=part.replaceAll("\\[(\\d)-\\1\\]","$1");
if (unique.add(part)) result.add(part);
}
return result;
}
static String compactSquares(String src){
boolean inSquares=false;
if (src.startsWith("[") && src.endsWith("]")){
inSquares=true;
src=src.substring(1,src.length()-1);
}
StringBuffer sb=new StringBuffer();
if (!src.contains("-")) {
List<Integer> digits=new ArrayList<Integer>();
for (int i=0; i<src.length();i++){
digits.add(Integer.parseInt(""+src.charAt(i)));
}
Collections.sort(digits);
for (Integer s : digits){
sb.append(s);
}
src=sb.toString();
sb.setLength(0);
}
int firstChar = -2;
int lastChar = -2;
int currentChar;
for (int i=0; i<src.length(); i++) {
currentChar=src.charAt(i);
if (currentChar == lastChar + 1) {
lastChar = currentChar;
continue;
}
if (currentChar == '-' && i+1 < src.length()) {
lastChar = src.charAt(i + 1) - 1;
continue;
}
flush(sb, firstChar, lastChar);
firstChar = currentChar;
lastChar = currentChar;
}
flush(sb, firstChar, lastChar);
return (inSquares?"[":"")+sb.toString()+(inSquares?"]":"");
}
private static void flush(StringBuffer sb, int firstChar, int lastChar) {
if (lastChar<=0) return;
if (firstChar==lastChar) {
sb.append((char)firstChar);
return;
}
if (firstChar+1==lastChar){
sb.append((char)firstChar);
sb.append((char)lastChar);
return;
}
sb.append((char)firstChar);
sb.append('-');
sb.append((char)lastChar);
}
static String glueParts(List<String> parts) {
if (parts==null || parts.isEmpty()) return "";
if (parts.size()==1) return parts.get(0);
StringBuilder result=new StringBuilder(128);
for (String part : parts){
result.append(part);
result.append("|");
}
result.deleteCharAt(result.length()-1);
return result.toString();
}
private String[] toParts() {
List<String> result=new ArrayList<String>();
if (getNumberOfDigits(left)>2 || getNumberOfDigits(right)>2) {
result.add(startPart(left));
}
long leftPart=left;
long rightPart=right;
if (!String.valueOf(left).matches("10*")) leftPart=toPower(left);
if (!String.valueOf(right).matches("10*")) rightPart=toPower(right)/10;
if (rightPart/leftPart>=10) {
result.add(speedUpPart(left, right));
}
//for 1-2 digit process
if (getNumberOfDigits(left)==1 && getNumberOfDigits(right)==1){
result.add("["+left+"-"+right+"]");
}
else if (getNumberOfDigits(left)==1 && getNumberOfDigits(right)==2){
if (0==Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (1==Integer.parseInt(getMajorDigit(right))) {
result.add("["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (2<=Integer.parseInt(getMajorDigit(right))) {
result.add("["+
getMajorDigit(left)+
"-9]");
result.add("[1-"+
(Integer.parseInt(getMajorDigit(right))-1)+
"][0-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else throw new IllegalStateException();
}
else if (getNumberOfDigits(left)==2 && getNumberOfDigits(right)==2){
if (Integer.parseInt(getMajorDigit(left))==Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (Integer.parseInt(getMajorDigit(left))+1==Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else if (Integer.parseInt(getMajorDigit(left))+2<=Integer.parseInt(getMajorDigit(right))) {
result.add(getMajorDigit(left)+
"["+
getMajorDigit(getNumberWithoutMajorDigit(left))+
"-9]");
result.add("["+(Integer.parseInt(getMajorDigit(left))+1)+
"-"+(Integer.parseInt(getMajorDigit(right))-1)+
"][0-9]");
result.add(getMajorDigit(right)+
"[0-"+
getMajorDigit(getNumberWithoutMajorDigit(right))+
"]");
}
else throw new IllegalStateException();
}
else result.add(staticPart(right));
result.add(breakPart(right));
return result.toArray(new String[0]);
}
static String breakPart(final Long number) {
if (getNumberOfDigits(number)<=2) {
return "";
}
StringBuilder result=new StringBuilder(256);
StringBuilder staticSection=new StringBuilder(32);
staticSection.append(getMajorDigit(number));
for (int i=1; i<getNumberOfDigits(number)-1; i++){
if (i!=1) result.append("|");
result.append(staticSection.toString());
staticSection.append(String.valueOf(number).charAt(i));
final long nextDigit=Long.parseLong(""+String.valueOf(number).charAt(i))-1;
if (nextDigit<0) {
result.setLength(0);
result.append("|");
continue;
}
if (nextDigit==0) result.append("0");
else if (nextDigit==1) result.append("[01]");
else result.append("[0-"+(nextDigit)+"]");
final int numberOfRepeats=(getNumberOfDigits(number)-i-1);
if (numberOfRepeats==1) result.append("[0-9]");
else result.append("[0-9]{"+numberOfRepeats+"}");
}
//остаток - 2 последние цифры числа
if (result.length()>0) {
result.append("|");
result.append(staticSection.toString());
//последнюю цифру от 0 до нее
result.append("[0-"+Long.parseLong(number.toString().replaceFirst("\\d+(\\d)","$1"))+"]");
}
if (result.length()>0) return result.toString().replace("||","|").replaceAll("^\\|","");
return "";
}
static String staticPart(final Long number) {
final long majorDigitMinus1=(Long.parseLong(getMajorDigit(number))-1);
if (majorDigitMinus1<=0) return "";
if (majorDigitMinus1==2) return "[1"+majorDigitMinus1+"][0-9]{"+(getNumberOfDigits(number)-1)+"}";
else if (majorDigitMinus1==1) return "1[0-9]{"+(getNumberOfDigits(number)-1)+"}";
return "[1-"+majorDigitMinus1+"][0-9]{"+(getNumberOfDigits(number)-1)+"}";
}
/**
* [1-9][0-9]{<X-1>,<Y-1>}, where X-number of digits of less number, Y-number of digits of greater number
*/
static String speedUpPart(Long left, Long right) {
//найти ближайшее до 0 то есть для 23 найти 100 для 777 найти 1000
//округленные до ближайшего 0
if (!String.valueOf(left).matches("10*")) left=toPower(left);
if (!String.valueOf(right).matches("10*")) right=toPower(right)/10;
final int leftPartRepeat=getNumberOfDigits(left)+(String.valueOf(left).matches("10*")?0:1)-1;
final int rightPartRepeat=getNumberOfDigits(right)+(String.valueOf(right).matches("10*")?0:1)-2;
if (getNumberOfDigits(left)==1 && getNumberOfDigits(right)==2)
return "[1-9]";
else if (leftPartRepeat>=rightPartRepeat)
return "[1-9][0-9]{"+rightPartRepeat+"}";
else
return "[1-9][0-9]{"+leftPartRepeat+","+rightPartRepeat+"}";
}
private static long toPower(final Long number) {
final double dValue=Math.pow(10, getNumberOfDigits(number));
final String value=String.format(Locale.US,"%24.0f",dValue);
return Long.parseLong(value.replaceFirst("\\s*(\\d+)(\\D\\d+)?","$1"));
}
private static int getNumberOfDigits(long number){
return (String.valueOf(number).length());
}
private static String getMajorDigit(long number){
return (String.valueOf(number).substring(0,1));
}
private static long getNumberWithoutMajorDigit(long number){
return Long.parseLong(String.valueOf(number).replaceFirst("\\d(\\d+)","$1"));
}
/**
* f(<n>>2)=<major digit>(f(<n-1>)|[<major digit+1>-9][0-9]{<n-1>})
*/
static String startPart(long number) {
int i=getNumberOfDigits(number);
if (i==1) {
if (number==9) return "9";
else if (number==8) return "[89]";
return "["+number+"-9]";
}
final long majorPlusOne=Long.parseLong(getMajorDigit(number))+1;
final int numberOfDigitsMinusOne=getNumberOfDigits(number)-1;
String result = (majorPlusOne < 10 ? "(" : "");
result+=getMajorDigit(number);
result+=startPart(getNumberWithoutMajorDigit(number));
result+=result.indexOf("|")<0 && majorPlusOne<10 && majorPlusOne!=numberOfDigitsMinusOne && numberOfDigitsMinusOne>1?"{"+numberOfDigitsMinusOne+"}":"";
result+=(majorPlusOne < 10
? "|[" + majorPlusOne + "-9][0-9]"+(numberOfDigitsMinusOne > 1 ? "{" + numberOfDigitsMinusOne + "}" : "")
: "");
result+=(majorPlusOne < 10 ? ")" : "");
return result;
}
private void parseAndCheck() {
Matcher matcher=pattern.matcher(src);
matcher.find();
try{
left=Long.parseLong(matcher.group(1));
right=Long.parseLong(matcher.group(2));
}
catch(Exception ex){
left=right+1;
}
if (left>right){
throw new IllegalArgumentException(MessageFormat.format(invalidArgumentEmpty,
src,
"Left part must be less than right one."));
}
}
public String getPattern() {
return result;
}
public static void main(String[] args) {
System.err.println(new NumberDiapasone2RegExp(args[0]).getPattern());
}
}
I was also trying to find a range of valid range for minutes
[0-60] worked for me.
I am using jdk 1.8 though

Categories