简体   繁体   中英

How to set number range from user input into a 2d array

just wanting to know how do i set an input range for the scanner object, which then transfers the values and inputs them into a 2d array.

I was able to set a range for random number generator but i do not know how to apply the same concept to my scanner object

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    Random random = new Random();
    int rows = 3; 
    int columns = 5;


    System.out.println("Enter array elements : ");

    int arry1[][] = new int[rows][columns];


    for (int i = 0; i < rows; i++) 
    {
        for (int j = 0; j < columns-2; j++) 
        {
            arry1[i][j] = sc.nextInt();
        }
    }

    arry1[0][3] = random.nextInt(50-10+1)+10;
    arry1[1][3] = random.nextInt(50-10+1)+10;
    arry1[2][3] = random.nextInt(50-10+1)+10;

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    sum1 = arry1[0][0]+arry1[0][1]+arry1[0][2]+arry1[0][3];
    sum2 = arry1[1][0]+arry1[1][1]+arry1[1][2]+arry1[1][3];
    sum3 = arry1[2][0]+arry1[2][1]+arry1[2][2]+arry1[2][3];

    arry1[0][4] = sum1;
    arry1[1][4] = sum2;
    arry1[2][4] = sum3;

    System.out.print("DISPLAYING ARRAY:"); 
    System.out.println();
    for (int[] x1 : arry1) {
        for (int y1 : x1) {
            System.out.print(y1 + "        ");
        }
        System.out.println();
    }
}

}

Add checking if the value is within range.

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    Random random = new Random();
    int rows = 3;
    int columns = 5;

    System.out.println("Enter array elements : ");

    int arry1[][] = new int[rows][columns];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns - 2; j++) {
            int input;

            do {
                input = sc.nextInt();
            } while (input < 0 || input > 3);

            arry1[i][j] = input;
        }
    }

    arry1[0][3] = random.nextInt(50 - 10 + 1) + 10;
    arry1[1][3] = random.nextInt(50 - 10 + 1) + 10;
    arry1[2][3] = random.nextInt(50 - 10 + 1) + 10;

    int sum1 = 0;
    int sum2 = 0;
    int sum3 = 0;

    sum1 = arry1[0][0] + arry1[0][1] + arry1[0][2] + arry1[0][3];
    sum2 = arry1[1][0] + arry1[1][1] + arry1[1][2] + arry1[1][3];
    sum3 = arry1[2][0] + arry1[2][1] + arry1[2][2] + arry1[2][3];

    arry1[0][4] = sum1;
    arry1[1][4] = sum2;
    arry1[2][4] = sum3;

    System.out.print("DISPLAYING ARRAY:");
    System.out.println();
    for (int[] x1 : arry1) {
        for (int y1 : x1) {
            System.out.print(y1 + "        ");
        }
        System.out.println();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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