如何在两个维数组中显示值?

时间:2013-04-16 04:57:50

标签: java

我想将坐标x和y插入到两个维数组中并将其打印出来。对于给定代码的示例,当它要求输入时,它不会执行一次但是两次接受该值。如果值实际存储在每个数组中,或者只存储一个,我不会这样做。是否可以独立于矩阵显示输出?我赎回任何帮助或更正!祝福你。 这是代码:

代码

import java.util.Scanner;

public class MummyMadness {

    public static void main(String []args){


    int [][] desert = new int [1][1];
    int x =0;
    int y =0;
    int mummies[] = new int [1];
    int Mlimit = 100000;


    coordinates(desert,mummies,x,y);
    }
    public static int[] inputmummy(int mummies[], int Mlimit){
        int i;
        Scanner input = new Scanner(System.in);
        System.out.println("How many mummies you want?");
        System.out.println("Note that the limit of mummies is 100k");
        i = input.nextInt();

        if(mummies[i] > Mlimit)
        {
            System.out.println("You exceeded from the mummies!");
        }


        return mummies;
    }



    public static int[][] coordinates(int desert[][],int mummies[], int x, int y){


        //Idea use length of mummies for coordinates but if you take out desert i doesnt work


         System.out.println("Enter mummy coordinates");

           for(int i = 0; i < desert.length; i++){

         System.out.println("Enter x:"); 
         Scanner input = new Scanner(System.in);

              if(input.nextInt() > desert.length)
              {
                  System.out.println("Error x exceeded desert length");
                  break;
              }
               desert[i][0] = input.nextInt();

            System.out.println("Mummy location x: " + desert[i][0]);

            for(int j = 0; j < mummies.length; j++){

         System.out.println("Enter y:");     
         Scanner input2 = new Scanner(System.in);

                if(input.nextInt() > desert[0].length)
              {
                  System.out.println("Error y exceeded desert length");
                  break;
              }

                 desert[0][j] = input2.nextInt();

                System.out.println("Mummy location y: " + desert[0][j]); 
                System.out.println(desert[i][j])


            }

        }

        return desert; 

        }

    }

1 个答案:

答案 0 :(得分:1)

您正在使用input.nextInt两次() - 一次用于检查,一次用于实际插入到数组中。每次调用此函数时,都需要输入。因此它要求输入两次。 这样做:

int tmp = input.nextInt();
if(tmp > desert.length)
{
    System.out.println("Error x exceeded desert length");
    break;
}
desert[i][0] = tmp;