用输入设置每个数组值

时间:2015-10-19 13:03:17

标签: java

我想这样做:

input number[0][0]=201
input number[0][1]=202
input number[1][0]=203    
input number[1][1]=204    
input last = 203

然后查找上次输入是否与上面相同,如果为true,则s.o.p找到,否则找不到

我的代码:

import java.util.Scanner;
public class array_input {
    public static void main(String[] args) {
        int a[][];
        Scanner scan = new Scanner(System.in);
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 2; j++) {
                System.out.print("input number[" + i + "][" + j + "]");
                int b = scan.nextInt();
                a[i][j] = b;
            }
        }
        System.out.print("input what u want");
        if (a[i][j] == b) {
            System.out.print("found");
        } else {
            System.out.print("not found");
        }
    }
}

2 个答案:

答案 0 :(得分:0)

也许你的意思是这样的?

import java.util.Scanner;
public class array_input
{
    public static void main(String [] args){
         int a [][] = new int[2][2];
         Scanner scan = new Scanner(System.in);

         for(int i = 0;i < 2; i++){
              for(int j = 0; j < 2; j++){
                   System.out.printf("input number[%d][%d]=", i, j);
                   int b = scan.nextInt();
                   a[i][j]=b;
              }
         }
         System.out.print("input last = ");
         int needle = scan.nextInt();

         for (int[] row : a){
              for (int col : row){
                   if(col == needle){
                        System.out.println("found");
                        return;
                   }
              }
         }
         System.out.print("not found");
     }
}

答案 1 :(得分:0)

好的,我想这就是你想要的。这将检查数组的最后一个输入是否在数组中(不包括最后一个输入)。

boolean valueInArray = false;
for(int i=0;i<2;i++){
    for(int j=0;j<2;j++){
        if(a[i][j]==b && (i != 2 || j != 2)){
            valueInArray = true;
        }
    }
}
if(valueInArray){
    System.out.print("found");
} else {
    System.out.print("not found");
}