How do I avoid repetitiveness? [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Im doing a tutorial in Java and I always read that I must try not to be repetitive and I noticed this is very repetitive; So if anyone can give me some tips to make it less repetitive or somehow better it is much appriciated. Thanks ;) (This isn't part of the the tutorial, I made it just for fun because of what I am learning in science at school)
Run.java file:
package scientificFormula;
public class Run {
public static void main(String[] args) {
Formula formula = new Formula();
formula.compound1 = args[0];
formula.compound2 = args[1];
String theFormula = formula.createFormula();
System.out.println("Molecule: " + args[0] + " " + args[1] + " = "
+ theFormula);
}
}
Formula.java file:
package scientificFormula;
import java.util.HashMap;
import java.util.Map;
public class Formula {
String compound1;
String compound2;
static private Map<String, String> map = new HashMap<String, String>();
static private void initiateIons() {
// 1+
map.put("Hydrogen", "H^1+");
map.put("Lithium", "Li^1+");
map.put("Sodium", "Na^1+");
map.put("Potassium", "K^1+");
map.put("Rubidium", "Rb^1+");
// 2+
map.put("Magnesium", "Mg^2+");
map.put("Calcium", "Ca^2+");
map.put("Strontium", "Sr^2+");
// 3+
map.put("Aluminium", "Al^3+");
// 3-
map.put("Nitrogem", "N^-3");
map.put("Phosphorus", "P^-3");
// 2-
map.put("Oxygen", "O^-2");
map.put("Sulfur", "S^-2");
map.put("Selenium", "Se^-2");
// 1-
map.put("Fluorine", "F^-1");
map.put("Chlorine", "Cl^-1");
map.put("Bromine", "Br^-1");
map.put("Iodine", "I^-1");
}
String createFormula() {
initiateIons();
// Example1: Input = Calcium Iodine:
// 2x + -1y = 0
// x = 1 and y = 2
// Output = CaI2
//
// Example2: Input = Sulfur Iodine
// Output = Molecule: Sulfur Iodine = SI2
String symbol1 = map.get(compound1);
String symbol2 = map.get(compound2);
int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
symbol1.length() - 2));
int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
symbol2.length() - 2));
String letter1 = null;
String letter2 = null;
if (symbol1.length() == 5) {
letter1 = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter1 = symbol1.substring(0, 1);
}
if (symbol2.length() == 5) {
letter2 = symbol2.substring(0, 2);
} else if (symbol2.length() == 4) {
letter2 = symbol2.substring(0, 1);
}
int possitive1 = (int) Math.sqrt(charge1 * charge1);
int possitive2 = (int) Math.sqrt(charge2 * charge2);
if ((possitive1 == 1) & (possitive2 == 1)) {
return letter1 + letter2;
} else if (possitive1 == 1) {
return letter1 + possitive2 + letter2;
} else if (possitive2 == 1) {
return letter1 + letter2 + possitive1;
}
if (possitive1 == 0) {
possitive1 = -(charge1);
}
if (possitive2 == 0) {
possitive2 = -(charge2);
}
return letter1 + possitive2 + letter2 + possitive1;
}
}

I highly recommend reading the book clean code which mainly deals with refactoring.
Duplicating code is just one (important) issue when you start refactoring (also called DRY - Don't Repeat Yourself). There are many other principles and I'll try describe a few of them which I find most important:
One important "rule of thumb" is the SRP: Single Responsibility Principle, which says that each class should have only one responsibility, and if we apply the same idea to methods - each method should do only one thing! It might sound very strict, but when you'll start applying it - your code will become clearer to read and easier to maintain.
Another one is using meaningful names (classes/methods/variables):
return letter1 + possitive2 + letter2; // you probably meant positive with one 's' (typo!)
might mean something to you - but it will not mean much to another reader - now, of course you can solve it by adding code comments, but that's patching the problem instead of solving it. Further, code comments get stale - either become irrelevant or even worse - might mislead the reader when the code changes and the comment doesn't.
And last (for now), keep clear order of execution, let's take a piece of code that you posted and improve it:
String symbol1 = map.get(compound1);
String symbol2 = map.get(compound2);
int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
symbol1.length() - 2));
int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
symbol2.length() - 2));
String letter1 = null;
String letter2 = null;
if (symbol1.length() == 5) {
letter1 = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter1 = symbol1.substring(0, 1);
}
if (symbol2.length() == 5) {
letter2 = symbol2.substring(0, 2);
} else if (symbol2.length() == 4) {
letter2 = symbol2.substring(0, 1);
}
int possitive1 = (int) Math.sqrt(charge1 * charge1);
int possitive2 = (int) Math.sqrt(charge2 * charge2);
As we can see: positive depends on charge which depends on symbol which depends on compound. And totaly unrelated to it: letter depends on symbol which depends on compound.
let's split it to separate methods:
int getPositive(String compound) { // I have no idea what "positive", "symbol" and compound represent, consider better names please
String symbol = map.get(compound);
int charge = Integer.parseInt(symbol.replace("+", "").substring(
symbol.length() - 2));
return (int) Math.sqrt(charge2 * charge2);
}
And now we can apply the same to getLetter(String compound) {...} etc.

I would throw some of that parsing into its own class, maybe you can even offload more into there when you build out more functionallity.
public class Symbol {
final int charge;
final String letter;
public Symbol(String str) {
int sepIndex = str.indexOf('^');
if(sepIndex != -1) {
letter = str.substring(0, sepIndex);
charge = Integer.parseInt(str.substring(sepIndex+1).replace("+", ""));
} else {
throw new IllegalArgumentException(str + " isnt a valid Symbol, no ^ found");
}
}
}
public class Formula {
String compound1;
String compound2;
static private Map<String, String> map = new HashMap<String, String>();
// make this a static block so its only called once.
static {
// 1+
map.put("Hydrogen", "H^1+");
map.put("Lithium", "Li^1+");
map.put("Sodium", "Na^1+");
map.put("Potassium", "K^1+");
map.put("Rubidium", "Rb^1+");
// 2+
map.put("Magnesium", "Mg^2+");
map.put("Calcium", "Ca^2+");
map.put("Strontium", "Sr^2+");
// 3+
map.put("Aluminium", "Al^3+");
// 3-
map.put("Nitrogem", "N^-3");
map.put("Phosphorus", "P^-3");
// 2-
map.put("Oxygen", "O^-2");
map.put("Sulfur", "S^-2");
map.put("Selenium", "Se^-2");
// 1-
map.put("Fluorine", "F^-1");
map.put("Chlorine", "Cl^-1");
map.put("Bromine", "Br^-1");
map.put("Iodine", "I^-1");
}
String createFormula() {
// Example1: Input = Calcium Iodine:
// 2x + -1y = 0
// x = 1 and y = 2
// Output = CaI2
//
// Example2: Input = Sulfur Iodine
// Output = Molecule: Sulfur Iodine = SI2
Symbol symbol1 = new Symbol(map.get(compound1));
Symbol symbol2 = new Symbol(map.get(compound2));
int possitive1 = Math.abs(symbol1.charge); // sqrt(a*a) == abs(a)
int possitive2 = Math.abs(symbol1.charge);
if ((possitive1 == 1) & (possitive2 == 1)) {
return symbol1.letter + symbol1.letter;
} else if (possitive1 == 1) {
return symbol1.letter + possitive2 + symbol2.letter;
} else if (possitive2 == 1) {
return symbol1.letter + symbol2.letter + possitive1;
}
// dead code, if positive1 is 0 then setting it to -0 does nothing
/*if (possitive1 == 0) {
possitive1 = -(symbol1.charge);
}
if (possitive2 == 0) {
possitive2 = -(symbol2.charge);
}*/
return symbol1.letter + possitive2 + symbol2.letter + possitive1;
}
}

First method:
getCharge(String symbol){
return Integer.parseInt(symbol.replace("+", "").substring(symbol.length() - 2));
}
Second Method:
getLetter(String symbol){
if (symbol.length() == 5) {
return symbol.substring(0, 2);
} else if (symbol.length() == 4) {
return symbol.substring(0, 1);
}
}

I believe this is equivalent to your posted code -
private static String checkCompound(String symbol) {
if (symbol.length() == 5) {
return symbol.substring(0, 2);
} else if (symbol.length() == 4) {
return symbol.substring(0, 1);
}
return "";
}
Then
String letter1 = checkCompound(symbol1);
String letter2 = checkCompound(symbol2);
if (charge1 > 0) {
if (charge2 > 0) {
return letter1 + letter2;
}
return letter1 + charge2 + letter2;
} else if (charge2 > 0) {
return letter1 + letter2 + charge1;
}
return letter1 + charge2 + letter2 + charge1;
Finally, this
if (possitive1 == 0) {
possitive1 = -(charge1);
}
was removed because it's -0 which is 0.

Well, first let's rearrange your code so that all of the ...1 variables are together. Judging by your naming convention, you use letter1 to calculate symbol1, symbol1 to calculate charge1, etc... I'm just going to focus on createFormula() since that's the part you want to reduce in size.
String createFormula() {
initiateIons();
//Calculate symbol1, charge1, letter1, possitive1
String symbol1 = map.get(compound1);
int charge1 = Integer.parseInt(symbol1.replace("+", "").substring(
symbol1.length() - 2));
String letter1 = null;
if (symbol1.length() == 5) {
letter1 = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter1 = symbol1.substring(0, 1);
}
int possitive1 = (int) Math.sqrt(charge1 * charge1);
//calculate symbol2, charge2, letter2, possitive2
String symbol2 = map.get(compound2);
int charge2 = Integer.parseInt(symbol2.replace("+", "").substring(
symbol2.length() - 2));
String letter2 = null;
if (symbol2.length() == 5) {
letter2 = symbol2.substring(0, 2);
} else if (symbol2.length() == 4) {
letter2 = symbol2.substring(0, 1);
}
int possitive2 = (int) Math.sqrt(charge2 * charge2);
//Returns
if ((possitive1 == 1) & (possitive2 == 1)) {
return letter1 + letter2;
} else if (possitive1 == 1) {
return letter1 + possitive2 + letter2;
} else if (possitive2 == 1) {
return letter1 + letter2 + possitive1;
}
if (possitive1 == 0) {
possitive1 = -(charge1);
}
if (possitive2 == 0) {
possitive2 = -(charge2);
}
return letter1 + possitive2 + letter2 + possitive1;
}
I agree, the calculation step seems redundant. It would be amazing to have a function that calculates those for and returns a tuple of them, but (as far as I know) Java doesn't yet have tuples. We can do a string array though, and parse the ints back out of the strings. Here's a less redundant revision of your code.
String[] calculatePieces(String compound){
String symbol = map.get(compound);
int charge = Integer.parseInt(symbol.replace("+", "").substring(
symbol.length() - 2));
String letter = null;
if (symbol.length() == 5) {
letter = symbol1.substring(0, 2);
} else if (symbol1.length() == 4) {
letter = symbol1.substring(0, 1);
}
int possitive = (int) Math.sqrt(charge * charge);
pieces = new String[4];
pieces[0] = symbol;
pieces[1] = charge + "";
pieces[2] = letter;
pieces[3] = possitive + "";
return pieces;
}
String createFormula() {
initiateIons();
String[] pieces1 = calculatePieces(compound1);
int charge1 = Integer.parseInt(pieces1[1]);
int possitive1 = Integer.parseInt(pieces1[3]);
String[] pieces2 = calculatePieces(compound2);
int charge2 = Integer.parseInt(pieces2[1]);
int possitive2 = Integer.parseInt(pieces2[3]);
//Returns
if ((possitive1 == 1) & (possitive2 == 1)) {
return pieces1[2] + pieces2[2];
} else if (possitive1 == 1) {
return pieces1[2] + possitive2 + pieces2[2];
} else if (possitive2 == 1) {
return pieces1[2] + pieces2[2] + possitive1;
}
if (possitive1 == 0) {
possitive1 = -(charge1);
}
if (possitive2 == 0) {
possitive2 = -(charge2);
}
return pieces1[2] + possitive2 + pieces2[2] + possitive1;
}
It's a bit better, but Java's restriction on returning a single object limits how clean this can get. The way to make it even cleaner is to make a wrapper object that basically acts as a tuple of (string, int, string, int), but if you need this to be fast that's not the way to go.

Related

How is it possible to spread exams of students in optaplanner?

I am learning to work with optaplanner. I need to spread exams of one student. The less time between two exams of one student, the more penalty I give.
I need the Integer List ExamIds of my Student class because there are all the exams for that one student.
Then I need to check all these Exams planned Timeslots with eachother to give them more time between.
What i tried is following code:
`
Constraint spaceBetweenExams(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Student.class)
.join(Exam.class)
.join(Exam.class)
.filter((student, exam1, exam2) ->{
if(student.getExamIds().contains(exam1.getID()) && student.getExamIds().contains(exam2.getID())){
if(exam1.getID() < exam2.getID()){
int timeDifference = Math.abs(exam1.getTimeslot().getID() - exam2.getTimeslot().getID());
if (timeDifference == 1) {
penalty = 16;
} else if (timeDifference == 2) {
penalty = 8;
} else if (timeDifference == 3) {
penalty = 4;
} else if (timeDifference == 4) {
penalty = 2;
} else if (timeDifference == 5) {
penalty = 1;
}
return true;
}
}
return false;
})
.penalize("Max time between exams", HardSoftScore.ofSoft(penalty));
`
The result I get is 24645 soft penalties but optaplanner doesn't even try to fix them.
I think that the way I check the exams in the code above is not fully correct.
This is my constraint class :
public class ExamTableConstraintProvider implements ConstraintProvider {
int penalty = 0;
List<Integer> studentExamIds;
#Override
public Constraint[] defineConstraints(ConstraintFactory constraintFactory) {
return new Constraint[]{
// Hard constraints
twoExamForStudentConflict(constraintFactory),
// Soft constraints
spaceBetweenExams(constraintFactory)
};
}
private Constraint twoExamForStudentConflict(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Exam.class)
.join(Exam.class,
Joiners.equal(Exam::getTimeslot),
Joiners.lessThan(Exam::getID))
.filter((exam1, exam2) -> {
List<Integer> result = new ArrayList<>(exam1.getSID());
result.retainAll(exam2.getSID());
return result.size() > 0;
})
.penalize("Student conflict", HardSoftScore.ONE_HARD);
}
Constraint spaceBetweenExams(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Student.class)
.join(Exam.class)
.join(Exam.class)
.filter((student, exam1, exam2) ->{
if(student.getExamIds().contains(exam1.getID()) && student.getExamIds().contains(exam2.getID())){
if(exam1.getID() < exam2.getID()){
int timeDifference = Math.abs(exam1.getTimeslot().getID() - exam2.getTimeslot().getID());
if (timeDifference == 1) {
penalty = 16;
} else if (timeDifference == 2) {
penalty = 8;
} else if (timeDifference == 3) {
penalty = 4;
} else if (timeDifference == 4) {
penalty = 2;
} else if (timeDifference == 5) {
penalty = 1;
}
return true;
}
}
return false;
})
.penalize("Max time between exams", HardSoftScore.ofSoft(penalty));
}
/*Constraint spaceBetweenExams(ConstraintFactory constraintFactory) {
penalty = 0;
return constraintFactory.forEach(Student.class)
.join(Exam.class,
equal(Student::getExamIds, Exam::getID),
filtering((student, exam1) -> exam1.getTimeslot() != null))
.join(Exam.class,
equal((student, exam1) -> student.getExamIds(), Exam::getID),
equal((student, exam1) -> exam1.getTimeslot(), Exam::getTimeslot),
filtering((student, exam1, exam2) -> {
int timeDifference = getPeriodBetweenExams(exam1, exam2);
if (timeDifference == 1) {
penalty += 16;
} else if (timeDifference == 2) {
penalty += 8;
} else if (timeDifference == 3) {
penalty += 4;
} else if (timeDifference == 4) {
penalty += 2;
} else if (timeDifference == 5) {
penalty += 1;
}
if(penalty == 0){
return false;
}
return true;
}))
.penalize("Max time between exams", HardSoftScore.ONE_SOFT);
}*/
}
And this is the class where I start the program:
public class ExamTableApp {
private static final Logger LOGGER = LoggerFactory.getLogger(ExamTableApp.class);
public static void main(String[] args) {
SolverFactory<ExamTable> solverFactory = SolverFactory.create(new SolverConfig()
.withSolutionClass(ExamTable.class)
.withEntityClasses(Exam.class)
.withConstraintProviderClass(ExamTableConstraintProvider.class)
// The solver runs only for 5 seconds on this small dataset.
// It's recommended to run for at least 5 minutes ("5m") otherwise.
.withTerminationSpentLimit(Duration.ofSeconds(30)));
// Load the problem
ExamTable problem = getData();
// Solve the problem
Solver<ExamTable> solver = solverFactory.buildSolver();
ExamTable solution = solver.solve(problem);
// Visualize the solution
printTimetable(solution);
}
public static ExamTable getData(){
DataReader parser = new DataReader("benchmarks/sta-f-83.crs", "benchmarks/sta-f-83.stu");
List<Room> roomList = new ArrayList<>(1);
roomList.add(new Room(1,"Room A"));
// roomList.add(new Room(2,"Room B"));
// roomList.add(new Room(3,"Room C"));
List<Exam> examList = new ArrayList<>();
HashMap<Integer, Exam> exams = parser.getExams();
Set<Integer> keys = exams.keySet();
for (Integer i : keys) {
Exam exam = exams.get(i);
examList.add(new Exam(exam.getID(), exam.getSID()));
}
List<Student> studentList = new ArrayList<>();
HashMap<Integer, Student> students = parser.getStudents();
Set<Integer> keys2 = students.keySet();
for (Integer i : keys2) {
Student student = students.get(i);
studentList.add(new Student(student.getID(), student.getExamIds()));
}
return new ExamTable(parser.getTimeslots(), roomList, examList, studentList);
}
private static void printTimetable(ExamTable examTable) {
LOGGER.info("");
List<Room> roomList = examTable.getRoomList();
List<Exam> examList = examTable.getExamList();
Map<TimeSlot, Map<Room, List<Exam>>> examMap = examList.stream()
.filter(exam -> exam.getTimeslot() != null && exam.getRoom() != null)
.collect(Collectors.groupingBy(Exam::getTimeslot, Collectors.groupingBy(Exam::getRoom)));
LOGGER.info("| | " + roomList.stream()
.map(room -> String.format("%-10s", room.getName())).collect(Collectors.joining(" | ")) + " |");
LOGGER.info("|" + "------------|".repeat(roomList.size() + 1));
for (TimeSlot timeslot : examTable.getTimeslotList()) {
List<List<Exam>> cellList = roomList.stream()
.map(room -> {
Map<Room, List<Exam>> byRoomMap = examMap.get(timeslot);
if (byRoomMap == null) {
return Collections.<Exam>emptyList();
}
List<Exam> cellLessonList = byRoomMap.get(room);
if (cellLessonList == null) {
return Collections.<Exam>emptyList();
}
return cellLessonList;
})
.collect(Collectors.toList());
LOGGER.info("| " + String.format("%-10s",
timeslot.getID() + " " + " | "
+ cellList.stream().map(cellLessonList -> String.format("%-10s",
cellLessonList.stream().map(Exam::getName).collect(Collectors.joining(", "))))
.collect(Collectors.joining(" | "))
+ " |"));
LOGGER.info("|" + "------------|".repeat(roomList.size() + 1));
}
List<Exam> unassignedExams = examList.stream()
.filter(exam -> exam.getTimeslot() == null || exam.getRoom() == null)
.collect(Collectors.toList());
if (!unassignedExams.isEmpty()) {
LOGGER.info("");
LOGGER.info("Unassigned lessons");
for (Exam exam : unassignedExams) {
LOGGER.info(" " + exam.getName() + " - " + exam.getNumberOfStudents() + " - " + exam.getSID());
}
}
}
}
Could someone help me out with this?
Thanks in advance.
The code you provided shows one major misunderstanding of how Constraint Streams work, which in turn makes it fundamentally broken.
Any instance of ConstraintProvider must be stateless. Even though you technically can have fields in that class, there is no use for it, as the constraints - when run - need to be without side effects. This way, you have introduced score corruptions and probably have not even noticed.
Also, the constraint weight HardScore.ofSoft(...) is only computed once during constraint creation, not at solver runtime, therefore defining it like you did would have been pointless anyway. (Its value will be whatever penalty was at instantiation, therefore 0.) What you need to use instead is a match weight, which is computed at runtime. Making just that modification, the constraint in question would look like this:
Constraint spaceBetweenExams(ConstraintFactory constraintFactory) {
return constraintFactory.forEach(Student.class)
.join(Exam.class)
.join(Exam.class)
.filter((student, exam1, exam2) -> {
if(student.getExamIds().contains(exam1.getID()) && student.getExamIds().contains(exam2.getID())){
if(exam1.getID() < exam2.getID()){
return true;
}
}
return false;
})
.penalize("Max time between exams", HardSoftScore.ONE_SOFT,
(student, exam1, exam2) ->{
int timeDifference = Math.abs(exam1.getTimeslot().getID() - exam2.getTimeslot().getID());
if (timeDifference == 1) {
return 16;
} else if (timeDifference == 2) {
return 8;
} else if (timeDifference == 3) {
return 4;
} else if (timeDifference == 4) {
return 2;
} else {
return 1;
}
}
});
}
The above code will at least make this code run properly, but it will likely be slow. See my other recent answer for inspiration on how to change your domain model to improve performance of your constraints. It may not fit exactly, but the idea seems valid to your use case as well.

Minecraft Bukkit coding Type mismatch: cannot convert from element type Object to String

Here is the full code for it:
public void trackAll() {
int north = count(Direction.North) * 25;
int east = count(Direction.East) * 25;
int south = count(Direction.South) * 25;
int west = count(Direction.West) * 25;
if ((north == 0) && (east == 0) && (south == 0) && (west == 0)) {
this.player.sendMessage(ChatColor.RED + "Not a valid tracking compass.");
return;
}
for (Direction direction : Direction.values()) {
int length = count(direction) * 25;
if (length != 0) {
#SuppressWarnings("rawtypes")
Set players = new TreeSet();
for (Player player : Bukkit.getOnlinePlayers()) {
if (this.player.canSee(player)) if ((on(player, direction) & !player.equals(this.player))) {
players.add(player.getDisplayName());
}
}
FancyMessage message = new FancyMessage(direction + " (" + length + "): ").color(ChatColor.DARK_AQUA);
int i = 0;
for (String str : players) {
if (i == players.size() - 1)
message.then(str).color(ChatColor.GRAY).tooltip(ChatColor.GREEN + "Click here to track " + ChatColor.RESET + str + ChatColor.GREEN + ".").command("/track " + ChatColor.stripColor(str));
else {
message.then(str).color(ChatColor.GRAY).tooltip(ChatColor.GREEN + "Click here to track " + ChatColor.RESET + str + ChatColor.GREEN + ".").command("/track " + ChatColor.stripColor(str)).then(", ");
}
i++;
}
message.send(this.player);
}
}
}
And I also have another issue "Type mismatch: cannot convert from element type Object to Block"
public int count(Direction direction, boolean b) {
int length = 0;
#SuppressWarnings("rawtypes")
Set toDelete = new HashSet();
for (int i = 1; i < 10000; i++) {
Block next = this.middle.getRelative(BlockFace.valueOf(direction.toString().toUpperCase()), i);
if (next.getType() == Material.COBBLESTONE) {
length++;
toDelete.add(next); } else {
if (next.getType() == Material.STONE) {
length++;
toDelete.add(next);
toDelete.add(this.middle);
break;
}
length = 0;
toDelete.clear();
break;
}
}
if (b) {
for (Block block : toDelete) {
block.getWorld().playEffect(block.getLocation(), Effect.STEP_SOUND, block.getTypeId());
block.setType(Material.AIR);
}
}
return length;
}
I currently don't have someone that can look over the code I personally do not see the issue but I've been working on it for hours so yeah ;/ Thanks. This code is to do with a Minecraft plugin it's tracking a players location and sending the information to the player that executed the command.
Use
Set<String> players = new TreeSet<>();
and
Set<Block> toDelete = new HashSet<>();

Creating a Complex number class in Java

I am a new in java and programming in general.
I am currently doing complex numbers. I know that there might be an answer for this online, but it will also reveal if I used the correct algorithm and so on, so I am trying to avoid other answers around here.
My main issue is that I am having trouble with the Divide class that I made, since in complex number division we are going to return a fraction as an answer, I can't figure out how to have the program return the 2 statements that it calculate, can someone advise what can be done? Here is the part of the division code, it works fine when I check both part 1 and then part 2, but how can i get it to return both of them when calling using that class.
I attached my full code that I made, I know it can be tweaked to have less coding, but that is not my current concern.
Thanks for your help in advance.
class complexN {
int R, I;
complexN(int R, int I) {
this.R = R;
this.I = I;
}
complexN AddCN(complexN A) {
return new complexN(this.R + A.R, this.I + A.I);
}
complexN SubCN(complexN A) {
int AnsR = this.R - A.R;
int AnsI = this.I - A.I;
complexN Sum = new complexN(AnsR, AnsI);
return Sum;
}
complexN MulCN(complexN A) {
int AnsI = (this.R * A.I) + (this.I * A.R);
int AnsR = (this.R * A.R) - (this.I * A.I);
complexN Sum = new complexN(AnsR, AnsI);
return Sum;
}
complexN DivCN(complexN A) {
complexN ComCon = new complexN(A.R, (A.I * -1));
complexN part1 = new complexN(this.R, this.I).MulCN(ComCon);
complexN part2 = A.MulCN(ComCon);
return part1;
}
void print() {
String i = (this.I == 1 ? "" : (this.I == -1 ? "-" : "" + this.I));
if (this.R != 0 && this.I > 0) {
System.out.println(this.R + "+" + i + "i");
}
if (this.R != 0 && this.I < 0) {
System.out.println(this.R + i + "i");
}
if (this.R != 0 && this.I == 0) {
System.out.println(this.R);
}
if (this.R == 0 && this.I != 0) {
System.out.println(i + "i");
}
if (this.R == 0 && this.I == 0) {
System.out.println("0");
}
}
}
class complex {
public static void main(String[] args) {
// TODO Auto-generated method stub
complexN z1 = new complexN(5, 2);
complexN z2 = new complexN(3, -4);
System.out.print("z1 = ");
z1.print();
System.out.print("z2 = ");
z2.print();
System.out.println("---------");
z1.DivCN(z2).print();
}
}

Random number - increase/decrease by 1

I'm working on a method, that takes steps between 3 and -3. My program will not print out the steps in a numerical order, and I can't quite figure out how to do it, and I can't find anything elsewhere.
public static final int SENTINEL = Math.abs(3);
public static void randomWalk(Random rand) {
int walk = 0;
while (walk != SENTINEL) {
walk = (rand.nextInt((3 - (-3)) + 1) - 3);
System.out.println("Position = " + walk);
}
}
If that is what you are looking for :
int walk = 0;
int randomStep = 0;
Random rand = new Random();
while (Math.abs(walk) != 3) {
randomStep = rand.nextInt(2) > 0 ? 1 : -1; // -1 or 1 with 50% probability
walk += randomStep;
System.out.print(walk + " ");
}
//sample output: -1 -2 -1 0 1 2 1 2 3
public static void randomWalk(Random rand) {
int walk = 0;
while (walk != SENTINEL) {
walk += rand.nextInt(3) - 1;
if(walk>3) walk = 3;
if(walk<-3) walk = -3;
System.out.println("Position = " + walk);
}
}
I guess you want this.
while (walk != SENTINEL) {
int walk = 0;
walk = (rand.nextInt((3 - (-3)) + 1) - 3);
System.out.println("Walk is = " + walk);
int temp = walk;
if (walk >= -3) {
System.out.println("Wlak plus = " + (temp + 1));
System.out.println("Wlak minus =" + (temp - 1));
}
}
Could this be what you are looking for?
package com.stackoverflow.random;
import java.util.Random;
public class Walking {
private final int bounds;
public Walking(int bounds) {
this.bounds = bounds;
}
private boolean isWithinBounds(int walk) {
return Math.abs(walk) < bounds;
}
public String randomWalk() {
int walk = 0;
StringBuilder sb = new StringBuilder();
while(isWithinBounds(walk)) {
sb.append(walk);
walk = getNextStep(walk);
}
return sb.toString();
}
private Random random = null;
private int getNextStep(int walk) {
if (random == null)
random = new Random();
boolean increase = random.nextBoolean();
return increase?++walk:--walk;
}
public static void main(String[] args) {
Walking app = new Walking(3);
System.out.println("walking: " + app.randomWalk());
}
}

Time delay and JInput

OK, I don't know how to word this question, but maybe my code will spell out the problem:
public class ControllerTest
{
public static void main(String [] args)
{
GamePadController rockbandDrum = new GamePadController();
DrumMachine drum = new DrumMachine();
while(true)
{
try{
rockbandDrum.poll();
if(rockbandDrum.isButtonPressed(1)) //BLUE PAD HhiHat)
{
drum.playSound("hiHat.wav");
Thread.sleep(50);
}
if(rockbandDrum.isButtonPressed(2)) //GREEN PAD (Crash)
{
//Todo: Change to Crash
drum.playSound("hiHat.wav");
Thread.sleep(50);
}
//Etc....
}
}
}
public class DrumMachine
{
InputStream soundPlayer = null;
AudioStream audio = null;
static boolean running = true;
public void playSound(String soundFile)
{
//Tak a sound file as a paramater and then
//play that sound file
try{
soundPlayer = new FileInputStream(soundFile);
audio = new AudioStream(soundPlayer);
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
AudioPlayer.player.start(audio);
}
//Etc... Methods for multiple audio clip playing
}
Now the problem is, if I lower the delay in the
Thread.sleep(50)
then the sound plays multiple times a second, but if I keep at this level or any higher, I could miss sounds being played...
It's an odd problem, where if the delay is too low, the sound loops. But if it's too high it misses playing sounds. Is this just a problem where I would need to tweak the settings, or is there any other way to poll the controller without looping sound?
Edit: If I need to post the code for polling the controller I will...
import java.io.*;
import net.java.games.input.*;
import net.java.games.input.Component.POV;
public class GamePadController
{
public static final int NUM_BUTTONS = 13;
// public stick and hat compass positions
public static final int NUM_COMPASS_DIRS = 9;
public static final int NW = 0;
public static final int NORTH = 1;
public static final int NE = 2;
public static final int WEST = 3;
public static final int NONE = 4; // default value
public static final int EAST = 5;
public static final int SW = 6;
public static final int SOUTH = 7;
public static final int SE = 8;
private Controller controller;
private Component[] comps; // holds the components
// comps[] indices for specific components
private int xAxisIdx, yAxisIdx, zAxisIdx, rzAxisIdx;
// indices for the analog sticks axes
private int povIdx; // index for the POV hat
private int buttonsIdx[]; // indices for the buttons
private Rumbler[] rumblers;
private int rumblerIdx; // index for the rumbler being used
private boolean rumblerOn = false; // whether rumbler is on or off
public GamePadController()
{
// get the controllers
ControllerEnvironment ce =
ControllerEnvironment.getDefaultEnvironment();
Controller[] cs = ce.getControllers();
if (cs.length == 0) {
System.out.println("No controllers found");
System.exit(0);
}
else
System.out.println("Num. controllers: " + cs.length);
// get the game pad controller
controller = findGamePad(cs);
System.out.println("Game controller: " +
controller.getName() + ", " +
controller.getType());
// collect indices for the required game pad components
findCompIndices(controller);
findRumblers(controller);
} // end of GamePadController()
private Controller findGamePad(Controller[] cs)
/* Search the array of controllers until a suitable game pad
controller is found (eith of type GAMEPAD or STICK).
*/
{
Controller.Type type;
int i = 0;
while(i < cs.length) {
type = cs[i].getType();
if ((type == Controller.Type.GAMEPAD) ||
(type == Controller.Type.STICK))
break;
i++;
}
if (i == cs.length) {
System.out.println("No game pad found");
System.exit(0);
}
else
System.out.println("Game pad index: " + i);
return cs[i];
} // end of findGamePad()
private void findCompIndices(Controller controller)
/* Store the indices for the analog sticks axes
(x,y) and (z,rz), POV hat, and
button components of the controller.
*/
{
comps = controller.getComponents();
if (comps.length == 0) {
System.out.println("No Components found");
System.exit(0);
}
else
System.out.println("Num. Components: " + comps.length);
// get the indices for the axes of the analog sticks: (x,y) and (z,rz)
xAxisIdx = findCompIndex(comps, Component.Identifier.Axis.X, "x-axis");
yAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Y, "y-axis");
zAxisIdx = findCompIndex(comps, Component.Identifier.Axis.Z, "z-axis");
rzAxisIdx = findCompIndex(comps, Component.Identifier.Axis.RZ, "rz-axis");
// get POV hat index
povIdx = findCompIndex(comps, Component.Identifier.Axis.POV, "POV hat");
findButtons(comps);
} // end of findCompIndices()
private int findCompIndex(Component[] comps,
Component.Identifier id, String nm)
/* Search through comps[] for id, returning the corresponding
array index, or -1 */
{
Component c;
for(int i=0; i < comps.length; i++) {
c = comps[i];
if ((c.getIdentifier() == id) && !c.isRelative()) {
System.out.println("Found " + c.getName() + "; index: " + i);
return i;
}
}
System.out.println("No " + nm + " component found");
return -1;
} // end of findCompIndex()
private void findButtons(Component[] comps)
/* Search through comps[] for NUM_BUTTONS buttons, storing
their indices in buttonsIdx[]. Ignore excessive buttons.
If there aren't enough buttons, then fill the empty spots in
buttonsIdx[] with -1's. */
{
buttonsIdx = new int[NUM_BUTTONS];
int numButtons = 0;
Component c;
for(int i=0; i < comps.length; i++) {
c = comps[i];
if (isButton(c)) { // deal with a button
if (numButtons == NUM_BUTTONS) // already enough buttons
System.out.println("Found an extra button; index: " + i + ". Ignoring it");
else {
buttonsIdx[numButtons] = i; // store button index
System.out.println("Found " + c.getName() + "; index: " + i);
numButtons++;
}
}
}
// fill empty spots in buttonsIdx[] with -1's
if (numButtons < NUM_BUTTONS) {
System.out.println("Too few buttons (" + numButtons +
"); expecting " + NUM_BUTTONS);
while (numButtons < NUM_BUTTONS) {
buttonsIdx[numButtons] = -1;
numButtons++;
}
}
} // end of findButtons()
private boolean isButton(Component c)
/* Return true if the component is a digital/absolute button, and
its identifier name ends with "Button" (i.e. the
identifier class is Component.Identifier.Button).
*/
{
if (!c.isAnalog() && !c.isRelative()) { // digital and absolute
String className = c.getIdentifier().getClass().getName();
// System.out.println(c.getName() + " identifier: " + className);
if (className.endsWith("Button"))
return true;
}
return false;
} // end of isButton()
private void findRumblers(Controller controller)
/* Find the rumblers. Use the last rumbler for making vibrations,
an arbitrary decision. */
{
// get the game pad's rumblers
rumblers = controller.getRumblers();
if (rumblers.length == 0) {
System.out.println("No Rumblers found");
rumblerIdx = -1;
}
else {
System.out.println("Rumblers found: " + rumblers.length);
rumblerIdx = rumblers.length-1; // use last rumbler
}
} // end of findRumblers()
// ----------------- polling and getting data ------------------
public void poll()
// update the component values in the controller
{
controller.poll();
}
public int getXYStickDir()
// return the (x,y) analog stick compass direction
{
if ((xAxisIdx == -1) || (yAxisIdx == -1)) {
System.out.println("(x,y) axis data unavailable");
return NONE;
}
else
return getCompassDir(xAxisIdx, yAxisIdx);
} // end of getXYStickDir()
public int getZRZStickDir()
// return the (z,rz) analog stick compass direction
{
if ((zAxisIdx == -1) || (rzAxisIdx == -1)) {
System.out.println("(z,rz) axis data unavailable");
return NONE;
}
else
return getCompassDir(zAxisIdx, rzAxisIdx);
} // end of getXYStickDir()
private int getCompassDir(int xA, int yA)
// Return the axes as a single compass value
{
float xCoord = comps[ xA ].getPollData();
float yCoord = comps[ yA ].getPollData();
// System.out.println("(x,y): (" + xCoord + "," + yCoord + ")");
int xc = Math.round(xCoord);
int yc = Math.round(yCoord);
// System.out.println("Rounded (x,y): (" + xc + "," + yc + ")");
if ((yc == -1) && (xc == -1)) // (y,x)
return NW;
else if ((yc == -1) && (xc == 0))
return NORTH;
else if ((yc == -1) && (xc == 1))
return NE;
else if ((yc == 0) && (xc == -1))
return WEST;
else if ((yc == 0) && (xc == 0))
return NONE;
else if ((yc == 0) && (xc == 1))
return EAST;
else if ((yc == 1) && (xc == -1))
return SW;
else if ((yc == 1) && (xc == 0))
return SOUTH;
else if ((yc == 1) && (xc == 1))
return SE;
else {
System.out.println("Unknown (x,y): (" + xc + "," + yc + ")");
return NONE;
}
} // end of getCompassDir()
public int getHatDir()
// Return the POV hat's direction as a compass direction
{
if (povIdx == -1) {
System.out.println("POV hat data unavailable");
return NONE;
}
else {
float povDir = comps[povIdx].getPollData();
if (povDir == POV.CENTER) // 0.0f
return NONE;
else if (povDir == POV.DOWN) // 0.75f
return SOUTH;
else if (povDir == POV.DOWN_LEFT) // 0.875f
return SW;
else if (povDir == POV.DOWN_RIGHT) // 0.625f
return SE;
else if (povDir == POV.LEFT) // 1.0f
return WEST;
else if (povDir == POV.RIGHT) // 0.5f
return EAST;
else if (povDir == POV.UP) // 0.25f
return NORTH;
else if (povDir == POV.UP_LEFT) // 0.125f
return NW;
else if (povDir == POV.UP_RIGHT) // 0.375f
return NE;
else { // assume center
System.out.println("POV hat value out of range: " + povDir);
return NONE;
}
}
} // end of getHatDir()
public boolean[] getButtons()
/* Return all the buttons in a single array. Each button value is
a boolean. */
{
boolean[] buttons = new boolean[NUM_BUTTONS];
float value;
for(int i=0; i < NUM_BUTTONS; i++) {
value = comps[ buttonsIdx[i] ].getPollData();
buttons[i] = ((value == 0.0f) ? false : true);
}
return buttons;
} // end of getButtons()
public boolean isButtonPressed(int pos)
/* Return the button value (a boolean) for button number 'pos'.
pos is in the range 1-NUM_BUTTONS to match the game pad
button labels.
*/
{
if ((pos < 1) || (pos > NUM_BUTTONS)) {
System.out.println("Button position out of range (1-" +
NUM_BUTTONS + "): " + pos);
return false;
}
if (buttonsIdx[pos-1] == -1) // no button found at that pos
return false;
float value = comps[ buttonsIdx[pos-1] ].getPollData();
// array range is 0-NUM_BUTTONS-1
return ((value == 0.0f) ? false : true);
} // end of isButtonPressed()
// ------------------- Trigger a rumbler -------------------
public void setRumbler(boolean switchOn)
// turn the rumbler on or off
{
if (rumblerIdx != -1) {
if (switchOn)
rumblers[rumblerIdx].rumble(0.8f); // almost full on for last rumbler
else // switch off
rumblers[rumblerIdx].rumble(0.0f);
rumblerOn = switchOn; // record rumbler's new status
}
} // end of setRumbler()
public boolean isRumblerOn()
{ return rumblerOn; }
} // end of GamePadController class
I think you are using the wrong design pattern here. You should use the observer pattern for this type of thing.
A polling loop not very efficient, and as you've noticed doesn't really yield the desired results.
I'm not sure what you are using inside your objects to detect if a key is pressed, but if it's a GUI architecture such as Swing or AWT it will be based on the observer pattern via the use of EventListeners, etc.
Here is a (slightly simplified) Observer-pattern
applied to your situation.
The advantage of this design is that when a button
is pressed and hold, method 'buttonChanged' will
still only be called once, instead of start
'repeating' every 50 ms.
public static final int BUTTON_01 = 0x00000001;
public static final int BUTTON_02 = 0x00000002;
public static final int BUTTON_03 = 0x00000004;
public static final int BUTTON_04 = 0x00000008; // hex 8 == dec 8
public static final int BUTTON_05 = 0x00000010; // hex 10 == dec 16
public static final int BUTTON_06 = 0x00000020; // hex 20 == dec 32
public static final int BUTTON_07 = 0x00000040; // hex 40 == dec 64
public static final int BUTTON_08 = 0x00000080; // etc.
public static final int BUTTON_09 = 0x00000100;
public static final int BUTTON_10 = 0x00000200;
public static final int BUTTON_11 = 0x00000400;
public static final int BUTTON_12 = 0x00000800;
private int previousButtons = 0;
void poll()
{
rockbandDrum.poll();
handleButtons();
}
private void handleButtons()
{
boolean[] buttons = getButtons();
int pressedButtons = getPressedButtons(buttons);
if (pressedButtons != previousButtons)
{
buttonChanged(pressedButtons); // Notify 'listener'.
previousButtons = pressedButtons;
}
}
public boolean[] getButtons()
{
// Return all the buttons in a single array. Each button-value is a boolean.
boolean[] buttons = new boolean[MAX_NUMBER_OF_BUTTONS];
float value;
for (int i = 0; i < MAX_NUMBER_OF_BUTTONS-1; i++)
{
int index = buttonsIndex[i];
if (index < 0) { continue; }
value = comps[index].getPollData();
buttons[i] = ((value == 0.0f) ? false : true);
}
return buttons;
}
private int getPressedButtons(boolean[] array)
{
// Mold all pressed buttons into a single number by OR-ing their values.
int pressedButtons = 0;
int i = 1;
for (boolean isBbuttonPressed : array)
{
if (isBbuttonPressed) { pressedButtons |= getOrValue(i); }
i++;
}
return pressedButtons;
}
private int getOrValue(int btnNumber) // Get a value to 'OR' with.
{
int btnValue = 0;
switch (btnNumber)
{
case 1 : btnValue = BUTTON_01; break;
case 2 : btnValue = BUTTON_02; break;
case 3 : btnValue = BUTTON_03; break;
case 4 : btnValue = BUTTON_04; break;
case 5 : btnValue = BUTTON_05; break;
case 6 : btnValue = BUTTON_06; break;
case 7 : btnValue = BUTTON_07; break;
case 8 : btnValue = BUTTON_08; break;
case 9 : btnValue = BUTTON_09; break;
case 10 : btnValue = BUTTON_10; break;
case 11 : btnValue = BUTTON_11; break;
case 12 : btnValue = BUTTON_12; break;
default : assert false : "Invalid button-number";
}
return btnValue;
}
public static boolean checkButton(int pressedButtons, int buttonToCheckFor)
{
return (pressedButtons & buttonToCheckFor) == buttonToCheckFor;
}
public void buttonChanged(int buttons)
{
if (checkButton(buttons, BUTTON_01)
{
drum.playSound("hiHat.wav");
}
if (checkButton(buttons, BUTTON_02)
{
drum.playSound("crash.wav");
}
}
Please post more information about the GamePadController class that you are using.
More than likely, that same library will offer an "event" API, where a "callback" that you register with a game pad object will be called as soon as the user presses a button. With this kind of setup, the "polling" loop is in the framework, not your application, and it can be much more efficient, because it uses signals from the hardware rather than a busy-wait polling loop.
Okay, I looked at the JInput API, and it is not really event-driven; you have to poll it as you are doing. Does the sound stop looping when you release the button? If so, is your goal to have the sound play just once, and not again until the button is release and pressed again? In that case, you'll need to track the previous button state each time through the loop.
Human response time is about 250 ms (for an old guy like me, anyway). If you are polling every 50 ms, I'd expect the controller to report the button depressed for several iterations of the loop. Can you try something like this:
boolean played = false;
while (true) {
String sound = null;
if (controller.isButtonPressed(1))
sound = "hiHat.wav";
if (controller.isButtonPressed(2))
sound = "crash.wav";
if (sound != null) {
if (!played) {
drum.playSound(sound);
played = true;
}
} else {
played = false;
}
Thread.sleep(50);
}

Categories