go to beginning of for statement in java - 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;
}
}

Related

Print a message only once after iterating 2d array

import java.util.Scanner;
public class Note {
public static void main(String[] args) {
String etudiants[][] = new String[1][4];
Scanner saisie = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
System.out.print("\n\nEtudiant BTI00" + (i + 1) + "\n\n");
for (int j = 0; j < 4; j++) {
if (j == 0) {
System.out.print("\n\tCode de l'etudiant : ");
} else if (j == 1) {
System.out.print("\n\tNom etudiant : ");
} else if (j == 2) {
System.out.print("\n\tNote Maths : ");
} else if (j == 3) {
System.out.print("\n\tNote Francais : ");
} else {
System.out.print("\n\tChamps inexistant!");
}
etudiants[i][j] = saisie.nextLine();
}
}
System.out.print("\n\tEtudiants Enregistres : \n\n");
// System.out.print("\tCode\tNom\t\tMaths\tFrancais\n\n");
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("\t" + etudiants[i][j] + " ");
}
}
System.out.println();
System.out.print("\n\tEntrez code etudiant : ");
String recherche = saisie.nextLine();
boolean trouve = false;
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 4; j++) {
if (recherche.equals(etudiants[i][0])) {
trouve = true;
System.out.print("\n\tCode etudiant correct!");
String math = etudiants[i][2];
String francais = etudiants[i][3];
Double m = new Double(math);
double mathConv = m.doubleValue();
Double f = new Double(francais);
double francaisConv = f.doubleValue();
double moyenne = (mathConv + francaisConv) / 2;
System.out.print("\n\tMoyenne de l'etudiant : " + moyenne);
System.out.print("\n\tEtudiant : " + etudiants[i][j]);
if (moyenne <= 40) {
System.out.print("\n\tEchec!");
} else if (moyenne > 40 && moyenne < 70) {
System.out.print("\n\tReprise!");
} else {
System.out.print("\n\tSucces!");
}
} if (!trouve) {
System.out.print("\n\tCode etudiant incorrect!");
}
}
}
}
}
I need to display only one message after entering the code etudiant but istead it displays the message 4 times. The loop should only iterate through the first column of each line and compares it to what the user entered.
The indexing variable (j) of the last inner for-loop (for (int j = 0; j < 4; j++) {) is never used inside the loop, so you actually do not need that loop at all. General styling issues of your sample aside, you should rewrite the last loop like this:
for (int i = 0; i < 1; i++) {
// throw away this
//for (int j = 0; j < 4; j++) {
if (recherche.equals(etudiants[i][0])) {
trouve = true;
// ... rest of the code like you currently have it
// You probably do not need this line too,
// because you have almost the same in your second loop
//System.out.print("\n\tEtudiant : " + etudiants[i][j]);
}
}

Word Search Program for loops not working

I have this code that will take a word search and find words in it. I got it to work for some things, i tired BINARY and i tried DRAC and it worked, but for some stuff, especially the diagonals, keep giving me outofbounds errors.
import java.util.Scanner;
public class WordSearch {
public static void main(String[] args) {
Scanner kboard = new Scanner(System.in);
char[][] maze = { {'A','P','B','I','N','A','R','Y','D','C','O','C','A','R','D'},
{'M','T','C','O','S','M','A','L','L','E','A','A','T','E','B'},
{'P','O','E','N','A','M','G','I','S','R','L','N','S','I','R'},
{'R','L','D','H','M','A','S','P','I','N','S','T','E','S','T'},
{'A','E','A','E','T','G','T','A','B','M','U','H','A','S','G'},
{'L','M','G','N','R','E','D','O','O','P','B','E','F','E','H'},
{'U','Y','L','O','E','N','O','K','A','L','L','R','A','M','T'},
{'C','I','E','V','E','T','E','C','U','N','A','C','D','Y','I'},
{'R','C','C','A','E','H','S','E','E','W','N','U','E','T','A'},
{'I','I','I','S','O','N','W','D','D','O','O','L','O','H','N'},
{'C','T','N','L','E','H','S','O','H','R','L','E','U','O','J'},
{'I','A','E','P','I','R','A','M','O','C','I','S','T','L','I'},
{'M','N','R','T','A','E','L','D','E','R','S','P','O','O','L'},
{'E','E','E','E','N','R','E','T','T','A','P','A','T','G','I'},
{'S','V','B','L','A','C','K','H','O','L','E','S','O','Y','N'}, };
for(int i = 0; i <= 14; i++)
{
for(int j = 0; j <= 14; j++)
{
System.out.print(maze[i][j] + " ");
}
System.out.println();
}
String input = kboard.nextLine();
//checking the word search horizontally
for(int r = 0; r <= maze.length - 1; r++)
{
for(int c = 0; c <= (maze.length - input.length()); c++)
{
boolean match = true;
for(int i=0; i<input.length(); i++)
{
if(maze[r][c + i] != input.charAt(i))
{
match = false;
break;
}
}
if(match)
{
System.out.print("Found match (horizontal) for " + input + " starting at (" + r + ", " + c + ")");
}
}
}
//checking the word search backwards horizontally
for(int r = 0; r < maze.length - 1; r++)
{
for(int c = 0; c <= (maze.length + 3 - input.length()); c++)
{
boolean match = true;
for(int i = 0; i < input.length(); i++)
{
if(maze[r][c - i] != input.charAt(i))
{
match = false;
break;
}
}
if(match)
{
System.out.print("Found match (backwards horizontal) for " + input + " starting at (" + r + ", " + c + ")");
}
}
}
//checking the word search diagonally down
for(int r = 0; r < maze.length - 1; r++)
{
for(int c = 0; c <= (maze.length - input.length()); c++)
{
boolean match = true;
for(int i = 0; i < input.length(); i++)
{
if(maze[r + i][c + i] != input.charAt(i))
{
match = false;
break;
}
}
if(match)
{
System.out.print("Found match (diagonal down) for " + input + " starting at (" + r + ", " + c + ")");
}
}
}
//searching the word search diagonally up
for(int r = 0; r < maze.length - 1; r++)
{
for(int c = 0; c <= (maze.length - input.length()); c++)
{
boolean match = true;
for(int i = 0; i < input.length(); i++)
{
if(maze[r - i][c - i] != input.charAt(i))
{
match = false;
break;
}
}
if(match)
{
System.out.print("Found match (diagonal up) for " + input + " starting at (" + r + ", " + c + ")");
}
}
}
}
}
Ive tried numbers and keep getting errors like
Found match (horizontal) for BLACKHOLE starting at (14, 2)
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at WordSearch.main(WordSearch.java:112)`
Also, is it bad to use the same for loop each time? Do i only need to change the one line in the third for loop of each one?
This line is causing issues:
if(maze[r - i][c - i] != input.charAt(i))
Because the loop only increments i and c, r remains at 0, so 0 - 1 = -1, hence out of bounds.
Adjusting to:
if(maze[r][c - i] != input.charAt(i))
Stops the out of bounds error, and the loops seem to go through all the columns of each row when searching "BLACK", but doesn't make diagonally searching work well.
You don't ask for different approaches, but you could try going from every point on the grid in all directions, and catching/ignore any outofbounds exceptions, since you know they will be false results, just a thought.

Stopping an inner loop after one correct iteration

The problem in the code is in the goldbach method. I want to stop iteration of the inner two loops after the inner most loop has found one pair of numbers, but I am not getting how to exit just those two loops. In other words, I only want to find only one pair per i integer created by the outermost for loop, and then move on to the next integer i.
Below is my code:
import java.util.Arrays;
import java.awt.List;
import java.util.ArrayList;
// finding prime numbers using sieve of Eratosthenes and golbach's conjecture
public class Test {
public static void main(String[] args) {
int[] num = new int[1000000];
for (int i = 2; i <= num.length; i++) {
num[i - 1] = i;
}
Test.sieve(num);
Test.goldbach(num);
}
public static void sieve(int[] array) {
for (int i = 2; i < Math.sqrt(array.length); i++) {
if (array[i - 1] == 0) {
continue;
}
for (int j = 2 * i; j <= array.length; j += i) {
array[j - 1] = 0;
}
}
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
//System.out.print(array[i] + " ");
}
}
//System.out.println(Arrays.toString(array));
}
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break;
}
}
}
}
}
}
You could set the value of j in your second loop. eg.
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
j = i + 1; // This will end the outer loop as well.
break;
}
}
}
}
use a label to break (or continue) a loop other than the inner one:
found:
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
break found;
}
}
}
or use an additional method and return - more indicated if that new method has an own clear function (and better name)
public static void goldbach(int[] array) {
for (int i = 2; i <= 1000000; i += 2) { //to go through every even integer
primeAdd(i);
}
}
private static void primeAdd(int i) {
for (int j = 0; j <= i; j++) {
for (int k = 0; k <= i; k++) {
System.out.println("two prime numbers that add to " + i + " are " + array[j] + " and " + array[k]);
return;
}
}
}
but, as already commented by bureaquete, there is no need for the inner loop since it is always being terminated.

java - Exercise, do not work properly on the subject arrays

Check if the matrix is folded from.
The test should make:
image
The code always returns false and it is unclear to me why. What's wrong with the code?
the code:
public class test1 {
public static void main(String[] args) {
int[][] mat = { { 1, 7, 9 }, { 2, 9, 7 }, { 9, 2, 1 } };
boolean flag = true;
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
System.out.print("[" + mat[i][j] + "]");
}
System.out.println();
}
for (int i = mat.length - 1; i > -1; i--) {
for (int j = mat.length - 1; j > -1; j--) {
if (i == j) {
j--;
}
if (mat[i][j] != mat[j][i]) {
flag = false;
System.out.println("mat[i][j]" + mat[i][j] + " " + i + " "
+ j);
j = -1;
i = -1;
}
}
}
if (flag == false) {
System.out.println("Not first folded matrix");
} else {
System.out.println("First folded matrix");
}
}
}
thank you
You can use this function:
public static boolean isFolded(int[][] mat){
for (int i = 0; i < mat.length; i++) {
for (int j = 0; j < mat.length; j++) {
if (i == j) {
continue;
}
if (mat[i][j] != mat[mat.length - 1 - j][mat.length - 1 - i]) {
System.out.println("mat[i][j] " + mat[i][j] + " i:" + i + " j:"
+ j);
return false;
}
}
}
return true;
}
Call it in you main like:
flag = isFolded(mat);

Console-based Connect Four game - diagonal win checker algorithm

I'm more or less new to Java.
I'm making a console-based connect 4 game in java and I'm pretty much done, I'm just struggling with how to check for a diagonal win (four pieces in a row diagonally). My vertical/horizontal win checkers are working fine, but I can't figure out how to do a similar thing for a diagonal-checker. The board is a 2d-array which is printed to the console, and to check for a win, I check for four of the same piece next to each other or above each other.
Here are the bits of board code:
private String board[][] = new String[8][8];
creates array
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = "( )";
}
}
fills the board with blank slots
void displayBoard() {
for (int i = 1; i < 9; i++) {
System.out.print(" " + i + " ");
}
System.out.println();
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
And here is the winchecker
boolean winCheck1() {
String p = "(" + piece1 + ")";
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 5; j++) {
if ((board[i][j].equals(p) && board[i][j + 1].equals(p)
&& board[i][j + 2].equals(p) && board[i][j + 3]
.equals(p))) {
this.win1();
return false;
}
}
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 5; j++) {
if ((board[j][i].equals(p) && board[j + 1][i].equals(p)
&& board[j + 2][i].equals(p) && board[j + 3][i]
.equals(p))) {
this.win1();
return false;
}
}
}
this.play2();
return false;
}
Any help would be appreciated. Thanks!
If you want to keep doing it your way:
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if ((board[j][i].equals(p) && board[j + 1][i + 1].equals(p)
&& board[j + 2][i + 2].equals(p) && board[j + 3][i + 3]
.equals(p))) {
this.win1();
return false;
}
}
}
for (int i = 3; i < 8; i++) {
for (int j = 0; j < 5; j++) {
if ((board[j][i].equals(p) && board[j + 1][i - 1].equals(p)
&& board[j + 2][i - 2].equals(p) && board[j + 3][i - 3]
.equals(p))) {
this.win1();
return false;
}
}
}
However, it's probably better to do this with loops (iterate over directions).

Categories

Resources