提示用户输入索引 - 二维数组 - 输出索引给出的数组元素 - java
Prompt the user for an index - 2D array - output the array element given by the index - java
我是 Java 的新手,完全不知道自己在做什么。如何提示用户输入格式为 'ab' 的二维数组的索引(a 的值为行号,b 的值为列号)并输出索引给出的数组元素?例如,如果用户输入“00”它
应该输出'3'。
任何帮助,将不胜感激。请记住,我不允许使用数组列表。
import java.util.Scanner;
public class Exercise23 {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int row = 3;
int col = 4;
int[][] array = new int[row][col];
System.out.println("Enter the index: ");
int index=scanner.nextInt();
String sIndex= String.format("%2d", index);
String quit = "quit";
if(sIndex!=quit){
array[0][0] =3;
array[0][1] =0;
array[0][2] =0;
array[0][3] =4;
array[1][0] =2;
array[1][1] =8;
array[1][2] =0;
array[1][3] =0;
array[2][0] =1;
array[2][1] =1;
array[2][2] =0;
array[2][3] =1;
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) {
System.out.print(array[i][j]);
}
System.out.println("");
}
}
}
}
有多种方法可以做到这一点。我会这样做:
if (sIndex.length() == 2) {
int selectedRow = Character.getNumericValue(sIndex.charAt(0));
int selectedColumn = Character.getNumericValue(sIndex.charAt(1));
// do your stuff
}
您可能想要添加一个发出错误消息的 else 部分。
如果用户很讨厌,输入-1,那么长度就是2,不知道上面的代码会做什么,肯定没什么意义。
我是 Java 的新手,完全不知道自己在做什么。如何提示用户输入格式为 'ab' 的二维数组的索引(a 的值为行号,b 的值为列号)并输出索引给出的数组元素?例如,如果用户输入“00”它 应该输出'3'。 任何帮助,将不胜感激。请记住,我不允许使用数组列表。
import java.util.Scanner;
public class Exercise23 {
public static void main(String[]args) {
Scanner scanner = new Scanner(System.in);
int row = 3;
int col = 4;
int[][] array = new int[row][col];
System.out.println("Enter the index: ");
int index=scanner.nextInt();
String sIndex= String.format("%2d", index);
String quit = "quit";
if(sIndex!=quit){
array[0][0] =3;
array[0][1] =0;
array[0][2] =0;
array[0][3] =4;
array[1][0] =2;
array[1][1] =8;
array[1][2] =0;
array[1][3] =0;
array[2][0] =1;
array[2][1] =1;
array[2][2] =0;
array[2][3] =1;
for(int i=0; i<row; i++) {
for(int j=0; j<col; j++) {
System.out.print(array[i][j]);
}
System.out.println("");
}
}
}
}
有多种方法可以做到这一点。我会这样做:
if (sIndex.length() == 2) {
int selectedRow = Character.getNumericValue(sIndex.charAt(0));
int selectedColumn = Character.getNumericValue(sIndex.charAt(1));
// do your stuff
}
您可能想要添加一个发出错误消息的 else 部分。
如果用户很讨厌,输入-1,那么长度就是2,不知道上面的代码会做什么,肯定没什么意义。