[英]How to store a integer into a string multi-dimensional array in java
我需要存储25个不同的数组,其中第一个位置是人的名字,其余的索引作为做数学运算的整数。 我有一个String arrray [25] [53]。 如何使array [0-25] [1-52]为整数? 我假设使用.parseInt,但是考虑到我仍在学习Java,我不太确定它们如何工作。
String[][] volunteerNamesAndHours = new String [25][53];
int ID = 0;
int week;
do{
volunteerNamesAndHours[ID][NAME] = input.next();
for(week = 1; week < 53; week++){
volunteerNamesAndHours[ID][week] = Integer.parseInt(null, ID);
编辑:我会使用OOP或地图,但考虑到我们还没有走得那么远,我不想超越自己的界限,让我的教授发疯。 我知道这不是最直观的方法,但是我最终想到的这个问题是什么?
public static String[][] getvolunteerChart(Scanner input){
String[][] volunteerNamesAndHours = new String [25][53];
int ID = 0;
int week;
do{
volunteerNamesAndHours[ID][NAME] = input.next();
for(week = 1; week < 53; week++){
volunteerNamesAndHours[ID][week] = Integer.toString(input.nextInt());
}
ID++;
}
while(ID <= 24);
return volunteerNamesAndHours;
}
我建议使用哈希图将名称存储为键,将整数数组列表存储为值,例如
Map<String, ArrayList<Integer>> volunteerNamesAndHoursMap = new HashMap<String, ArrayList<Integer>>();
您需要针对此用例使用Map结构。
Map<String, Integer[]> personIDs = new HashMap<>(25);
personIDs.put("Peter", new Integer[]{5,22,7734});
personIDs.get("Peter");//returns the array 5,22,7734
您应该遵循一种面向对象的方法,并将您的志愿者数据封装在这样的类中:
public class Volunteer {
private int id;
private String name;
private int hours;
.
.
.
public in getId() {
return id;
}
public void setid(int id) {
this.id = id;
}
.
.
.
}
现在,您可以将它们存储在List
或数组中。 除了数组之外, List
通常没有预定义的大小限制。
List<Volunteer> volunteers = new ArrayList<>();
// Or as an array
Volunteer[] volunteers = new Volunteer[25];
然后,您可以遍历列表,并使用如下的getter和setter进行数学运算:
for (Volunteer volunteer : volunteers) {
int oldHours = volunteer.getHours();
int newHours = oldHours + 8;
volunteer.setHours(newHours);
}
首先,我认为您需要一个String数组,然后是一个长度为52的int多维数组。Java是一种非常静态的语言,它不会让您做疯狂的事情,例如将Integer存储在字符串数组。
String[] volunteerNames = new String [25];
int[] volunteerHours = new int [25][52];
第二,我认为您确实可以在这里使用一些不错的Object定向,为Volunteer创建一个类,并在其中存储一个带有名称和int数组的字符串。
(关于此的PS:稍后尝试搜索getter和setter。通常的做法是声明具有私有作用域的类变量并定义访问它们的方法,但是我在这里将它们与公共作用域一起使用只是为了使示例简短
public class Volunteer {
public String name;
public int[] hours;
Volunteer(String name, int[] hours) {
this.name = name;
this.hours = hours;
}
}
第三,如果您真的想像做的那样做,我想您应该使用地图。
Map<String, Integer[]> volunteersHours = new HashMap<String, Integer[]>();
volunteersHours.put("John", new Integer[] {1, 2, 3, 4, etc...});
volunteersHours.get("John"); // will return the hours array
如果您坚持使用String数组,则需要使用Integer
类的toString
函数。
例如
Integer.toString(42);
但是,这将在以后尝试对它们执行数学运算时引起痛苦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.