This question already has answers here:
Java - How do you make a jButton# index take the value of an int variable?
(2 answers)
Closed 7 years ago.
I am making a game in Java. I want to be able to check whether a level has been previously visited.
I came up with this:
public class LevelTracker {
boolean depth1visited = false;
boolean depth2visited = false;
// ..
boolean depth100visited = false;
private boolean LevelTracking() {
if (Dungeon.depth == 1) {
depth1visited = true;
}
if (Dungeon.depth == 2) {
depth2visited = true;
}
// ..
if (Dungeon.depth == 100) {
depth100visited = true;
}
}
}
In my situation, each depth must be checked independently since any level might be accessed from any other level. So this:
if (depth > deepestdepth) {
deepestdepth = depth;
}
won't work in my situation. Unless I'm wrong, which is possible. I am, as you can probably tell, a novice at this.
What is a better way to do this? Could a for loop be used in this situation?
Use arrays, which can be addressed by index. This can replace all your ifs and your 100 separate variables.
boolean[] depthVisited = new boolean[100]; // default values: false
Then you can access the array by calculating an index.
depthVisited[Dungeon.depth - 1] = true; // 0-based index
No for loop is necessary.
Related
This question already has answers here:
Comparing two integer arrays in Java
(10 answers)
Closed 1 year ago.
I have a program that uses a java.awt robot to get a picture of the screen and then cycle through the pixels and categorize certain colors in blocks in a list of lists of integer arrays. I have a List<List<int[]>> blocks. The first List is a list of all the blocks, the second list is a list of all the pixels in the blocks, and the integer array is 2 value that are the x and y of the pixel. I first tried to use a for loop through all the blocks with list.contain's to find the array, but that always returned false. I am trying now to use a loop like this to find them.
boolean continuer = false;
boolean found = false;
for (List<int[]> thisBlock : blocks) {
int[] newInt = new int[2];
newInt[0] = i;
newInt[1] = j;
for (int[] thisInt : thisBlock) {
if (thisInt == newInt) {
continuer = false;
found = true;
System.out.println("Found pixel in block");
break;
}
if (found) {
break;
}
}
if (found) {
break;
}
}
if (!found) {
continuer = true;
}
This also returned false always. Any help would be greatly appreciated.
Arrays cannot be compared with == operator. There are methods that Arrays Class provides to perform operations on Arrays. Use Arrays.equals(thisInt,newInt) instead of thisInt == newInt
This question already has answers here:
How do I generate random integers within a specific range in Java?
(72 answers)
Closed 6 years ago.
I have recently begun programming at university and I am a little stumped with one of my tutorial problems.
I basically need to create a method within a class which uses the Random.nextInt()
method to flip a coin, assigning and saving the value once the process has been run.
MY current attempts include this:
public void Flip() {
int flipResult;
flipResult = mRandNumGen.nextInt(1);
if(flipResult == 0)
{
mFace = 'H';
}
else
{
mFace = 'T'
}
}
mFace and mRandNumGen are variables which have been declared already outside the specific method. What exactly is going wrong here? I can't for the life of me get this to work :/
Simple way to do this:
if (mRandNumGen.nextBoolean()) {
mFace = 'H';
} else {
mFace = 'T';
}
The first argument in Random.nextInt is an exclusive upper bound, not inclusive.
So with n=1 it will always return 0. for n=2 it will return either 0 or 1 which is what you're looking for.
Note: Not a duplicate of How do I compare strings in java as I am taking about going through some checks to determine if something is inheriting something something else
Is their a better and more efficient way to do this:
As you can see I am inputting 2 strings then checking them of on a list, as if current = three then it returns true for checking for one, two and three
NOTE: these values(one,two,three) are just placeholders for the example in my use their is no relation between them except that they have a different priority.
public boolean checker(String current, String check) {
if (check.equals("one")) {
if (current.equals("one") || current.equals("two")
|| current.equals("three")) {
return true;
}
}
if (check.equals("two")) {
if (current.equals("two") || current.equals("three")) {
return true;
}
}
if (check.equals("three")) {
if (current.equals("three")) {
return true;
}
}
return false;
}
Here are a few pointers
As Frisch mentioned in comments, use .equals rather than == for String comparison.
Use switch/case
switch (check) {
case "one":
if (current.equals("one")) return true;
case "two":
if (current.equals("two")) return true;
case "three":
if (current.equals("three")) return true;
}
Apart from that, there doesn't seem to be much to do.
Two things.
Don't check strings using equality. Use the .equals() method. You can call it off the string literal. So something like this. Calling it off the string literal is safe even with nulls, which is generally a good thing.
if ("one".equals(check))
You can take advantage of Java's short circuit operators && and ||
if ("one".equals(check)) {
if ("one".equals(current) || "two".equals(current) || "three".equals(current)) {
return true;
}
}
Can become
if ("one".equals(check) && ("one".equals(current) || "two".equals(current) || "three".equals(current))) {
return true;
}
Which will be evaluated from left to right. Since the "one".equals(check) is on the far most left, and is &&'ed with the rest of the statement, Java will bail out of the condition checking if "one".equals(check) is not true, and will not evaluate the rest of the statement.
Since you're just returning true or false, you can also take this a step further and reduce all of your if statements into a single one using De Morgan's laws (http://en.wikipedia.org/wiki/De_Morgan's_laws). Generally you state your boolean if statement in the way that is most natural to you, and then you start simplifying it by applying transformations that keep the logical if statement the same.
A good example of this is, stolen from the below link.
In the context of the main method's program body, suppose the following data is defined:
int score, min = 0, max = 20;
boolean bad, good;
Further suppose that a value is assigned to score, perhaps from a keyboard entry, and I would like to test, with a Boolean expression whether the score is a valid number or not. A good score is in the closed range [0 .. 20], which includes 0 and 20.
good = (score >= min && score <= max);
I would like to get the score from the keyboard in a do while loop, so that I can validate the entry. The logic in my control structure is to demand another entry for the score while the entry is bad. I have a definition of a good entry, and I will use definitions of operators and De Morgan's Law to help me write an expression that represents a bad entry.
good = (score >= min && score <= max); // original definition of good from the logic of my task
good = !(score < min) && !(score > max); // by definition, >= means ! < , <= means ! >
good = !(score < min || score > max); // by De Morgan's' Law
bad = !good ; // bad is not good
bad = !!(score < min || score > max); // substituting for good
bad = score < min || score > max; // double negation is dropped
http://fcmail.aisd.net/~JABEL/1DeMorgansLaw.htm
I would like to update you some thing.
1. We can apply switch cases only on primitive data types but not on objects. As string is object we can't use strings in case/switch statement.
I would like to suggest you to enums/maps in this case.
Please find the below sample programm how i implemented using maps.
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
String current = "one";
String check = "one";
if(map.get(check)<=map.get(current)){
System.out.println("Our condition is success");
}
}
Instead of multiple comparison this is better.
---Santhosh
I am currently making a text adventure game in Java, but I have come across a problem:
I need the value of a String variable to change each time the value of a particular int variable changes.
I want the program to perform this task (then continue where it left off) each time the value of an int variable changes:
if (enemyposition == 1) {
enemyp = "in front of you";
}
else if (enemyposition == 2) {
enemyp = "behind you";
}
else if (enemyposition == 3) {
enemyp = "to your left";
}
else if (enemyposition == 4) {
enemyp = "to your right";
}
else {
enemyp = "WOAH";
}
Thanks! :D
You could make the code much shorter using an array.
String[] message = {"WOAH", // 0
"in front of you", // 1
"behind you", // 2
"to your left", // 3
"to your right"}; // 4
enemyp = (enemyposition > 0 && enemyposition < 5) ? message[enemyposition] :
message[0];
The question you're asking sounds like it might be answerable by creating a class to hold the enemyposition integer. Add a "setter" method to your class to set the integer. You can write your setter method so that when the integer is set, it also sets up a string. Then write a "getter" method to retrieve the string. That's one common way of making sure two variables change together.
public class EnemyPosition {
private int enemyposition;
private String enemyp;
public void setPosition(int n) {
enemyposition = n;
enemyp = [adapt your code to set this based on the position]
}
public String getEnemyp() {
return enemyp;
}
}
I'm sure there are a lot of details missing, but you get the idea. Then instead of int enemyposition in the rest of your code, use EnemyPosition enemyposition = new EnemyPosition(), and use the setPosition method instead of assigning to it.
That's not the only solution (an array or Map that maps integers to strings may be good enough), but it's one OOP way to do things.
I am learning about Recursions, and I haven't fully grasped it yet. So here I am trying to do an assignment on recursion but I'm stuck.
In this assignment, I am supposed to ask the user to input phrases, and the program determines whether it's a palindrome or not. We are supposed to accomplish this task using recursions.
This is the section with the recursion, and I can't quite figure out how to tackle it, as when I run it, I get no error, but it always comes up as false.
I'm using a ArrayList to keep all the user input.
Here's the code I've got right now
//instance variables
private boolean det;
private String input;
private String inputHelp;
//constructor
public RecursivePalindrome(String i)
{
det = false;
input = i;
inputHelp = "";
}
//determines if the method is a palindrome or not using recursions
public boolean palindrome(String b)
{
if(inputHelp.length() == 0)
{
det = true;
}
if(inputHelp.substring( 0 , 1 ).equals(inputHelp.substring( inputHelp.length() )))
{
inputHelp = inputHelp.substring( 1, inputHelp.length());
palindrome(inputHelp);
}
else
{
det = false;
}
return det;
}
There are three mistakes. First, note the substring documentation: second parameter is the end index "exlusive". Secondly, you need to use the result of the recursive call. And finally (as pointed out correctly by ajb in the comments), you should account for palindromes with odd letter count (first condition):
if (inputHelp.length() <= 1)
{
det = true;
}
else if (inputHelp.substring(0, 1)
.equals(inputHelp.substring(inputHelp.length() - 1)))
{
inputHelp = inputHelp.substring( 1, inputHelp.length() - 1);
det = palindrome(inputHelp);
}
else
{
det = false;
}
Also, you can make it a bit more readable:
public boolean palindrome(String b)
{
if (b.length() <= 1)
{
return true;
}
if (b.substring(0, 1)
.equals(b.substring(b.length() - 1)))
{
return palindrome(b.substring(1, b.length() - 1));
}
return false;
}
Further improvements can be made - lines still seem to long, especially the second condition (left as an exercise for the reader ;)).
As far as I can tell you are never setting inputHelp to anything other than an empty string, and the string b which is passed in to your method is not used anywhere.
So the method will never call back on to itself, and even if it did the value passed in would not be used for anything, rendering the recursion useless.