[英]How do I create a 2d array with strings?
我想格式化一个名为 events 的二维数组,当 while 循环完成时,它看起来像这样:
incidents {{1500, xxxxxx, jan, 2010},{2000, xxxxxx, feb, 2000},{1000, xxxxxx, sep, 2016}}
我可以使用类似incidents[0,3]
的方式访问数组:给出第一个数组的第三个值,即 jan。
import java.util.Scanner;
public class Incident {
public static String main(String[] args) {
String[] incident; // Want to make this array a 2d array
Scanner myObj = new Scanner(System.in);
int choice = 1;
while(choice!=0) {
System.out.println("Enter value, postcode, month and year:");
String value = myObj.nextLine();
String postcode = myObj.nextLine();
String month = myObj.nextLine();
String year = myObj.nextLine();
incident = new String[]{value, postcode, month, year};
System.out.println("Enter 0 if you would like to exit entering incidents. Any other key if not.");
choice = myObj.nextInt();
}
return null;
}
}
考虑使用ArrayList :
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Incident {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<String[]> incidentsList = new ArrayList<>();
int i = 0;
while (true) {
System.out.printf("Enter incident %d details:%n", ++i);
System.out.print("Enter value: ");
String value = scanner.nextLine();
System.out.print("Enter postcode: ");
String postcode = scanner.nextLine();
System.out.print("Enter month: ");
String month = scanner.nextLine();
System.out.print("Enter year: ");
String year = scanner.nextLine();
String[] incident = new String[]{value, postcode, month, year};
incidentsList.add(incident);
System.out.println("Enter 0 if you would like to exit entering incidents. " +
"Any other key if not.");
String choice = scanner.nextLine();
if (choice.equals("0")) {
break;
}
}
System.out.printf("%nYou entered the following incidents:%n");
for (String[] incident : incidentsList) {
System.out.println(Arrays.toString(incident));
}
System.out.printf("%nincidentsList.get(0)[3] = %s%n", incidentsList.get(0)[3]);
}
}
示例用法:
Enter incident 1 details:
Enter value: 1500
Enter postcode: xxxxx
Enter month: jan
Enter year: 2010
Enter 0 if you would like to exit entering incidents. Any other key if not.
Enter incident 2 details:
Enter value: 2000
Enter postcode: xxxxx
Enter month: feb
Enter year: 2000
Enter 0 if you would like to exit entering incidents. Any other key if not.
a
Enter incident 3 details:
Enter value: 1000
Enter postcode: xxxxx
Enter month: sep
Enter year: 2016
Enter 0 if you would like to exit entering incidents. Any other key if not.
0
You entered the following incidents:
[1500, xxxxx, jan, 2010]
[2000, xxxxx, feb, 2000]
[1000, xxxxx, sep, 2016]
incidentsList.get(0)[3] = jan
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.