繁体   English   中英

在二维数组中搜索值

[英]Searching for Values in Two-Dimensional 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.");
}

break只会打破内在循环。 外层的继续前进。

尝试:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM