I am trying to create a win condition for my text game. I have two methods that decide whether a player has established criteria for a win or loss. These methods are in one class, while I want to use them in my controller class. The variables are hitTimes and nonHits:
class1:
if(choiceC > 0 || choiceR > 0)
{
Character currentCharacter;
currentCharacter= grid[choiceR][choiceC];
gameBoard[choiceR][choiceC] = currentCharacter;
loseTest(currentCharacter);
winTest(currentCharacter);
}
}
}
}
public int loseTest(Character currentCharacter)
{
int hitTimes = 0;
if(currentCharacter.minePresent == true)
{
hitTimes = 1;
}
return hitTimes;
}
public int winTest(Character currentCharacter)
{
int nonHits = 0;
if(currentCharacter.minePresent == false)
{
nonHits++;
}
return nonHits;
}
class2:
Grid grid = new Grid();
double notMines = grid.notMine;
View view = new View();
result = grid.toString();
view.display(result);
final int ITERATIONS = 13;
final int numGames = 1000;
for (int i=0;i <= numGames; i++)
{
while (hitTimes != 1 || nonHits != notMines )
{
grid.runGame();
result2 = grid.toString();
view.display(result2);
if(nonHits == ITERATIONS)
{
System.out.println("You Win!");
}
if(hitTimes == 1)
{
System.out.println("You Lose!");
}
}
}
You could make boolean attributes gameWon and gameLost, and put them both at false initial value. Then if conditions are fulfilled you turn one of them into true depending on the case of course. Make also getter methods in your class so you can access to them from another class.
Place this in your second method:
private boolean gameWon = false;
private boolean gameLost = false;
public boolean getGameWon() {
return gameWon;
}
public boolean getGameLost() {
return gameLost;
}
Change if condition to also have:
if(nonHits == ITERATIONS)
{
gameWon = true;
}
if(hitTimes == 1)
{
gameLost = true;
}
In your other class create this class and access your gameWon/gameLost values through getters.
SecondClass sc = new SecondClass();
boolean isGameWon = sc.gameWon();
boolean isGameLost = sc.gameLost();
Hopefully I gave you an idea.. I can't see your whole code so this is just an assumption I made of what's bothering you. Cheers!
Related
Edit. thank you.
I have an array of 'normal' vehicles and 'large' vehicles. I have an assignment requiring me to divide them up to contribute to a far larger app.
One array for the large vehicles, one for the normal vehicles containing all the info for each element. ArrayLists are not permitted as my instructor is teaching us fundamentals.
Sample of the array
27723 4/09/61 large 7337
28507 22-02-1983 large 7055
28558 1/05/70 normal 3518
//On button press
//recieve single item from array from main and test it
//array in main will be looped for all elements.
public String loadVehicle(Vehicle v) {
String res = Constants.OK;
boolean normBool = false;
boolean largeBool = false;
//if both arrays are full , stop the method call in the main form
if (normBool && largeBool){return Constants.ERROR;}
//if vehicle size is normal, fill the normal veh array
if(v.getSize().equals(Constants.NORMAL_SIZE))
{
for(int i = 0; i<normalVehicles.length; i++)
{
//if norm veh array element is null, add the appropriate value to it
if(normalVehicles[i] == null){normalVehicles[i] = v;}
else{normBool = true;}
}
}
//if veh size is large put it in the large veh array
else if(v.getSize().equals(Constants.LARGE_SIZE))
{
for(int iL = 0; iL<largeVehicles.length; iL++)
{
if(largeVehicles[iL] == null){largeVehicles[iL] = v;}
else{largeBool = true;}
}
}
return res;
}//end method
Seems you cannot use builtin LinkedList class too, then do this:
Add the following code in your Vehicle class:
class Vehicle(){
//YOUR OTHER PIECES OF CODES ...
private static Vehicle firstLargeVehicle;
private Vehicle nextLargeVehicle;
private int index;
public void setIndex(int index){
this.index = index;
if(index == 0) Vehicle.firstLargeVehicle = this;
}
public int getIndex(){
return index;
}
public void setNextLargeVehicle(Vehicle nextLargeVehicle){
this.nextLargeVehicle = nextLargeVehicle;
}
public Vehicle getNextLargeVehicle(){
return nextLargeVehicle;
}
public addLargeVehicle(Vehicle newVehicle){
this.nextLargeVehicle = newVehicle;
newVehicle.setIndex(index + 1);
}
public getListSize(){
Vehicle lastOne = this;
while (lastOne.getNextLargeVehicle() != null){
lastOne = lastOne.getNextLargeVehicle();
}
return lastOne.getIndex() + 1;
}
public static Vehicle[] largeVehiclesToArray(){
Vehicle[] result = new Vehicle[firstLargeVehicle.getListSize()]();
Vehicle pointer = firstLargeVehicle;
for (int counter = 0; pointer != null; counter ++){
result[counter] = pointer;
pointer = pointer.getNextLargeVehicle();
}
return result;
}
}
And in your main loop, do something like the following code:
Vehicle vehicle = null;
for(Vehicle newVehicle : allVehicles) {
if (newVehicle.isLarge()){
if (vehicle == null) {
vehicle = newVehicle;
vehicle.setIndex(0);
}else{
vehicle.addLargeVehicle(newVehicle));
}
}
}
Vehicle[] largeVehicles = Vehicle.largeVehiclesToArray();
And the same story goes for normal vehicles.
Any question ?
You can write your loops like this:
for(int i = 0; i < normalVehicles.length; i++)
{
if(normalVehicles[i] == null)
{
normalVehicles[i] = v;
break;
}
}
// if last slot isn't null then it's full
normBool = normalVehicles[normalVehicles.length-1] != null;
I'm trying to compare two BigInts that were manually created and did not use the built-in BigInt class. Right now I'm getting hung up trying to be able to determine how to find the bigger number of the 2. For example if I want to find which number is bigger between 123 and 134, and I pass in both BigInts I want to return a false if 123 is the first number passed or True if the second number is passed. Please see the code below:
private boolean thisBigIntGreaterThanOrEqualToOther(BigInt b1, BigInt b2){
boolean value = true;
if(b1.bigInt.size() >= b2.bigInt.size()){
for(int i = 0; i < b2.bigInt.size(); i++){
if(b1.bigInt.get(i) >= b2.bigInt.get(i)){
value = true;
}
else{
value = false;
}
}
}
else{
value = false;
}
return value;
}
As you can see in my code I thought about trying to compare each digit, but I run into an issue when I get to 1's for each number, it sets the value to true.
BigInt Class Below:
public class BigInt {
//Instance variables for the class, a boolean for the sign and an ArrayList to store the input String
private boolean pos = true;
private ArrayList<Integer> bigInt = new ArrayList<Integer>();
//No argument constructor, creates a big integer of value zero
public BigInt () {
this.pos = true;
}
//Constructor for big integers input as int
public BigInt (int newBigInt) {
String inputInt = Integer.toString(newBigInt);
inputInt = handleSign(inputInt);
inputInt = checkNumber(inputInt);
for(int i = inputInt.length() - 1; i >=0; i--) {
bigInt.add(Integer.parseInt(inputInt.substring(i, i+1)));
}
}
//Constructor for big integers input as strings
public BigInt (String newBigInt) {
newBigInt = handleSign(newBigInt);
newBigInt = checkNumber(newBigInt);
for(int i = newBigInt.length() - 1; i >=0; i--) {
bigInt.add(Integer.parseInt(newBigInt.substring(i, i+1)));
}
}
private String handleSign(String num) {
if(num.charAt(0) == '+' || num.charAt(0) == '-') {
if(num.length() == 1) {
throw new ErrorMessage("Invalid value: sign only, no integer.");
}
if(num.charAt(0) == '-') {
this.pos = false;
}
else {
this.pos = true;
}
num = num.substring(1);
}
return num;
}
// Private method to remove leading zeros from add/subtract methods
private BigInt removeZeros(BigInt result){
for(int i = 0; i < result.bigInt.size(); i++){
if(result.bigInt.get(i) == 0){
result.bigInt.remove(i);
}
}
return result;
}
//Private method to check the number; remove leading zeros and check for leading spaces (throw error message)
private String checkNumber(String num) {
if(num.charAt(0) == ' ') {
throw new ErrorMessage("Invalid value: leading blank space.");
}
if(num.charAt(0) == '0'){
while(num.length() > 1 && num.charAt(0) == '0') {
num = num.substring(1);
}
}
return num;
}
//toString method
public String toString() {
String answer = "";
for(int i = bigInt.size() - 1; i >=0; i--) {
answer = answer + bigInt.get(i);
}
if(this.pos == false){
return "-" + answer;
}
return answer;
The method to compare two BigInts is broken in several ways:
1. You iterate in the wrong direction:
for(int i = 0; i < b2.bigInt.size(); i++)
You start from the least significant digit which means 20 would be considered smaller than 11. Change it to
for(int i = b2.bigInt.size() - 1; i >= 0 ; i--)
2. You override the result of the comparison
If your code reaches the point where it sets value = false; it does not return or exit the loop. That means that in the next iteration the value gets overriden. That means suddenly 13 and 23 are considered equal.
BigInt c = new BigInt("13");
BigInt d = new BigInt("23");
System.out.println(BigInt.thisBigIntGreaterThanOrEqualToOther(c, d));
System.out.println(BigInt.thisBigIntGreaterThanOrEqualToOther(d, c));
The output is
true
true
Change value = false; to return false;
3. You do not check whether b1.bigInt.size() > b2.bigInt.size()
This results in your method returning that 131 is smaller than 23.
Change your code in the following way:
if(b1.bigInt.size() > b2.bigInt.size()){
return true;
} else if(b1.bigInt.size() < b2.bigInt.size()){
return false;
} else {
// the other comparison code
}
Some final remarks:
It is good design to implement the Comparable interface as it allows you to use many library methods with your class.
EDIT: code now does not use library functions anymore
public class BigInt implements Comparable<BigInt> {
...
#Override
public int compareTo(BigInt other) {
int c = this.bigInt.size() - other.bigInt.size();
if (c != 0) {
return c;
} else {
for (int i = this.bigInt.size() - 1; i >= 0; i--) {
c = this.bigInt.get(i) - other.bigInt.get(i);
if (c != 0) {
return c;
}
}
return 0;
}
}
}
I am working on a robot maze where the robot finds the target without bumping into walls. As a "backtrack" method, I need the robot to go in the opposite direction as it did when it first came across a junction. This is my code:
import uk.ac.warwick.dcs.maze.logic.IRobot;
import java.util.ArrayList;
import java.util.*;
import java.util.Iterator;
public class Explorer {
private int pollRun = 0; // Incremented after each pass.
private RobotData robotData; // Data store for junctions.
private ArrayList<Integer> nonWallDirections;
private ArrayList<Integer> passageDirections;
private ArrayList<Integer> beenbeforeDirections;
private Random random = new Random();
int [] directions = {IRobot.AHEAD, IRobot.LEFT, IRobot.RIGHT, IRobot.BEHIND};
public void controlRobot (IRobot robot) {
// On the first move of the first run of a new maze.
if ((robot.getRuns() == 0) && (pollRun ==0))
robotData = new RobotData();
pollRun++; /* Increment poll run so that the data is not reset
each time the robot moves. */
int exits = nonwallExits(robot);
int direction;
nonWallDirections = new ArrayList<Integer>();
passageDirections = new ArrayList<Integer>();
beenbeforeDirections = new ArrayList<Integer>();
// Adding each direction to the appropriate state ArrayList.
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonWallDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageDirections.add(item);
}
}
for(int item : directions) {
if(robot.look(item) == IRobot.BEENBEFORE) {
beenbeforeDirections.add(item);
}
}
// Calling the appropriate method depending on the number of exits.
if (exits < 2) {
direction = deadEnd(robot);
} else if (exits == 2) {
direction = corridor(robot);
} else {
direction = junction(robot);
robotData.addJunction(robot);
robotData.printJunction(robot);
}
robot.face(direction);
}
/* The specification advised to have to seperate controls: Explorer and Backtrack
and a variable explorerMode to switch between them.
Instead, whenever needed I shall call this backtrack method.
If at a junction, the robot will head back the junction as to when it first approached it.
When at a deadend or corridor, it will follow the beenbefore squares until it
reaches an unexplored path. */
public int backtrack (IRobot robot) {
if (nonwallExits(robot) > 2) {
return robotData.reverseHeading(robot);
} else {
do {
return nonWallDirections.get(0);
} while (nonwallExits(robot) == 1);
}
}
// Deadend method makes the robot follow the only nonwall exit.
public int deadEnd (IRobot robot) {
return backtrack(robot);
}
/* Corridor method will make the robot follow the one and only passage.
The exception is at the start. Sometimes, the robot will start with
two passages available to it in which case it will choose one randomly.
If there is no passage, it will follow the beenbefore squares
until it reaches an unexplored path.*/
public int corridor (IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) == 2) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
/* Junction method states if there is more than one passage, it will randomly select one.
This applies to crossroads as well as essentially they are the same.
If there is no passage, it will follow the beenbefore squares until it reaches an unexplored
path. */
public int junction(IRobot robot) {
if (passageExits(robot) == 1) {
return passageDirections.get(0);
} else if (passageExits(robot) > 1) {
int randomPassage = random.nextInt(passageDirections.size());
return passageDirections.get(randomPassage);
} else {
return backtrack(robot);
}
}
// Calculates number of exits.
private int nonwallExits (IRobot robot) {
int nonwallExits = 0;
for(int item : directions) {
if(robot.look(item) != IRobot.WALL) {
nonwallExits++;
}
}
return nonwallExits;
}
// Calculates number of passages.
private int passageExits (IRobot robot) {
int passageExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
passageExits++;
}
}
return passageExits;
}
// Calculates number of beenbefores.
private int beenbeforeExits (IRobot robot) {
int beenbeforeExits = 0;
for(int item : directions) {
if(robot.look(item) == IRobot.PASSAGE) {
beenbeforeExits++;
}
}
return beenbeforeExits;
}
// Resets Junction Counter in RobotData class.
public int reset() {
return robotData.resetJunctionCounter();
}
}
class RobotData {
/* It was advised in the specification to include the variable:
private static int maxJunctions = 10000;
However, as I am not using arrays, but ArrayLists, I do not
need this. */
private static int junctionCounter = 0;
private ArrayList<Junction> junctionList = new ArrayList<Junction>();
private Iterator<Junction> junctionIterator = junctionList.iterator();
// Resets the Junction counter.
public int resetJunctionCounter() {
return junctionCounter = 0;
}
// Adds the current junction to the list of arrays.
public void addJunction(IRobot robot) {
Junction newJunction = new Junction(robot.getLocation().x, robot.getLocation().y, robot.getHeading());
junctionList.add(newJunction);
junctionCounter++;
}
// Gets the junction counter for Junction info method in Junction class.
public int getJunctionCounter (IRobot robot) {
return junctionCounter;
}
// Prints Junction info.
public void printJunction(IRobot robot) {
String course = "";
switch (robot.getHeading()) {
case IRobot.NORTH:
course = "NORTH";
break;
case IRobot.EAST:
course = "EAST";
break;
case IRobot.SOUTH:
course = "SOUTH";
break;
case IRobot.WEST:
course = "WEST";
break;
}
System.out.println("Junction " + junctionCounter + " (x=" + robot.getLocation().x + ", y=" + robot.getLocation().y +") heading " + course);
}
/* Iterates through the junction arrayList to find the
heading of the robot when it first approached the junction. */
public int searchJunction(IRobot robot) {
Junction currentJunction = junctionIterator.next();
while (junctionIterator.hasNext()) {
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
// Returns the reverse of the heading the robot had when first approaching the junction.
public int reverseHeading(IRobot robot) {
int firstHeading = searchJunction(robot);
int reverseHeading = 1; // Random integer to Iniitalise variable.
switch (firstHeading) {
case IRobot.NORTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.AHEAD;
else
reverseHeading = IRobot.LEFT;
break;
case IRobot.EAST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.BEHIND;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.RIGHT;
else
reverseHeading = IRobot.AHEAD;
break;
case IRobot.SOUTH:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.LEFT;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.BEHIND;
else
reverseHeading = IRobot.RIGHT;
break;
case IRobot.WEST:
if (robot.getHeading() == IRobot.NORTH)
reverseHeading = IRobot.RIGHT;
else if (robot.getHeading() == IRobot.EAST)
reverseHeading = IRobot.AHEAD;
else if (robot.getHeading() == IRobot.SOUTH)
reverseHeading = IRobot.LEFT;
else
reverseHeading = IRobot.BEHIND;
break;
}
return reverseHeading;
}
}
class Junction {
int x;
int y;
int arrived;
public Junction(int xcoord, int ycoord, int course) {
x = xcoord;
y = ycoord;
arrived = course;
}
}
Whenever it is backtracking and reaches a junction it has already visited, it freezes and this comes up.
`java.lang.reflect.InvocationTargetException
at sun.reflect.GeneratedMethodAccessor41.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at uk.ac.warwick.dcs.maze.controllers.PolledControllerWrapper.start(PolledControllerWrapper.java:70)
at uk.ac.warwick.dcs.maze.logic.ControllerThread.run(ControllerThread.java:46)
Caused by: java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at RobotData.searchJunction(Explorer.java:242)
at RobotData.reverseHeading(Explorer.java:255)
at Explorer.backtrack(Explorer.java:74)
at Explorer.junction(Explorer.java:122)
at Explorer.controlRobot(Explorer.java:56)
... 5 more`
I don't think your searchJunction() is right or safe, the ConcurrentModificationException might be thrown due to the incorrect iterator through junctionList . The problem should be more about the iterator rather than reflection.
You might try:
private Iterator<Junction> junctionIterator = junctionList.iterator(); doesn't make much sense since the list is empty when initialize a RobotData object. Try to move it into searchJunction()
Check hasNext() first then invoke next()
public int searchJunction(IRobot robot) {
Iterator<Junction> junctionIterator = junctionList.iterator();
while (junctionIterator.hasNext()) {
Junction currentJunction = junctionIterator.next();
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
It looks like that issue is in following code -
`public int searchJunction(IRobot robot) {
Junction currentJunction = junctionIterator.next();
while (junctionIterator.hasNext()) {
if ((((currentJunction.x)==(robot.getLocation().x))) && ((currentJunction.y)==(robot.getLocation().y)))
break;
}
return currentJunction.arrived;
}
You are calling junctionIterator.next() before calling junctionIterator.hasNext(). Iterator specification says that you should call next() only after calling hasNext()
I created an object Student using Comparable with getters/setters as well as a method that overrides compareTo. In a separate file an arraylist of objects is populated from a text file. Now I need to compare the values in the arraylist to another Student object.
The file was used to create an arraylist as below:
try {
private static ArrayList<Student> array = new ArrayList<Student>();
File file = new File("students.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String inline = scanner.nextLine();
String[] split = inline.split(":");
Student myStudent = new Student();
myStudent.setUsername(split[0]);
myStudent.setPassword(split[1]);
array.add(myStudent);
}
scanner.close();
}
catch (FileNotFoundException e)
{
System.out.println("ERROR.");
}
The text file looks like this:
John:password1
Jane:password2
Jack:password3
(One on each line, no blank lines in between.)
And in a separate method a created Student object is compared to the elements in the arraylist:
Student aStudent = new Student();
aStudent.setUsername("student");
aStudent.setPassword("password");
boolean found = false;
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break;
}
else
{
System.out.println("No such records found!");
found = false;
break;
}
System.out.println(found);
}
The problem is that the object aStudent is not being compared with the objects in the arraylist. It does not print out anything (a -1, 0, or 1) for the call to compareTo, but it always shows that found is true, even though it should be false when there are no matches for aStudent in the file (which there aren't any matches to the username "student" or the password "password").
All together my code complies and works - it just works incorrectly.
Sorry if this sounds confusing. In short, my question is how can I compare the objects of an arraylist to another object using the Comparable interface and compareTo? A plus is if you can tell me what I'm doing wrong.
Thank you in advance.
EDIT
Here is the overriding of the compareTo method:
public int compareTo(Student obj){
int result = 1;
if ((this.Username.compareToIgnoreCase(object.Username) < 0) || (this.Password.compareTo(object.Password) < 0))
{
result = -1;
}
else if ((this.Username.compareToIgnoreCase(object.Username) == 0) && (this.Password.compareTo(object.Password) == 0))
{
result = 0;
}
return result;
}
More context would be useful, but your for-loop looks wrong...
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break; // out of loop
}
else
{
System.out.println("No such records found!");
found = false;
break; // break out loop
}
System.out.println(found);
}
The break statement is used to break out of the loop, meaning that you will only ever compare the first element in the list.
The entire else branch isn't required (or at least I don't think it is ;)), for example...
for (int i = 0; i < array.size(); i++)
{
if (array.get(i).compareTo(aStudent) == 0)
{
System.out.println(aStudent.equals(array.get(i)));
found = true;
break; // out of loop
}
}
System.out.println(found);
Updated
Based on you new compareTo code snippet, this...
if ((this.Username.compareToIgnoreCase(object.Username) < 0) || (this.Password.compareTo(object.Password) < 0))
{
result = -1;
}
else if ((this.Username.compareToIgnoreCase(object.Username) < 0) && (this.Password.compareTo(object.Password) < 0))
{
result = 0;
}
seems wrong to me...the else if should be more like
else if ((this.Username.compareToIgnoreCase(object.Username) == 0) && (this.Password.compareTo(object.Password) == 0))
if the contract for the Comparable interface is to be met, where 0 is equal...
For example...
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Test {
private static ArrayList<Student> array = new ArrayList<Student>();
public static void main(String[] args) {
array.add(new Student("John", "password1"));
array.add(new Student("Jane", "password2"));
array.add(new Student("Jack", "password3"));
Student aStudent = new Student("Jack", "password3");
boolean found = false;
for (int i = 0; i < array.size(); i++) {
if (array.get(i).compareTo(aStudent) == 0) {
System.out.println(aStudent.equals(array.get(i)));
found = true;
break;
}
}
System.out.println(found);
}
public static class Student implements Comparable<Student> {
private String name;
private String password;
public Student(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
public void setName(String name) {
this.name = name;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int compareTo(Student object) {
int result = 1;
if ((this.getName().compareToIgnoreCase(object.getName()) < 0) || (this.getPassword().compareTo(object.getPassword()) < 0)) {
result = -1;
} else if ((this.getName().compareToIgnoreCase(object.getName()) == 0) && (this.getPassword().compareTo(object.getPassword()) == 0)) {
result = 0;
}
return result;
}
}
}
Which will print out...
false
true
Where the objects are not equal but where they are comparable...which is kind of weird...to me ;)
Your problem may lie in the compareTo function that you overrode, you need to include that code otherwise no one can determine why certain values are being returned
EDIT:
Note that when objects are created, they are not necessarily equal solely because their contained values are equal. They are separate instances of the object and treated as such.
You will need to override the equals function as well, not just the compareTo function, in order to get the result that you seek.
I wanted to know if there is any method to store if else condition in java? What I mean is like having a variable to represent the condition. This is my original code
private OnClickListener click2 = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText("");
List<Integer> mClickedButtonIds = new ArrayList<Integer>();
int[] mDesiredOrder = new int[] { ans1.getId(), ans2.getId(), ans3.getId(),
ans4.getId(), ans5.getId() };
mClickedButtonIds.add(v.getId());
if (mClickedButtonIds.size() >= mDesiredOrder.length )
{
if (mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3]
&& mClickedButtonIds.get(4) == mDesiredOrder[4]
)
{
tv1.setText("Correct!");
}
else
{
tv1.setText("Try Again!");
}
mClickedButtonIds.clear();
}
}
};
I plan to change it to something like this
private OnClickListener click2 = new OnClickListener() {
#Override
public void onClick(View v) {
tv1.setText("");
List<Integer> mClickedButtonIds = new ArrayList<Integer>();
int[] mDesiredOrder = new int[] { ans1.getId(), ans2.getId(), ans3.getId(),
ans4.getId(), ans5.getId(), ans6.getId() };
switch (main)
{
case 4 : Variable x = mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3];
case 5 : Variable x = mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3]
&& mClickedButtonIds.get(4) == mDesiredOrder[4];
case 6: Variable x = mClickedButtonIds.get(0) == mDesiredOrder[0]
&& mClickedButtonIds.get(1) == mDesiredOrder[1]
&& mClickedButtonIds.get(2) == mDesiredOrder[2]
&& mClickedButtonIds.get(3) == mDesiredOrder[3]
&& mClickedButtonIds.get(4) == mDesiredOrder[4]
&& mClickedButtonIds.get(5) == mDesiredOrder[5];
}
mClickedButtonIds.add(v.getId());
if (mClickedButtonIds.size() >= mDesiredOrder.length )
{
if (x)
{
tv1.setText("Correct!");
}
else
{
tv1.setText("Try Again!");
}
mClickedButtonIds.clear();
}
}
};
The Variable x is something which I would like to ask. Is there any method to do so or is there any variable that can store if else condition. Cause the original code, it is fixed to 5 clicks. Now I want the number of required clicks to change according to how many clicks the user want.
Based on the code snippet, consider a loop:
boolean result = true;
for (int i = 0; i < main; ++i) {
result = result && mClickedButtonIds.get(i) == mDesiredOrder[i];
if (!result)
break; // short-circuit out from loop if false
}
// now you can use "result" to test whether the condition matched all "main" ids
if (result) {
// correct
} else {
// bzzt, try again
}
If I understand correctly, that you want x to be a condition that you may change programatically (but which conforms to some structure) then you can do this using an interface Question and classes which implement that interface
public interface Question {
boolean getResponse(String condition1, int condition2);
}
public class StringIsLongCondition implements Question{
public boolean getResponse(String condition1, int condition2) {
return condition1.length()>condition2;
}
}
public class StringIsShortCondition implements Question{
public boolean getResponse(String condition1, int condition2) {
return condition1.length()<condition2;
}
}
Then use like
Question x;
//some code that selects the question
x= new StringIsShortCondition();
if(x.getResponse(someString, someInt){
//do something
}