Java: Array with loop(matches) - java

I need to find the first match in this task. Probably i am just missing something. As you can see, i found the last match.I am not copied the first half of the code. Thank you.
for (int i = 0; i <= n - 1; i++) {
if (iv[i] == a) {
hely = i;
}
}
if (hely == -1) {
System.out.println("text");
} else {
System.out.println("text " + a + " text " + (hely + 1) + "text");
}

break the loop when you find first match.
for (int i = 0; i <= n - 1; i++) {
if (iv[i] == a) {
hely = i;
break;
}
}

You need to exit the for loop after finding the first match:
for (int i = 0; i <= n - 1; i++) {
if (iv[i] == a) {
hely = i;
break;
}
}

Related

Checking adjacent tiles in 2-dimensional array

So i'm trying to make a game of Connect Four in Java, instead I'm connecting 6 instead of 4.
I have a 2-dimensional array and X amount of players. I have to check if 6 blocks in succession (horizontal, vertical and diagonal) are marked by the same player. If they are, the program should print who won.
Now, I don't have problems with the checking or determining who won, though for the life of me I can't figure out how to prevent the program from crashing whenever it tries to check for a block that's outside the array.
Now, I'm trying to avoid using try-catch or plopping 8 loops one after the other, and instead use one method for all of the directions with just variation in the parameters but I can't seem to make it work :\
Does anyone have a suggestion on how this might work?
I'm a beginner in programming and I've possibly missed something so that's why I'm asking for help :)
Cheers
Edit: here's the code. It's a bit long, that's why i want to shorten it and make it work somehow. the Terminal class is the same as the System.out.println one.
void checkIfPlayerWins(Field field, Integer rowNumber, Integer colNumber) {
Integer counter = 1;
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber, colNumber + i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber + i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber - i, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber - i)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber)) {
counter++;
} else {
break;
}
}
for (int i = 1; i <= 6; i++) {
if (field.isOccupied(rowNumber + i, colNumber + i)) {
counter++;
} else {
break;
}
}
if (counter == 6) {
Terminal.printLine("");
}
}
here's the isOccupied method
boolean isOccupied(Integer x, Integer y) {
return !this.field[x][y].equals("**");
}
You could simply handle the case where you're attempting to check whether the Field is occupied at invalid coordinates in your isOccupied method:
boolean isOccupied(Integer x, Integer y) {
if(x < 0 || y < 0 || x >= numberOfColumns || y >= numberOfRows) {
// Attempting to check outside the grid: it's non-occupied.
return false;
}
return !this.field[x][y].equals("**");
}

Algorithm in array works for i=1 only

Hello fellow eingineers/programmers. I'm calculating the course of the moment from right to left of a cantilever arm. problem: the algorithm works for a=0, a=1 and then it doesn't work. Code below:
objekte[] is an array of objects of two classes- Einzelmoment (moment) and Punktlast (single force).
for (int a = 0; a < verlauf[0].length; a++) {
for (int k = 0; k < objekte.length; k++) {
if (a == 0) {
verlauf[0][0] = objekte[k].getLage();
verlauf[1][a] = objekte[k].getKraft();
if (objekte[k].getClass() == Punktlast.class) {
verlauf[2][a] = -(objekte[k].getKraft() * (objekte[a]
.getLage() - objekte[k].getLage()));
} else if (objekte[k].getClass() == Einzelmoment.class) {
verlauf[2][a] = -(objekte[k].getMoment());
}
}
else {
verlauf[0][a] = objekte[k].getLage();
verlauf[1][a] = objekte[k].getKraft() + verlauf[1][a - 1];
if (objekte[k].getClass() == Punktlast.class) {
for (int j = 1; j == k; j++) {
if (objekte[k - j].getClass() == Einzelmoment.class) {
verlauf[2][a] += -(objekte[k - j].getMoment());
} else if (objekte[k - j].getClass() == Punktlast.class) {
verlauf[2][a] += -(objekte[k - j].getKraft() * (objekte[k- j].getLage() - objekte[k].getLage()));
}
j++;
}
}
else if (objekte[k].getClass() == Einzelmoment.class) {
for (int j = 1; j == k; j++) {
if (objekte[k - j].getClass() == Einzelmoment.class) {
verlauf[2][a] += -(objekte[k - j].getMoment() + objekte[k].getMoment());
} else if (objekte[k - j].getClass() == Punktlast.class) {
verlauf[2][a] += -(objekte[k - j].getKraft() * (objekte[k- j].getLage() - objekte[k].getLage()));
}
j++;
}
}
}
a++;
}
}
Hope somehow this makes sense. As you can see here, it works for a=1 but it doesn't continue to the rest of the objects. Where's the problem in the code that it stops by a=1? Thank you in advance!

Why is this loop within a loop not running to completion?

I need the loop to iterate through A1,A2..A8..B8...H8 but it stops at C3 for some reason. For the life of me I cannot figure out why this loop within a loop is not running.
P.S letters is just an arraylist of the alphabet {A,B,C...Z} and getValue() just returns a value depending on how much a letter is worth.
int bestMove = 0;
for(int i = 0; i < 8; i++){
for(int x = 0; x < 8; x++){
System.out.println(letters.get(i) + "" + (x+1));
int distanceRow = currentRow - i;
int distanceCol = currentCol - x;
distanceRow = Math.abs(distanceRow);
distanceCol = Math.abs(distanceCol);
if(currentRow == i && currentCol == x){
System.out.println("if");
} else if (distanceRow - distanceCol == 0) {
bestMove = getValue(getPiece(i, x));
System.out.print("else if");
System.out.println(letters.get(i) + "" + (x+1));
} else {
System.out.print(letters.get(i) + "" + (x+1));
System.out.println("else");
}
}
Edit: I tested it as was suggested and it seems theres an error with this method although I dont know what since it just returns a value
public int getValue(String piece) {
if (piece.equals(w1)) {
return 1;
} else if (piece.equals(w2)) {
return 3;
} else if (piece.equals(w3)) {
return 3;
} else if (piece.equals(w4)) {
return 5;
} else if (piece.equals(w5)) {
return 9;
}
return 0;
}

Cannot read repeating characters

I'm writing a code to read a string and count sets of repeating
public int countRepeatedCharacters()
{
int c = 0;
for (int i = 1; i < word.length() - 1; i++)
{
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
if ( word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
return c;
}
If I try the input
aabbcdaaaabb
I should have 4 sets of repeat decimals
aa | bb | aaaa | bb
and I know I'm not reading the first set aa because my index starts at 1. I tried fixing it around to read zero but then I tr to fix the entire loop to work with the change and I failed, is there any advice as to how to change my index or loop?
Try this code:
public int countRepeatedCharacters(String word)
{
int c = 0;
Character last = null;
bool counted = false;
for (int i = 0; i < word.length(); i++)
{
if (last != null && last.equals(word.charAt(i))) { // same as previous characted
if (!counted) { // if not counted this character yet, count it
c++;
counted = true;
}
}
else { // new char, so update last and reset counted to false
last = word.charAt(i);
counted = false
}
}
return c;
}
Edit - counted aaaa as 4, fixed to count as 1
from what I understood from your question, you want to count number of repeating sets, then this should help.
for (int i = 0; i < word.length()-1; i++){
if (word.charAt(i) == word.charAt(i + 1)){ // found a repetition
if (i==0 || word.charAt(i - 1) != word.charAt(i)) {
c++;
}
}
}
Try this----
public int countRepeatedCharacters()
{
int c = 0,x=0;
boolean charMatched=false;
for (int i = 0; i < word.length(); i++)
{
if(i==word.length()-1)
{
if (word.charAt(i-1) == word.charAt(i))
c++;
break;
}
if (word.charAt(i) == word.charAt(i + 1)) // found a repetition
{
charMatched=true;
continue;
}
if(charMatched==true)
c++;
charMatched=false;
}
return c;
}
Try this method. It counts the sets of repeating charactors.
public static void main(String[] args) {
String word = "aabbcdaaaabbc";
int c = 0;
for (int i = 0; i < word.length()-1; i++) {
// found a repetition
if (word.charAt(i) == word.charAt(i + 1)) {
int k = 0;
while((i + k + 1) < word.length()) {
if(word.charAt(i+k) == word.charAt(i + k + 1)) {
k++;
continue;
}
else {
break;
}
}
c++;
i+=k-1;
}
}
System.out.println(c);
}
You can try something like this:-
public static void main(String str[]) {
String word = "aabbcdaaaabbc";
int c = 1;
for (int i = 0; i < word.length() - 1; i++) {
if (word.charAt(i) == word.charAt(i + 1)) {
c++;
} else {
System.out.println(word.charAt(i)+ " = " +c);
c = 1;
}
}
System.out.println(word.charAt(word.length()-1)+ " = " +c);
}
You can modify this as per your needs, by removing the sysouts and other stuffs.
Using length() -1 is causing you to not consider the last character in your calculations.
This is causing you to lose the last repetitive character.
Finally, I would have done this as follows:
public static int countRepeatedCharacters(String word)
{
boolean withinRepeating = false;
int c = 0;
for (int i = 1; i < word.length(); i++)
{
if (!withinRepeating && (withinRepeating = word.charAt(i) == word.charAt(i - 1)))
c++;
else
withinRepeating = word.charAt(i) == word.charAt(i - 1);
}
return c;
}

go to beginning of for statement in java

I'm very new to Java and maybe my question is a bit irritating.
I have two for loops in my code and I want to go to the beginning of each one by a for-else statement.
public static void main(String[] args)
{
int[][] x=new int[1000][1000];
int[] Z=new int[1000];
lable1:
for(int i=1; i<=1000; i++)
{
Z[i]=rand1.nextInt(1000);
System.out.println("Z["+i +"] = " + Z[i] );
if(Z[i]>0 && Z[i]<=Nk)
{
int Z1=Z[i]-1;
lable2:
for(int j = 1; j<=Z1;j++ )
{
x[i][j]= rand2.nextInt(1000);
sum+=x[i][j];
if( sum<1000)
{
x[i][(j+1)]=1000-sum;
System.out.println("x[" + i+"][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i+"][" + (j+1) + "] = " +x[i][(j+1)]);
}
else{
// ????
//Goto lable2;
}
}
}
else{
//goto label1;
// ????
}
}
}
You can break to any defined label (within scope) by using:
break label;
Same holds for continue.
Here is something to read.
In your particular example, removing the elses would do what you want.
Just use continue keyword.. It will continue with the next iteration.. No need to label your loop.. As you are not continuing the outer loop from the inner one.. Or, if you want to continue with outer loop, you can use continue with a label...
And you should use your for loop from j = 0 to j < z1..
for(int j = 0; j < Z1;j++ ) {
if( sum<1000) {
x[i][(j+1)]=1000-sum;
System.out.println("x[" + i+"][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i+"][" + (j+1) + "] = " +x[i][(j+1)]);
}
else{ // Not needed if your else does not contain anything else..
continue;
}
}
In fact you don't need an else block at all.. If you are not doing any further processing in it..
Just remove it.. It will automatically go to your loop..
Suggestion: - You should use coding convention.. variable names start with lowercase letter or underscore.. (Z1 -> z1)
Here you are:
public static void main(String[] args) {
int[][] x = new int[1000][1000];
int[] Z = new int[1000];
boolean resetOuterCycle = true;
for (int i = 0; i < 1000; i++) {
Z[i] = rand1.nextInt(1000);
System.out.println("Z[" + i + "] = " + Z[i]);
if (Z[i] > 0 && Z[i] <= Nk) {
int Z1 = Z[i] - 1;
boolean resetInnerCycle = true;
for (int j = 0; j < Z1; j++) {
x[i][j] = rand2.nextInt(1000);
sum += x[i][j];
if (sum < 1000) {
x[i][(j + 1)] = 1000 - sum;
System.out.println("x[" + i + "][" + j + "] = " + x[i][j]);
System.out.println("Nx[" + i + "][" + (j + 1) + "] = " + x[i][(j + 1)]);
} else if (resetInnerCycle) {
j = 0;
resetInnerCycle = false;
}
}
} else if (resetOuterCycle) {
i = 0;
resetOuterCycle = false;
}
}
}
- In your above code you can use 2 approach to do it...
1st Approach : No else part
for (int i = 0; i < 1000; i++) {
if (Z[i] > 0 && Z[i] <= Nk){
for (int j = 0; j < Z1; j++) {
if(sum < 1000){
}
}
}
}
2nd Approach : With else part and continue
for (int i = 0; i < 1000; i++) {
if (Z[i] > 0 && Z[i] <= Nk){
for (int j = 0; j < Z1; j++) {
if(sum < 1000){
}else{
continue;
}
}
}else{
continue;
}
}

Categories

Resources