在二维数组中搜索值

时间:2013-11-10 18:23:28

标签: java arrays search multidimensional-array

我遇到麻烦的部分是在破折号之后。我需要在二维数组中搜索两个用户输入的数字。他们使用它的方式,总是说值存在,并且它没有指定数字正确的索引。

import javax.swing.*;
import java.util.*;

public class labActivityArrays{

public static void main(String[] args){

String rowS;
rowS = JOptionPane.showInputDialog("Number of rows: ");
int row =  Integer.parseInt(rowS);
String columnS;
columnS = JOptionPane.showInputDialog("Number of columns: ");
int column = Integer.parseInt(columnS);

String initialS;
initialS = JOptionPane.showInputDialog("Initial value: ");
int initial =  Integer.parseInt(initialS);

int[][] arr = new int [row][column];

int temp = initial; 

for(int i=0; i < row; i++){
  for(int j=0; j < column; j++){
     arr[i][j] = temp;
     temp += 1;
  }
}

for(int i=0; i < row; i++){
  for(int j=0; j < column; j++){
     System.out.print(arr[i][j] + " ");
  }
  System.out.println();
}

String check1S;
check1S = JOptionPane.showInputDialog("First value to check for: ");
int check1 =  Integer.parseInt(check1S);

String check2S;
check2S = JOptionPane.showInputDialog("Second value to check for: ");
int check2 =  Integer.parseInt(check2S);

// --------------------------------------------- ----

boolean found = false;    

int i = 0;
int j = 0;

//for the first value
for(i = 0; i < row; i++){
  for(j=0; j < column; j++){
     if(arr[i][j] == check1){
        found = true;      
        break;
     }
  }
}

if(found){
  System.out.println("Found " + check1 + " at index [" + i + "][" + j + "].");
}
else{
  System.out.println(check1 + " is not in this array.");
}

//for the second value
for(i = 0; i < row; i++){
  for(j=0; j < column; j++){
     if(arr[i][j] == check2){
        found = true;      
        break;
     }
  }
}

if(found){
  System.out.println("Found " + check2 + " at index [" + i + "][" + j + "].");
}
else{
  System.out.println(check2 + " is not in this array.");
}


}
}

这是破折号后面的新代码:

boolean found = false;
int i = -1;
int j = -1;

//for the first value  
while(!found && i++ < row){
  j = -1;
  while(!found && j++ < column){
     found = (arr[i][j] == check1);
  }
}

if(found){
  System.out.println("Found " + check1 + " at index [" + i + "][" + j + "].");
}
else{
  System.out.println(check1 + " is not in this array.");
}

//for the second value

while(!found && i++ < row){
  j = -1;
  while(!found && j++ < column){
     found = (arr[i][j] == check2);
  }
}

if(found){
  System.out.println("Found " + check2 + " at index [" + i + "][" + j + "].");
}
else{
  System.out.println(check2 + " is not in this array.");
}

1 个答案:

答案 0 :(得分:0)

break只打破内循环。外面的人继续前进。

尝试:

int i = -1;
int j = -1;
while(!found && ++i < row) {
    j = -1;
    while(!found && ++j < column) {
        found = (arr[i][j] == check);
    }
}