繁体   English   中英

我如何从使用此2D数组的用户那里获得列号和行号?

[英]How would I get the column number and line number from a user using this 2D array?

我试图找到一种方法,除了与行号相对应的元素外,还根据用户输入来输出相应的列。 因此,例如,用户将“ 0”作为行号,因此输出应为00 01 02 03 ,如果列号为“ 2”,则输出应为:

02
12
22

这是以下2D数组的代码:

import java.util.Scanner;


public class TwoDimArray {
  public static void main(String[] args) {
    // the dimensions of the array
    int height = 3, width = 4;

    Scanner input = new Scanner(System.in);

    System.out.println("Input a column number: ");
    int columnNum = input.nextInt();
    System.out.print("Input a line number: ");
    int lineNum = input.nextInt();

    // the array
    String[][] array = new String[height][width];

    // an auxiliary variable to print the array
    String line;
    int sum = 0;

    // fill the 2-dim array
    for (int i = 0; i < height; i++) {
      for (int j = 0; j < width; j++) {
        array[i][j] = " "+ i + j;
      }
    }

    // print the 2-dim array
    for (int i = 0; i < height; i++) {
      line = "";
      sum += 1;

      for (int j = 0; j < width; j++) {
        line += array[i][j];
      }

      if (columnNum < 0 || columnNum > array[0].length)
        System.out.println("Column number outside range");
      else
        System.out.println(array[i][columnNum]);

      if (sum == lineNum) {
        System.out.println(line);
      }
      else if (lineNum <= 0 || lineNum > array.length) {
        System.out.println("Line number outside range");
        break;
      }
    }
  }
}

这是数组:

00 01 02 03
10 11 12 13
20 21 22 23

起初我完全误解了你的问题。

因此,您将必须提示用户输入行号/列号。 您需要决定如何确定哪个。 对于行/列,也许它们的输入形式应为“ r 3”或“ c 1”。

现在您已经拥有了,就像:

switch (isRow?) { // switch on a bool but you could do this however you want
case true: // row
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
      if (i == (userVal-1)) { // if this is the row they want, print it
        System.out.print(i);
        System.out.print(j + " ");
      }
    }
  }
break;
case false: // col
  for (int i = 0; i < height; i++) {
    for (int j = 0; j < width; j++) {
      if (j == (userVal-1)) { // if this is the col they want, print it
        System.out.print(i);
        System.out.print(j + "\n");
      }
    }
  }
break;

暂无
暂无

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

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