我想从用户那里获得2个输入,然后将它们添加到下面的2个数组中。我尝试了这个代码,但这不是正确的工作。我该怎么办
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Input {
public static void main(String args[]) {
String[] runnersNames = {"Shiran", "Hasini", "Chanchala", "Priyankara", "Mayuri", "Sameera", "Supun"
, "Supuni", "Kavindu", "Nadeeka"};
int[] minutes = {342, 448, 398, 399, 350, 321, 299, 378, 384, 440};
System.out.println("Do you want to add more players? 1.Yes 2.No ");
int n;
Scanner sc = new Scanner(System.in);
System.out.print("your choice : ");
n = sc.nextInt();
if (n == 1) {
for (int i = 0; i < 10; i++) {
System.out.println("Enter the player name : ");
runnersNames[i] = sc.nextLine();
for (int j = 0; j < i; j++) {
System.out.println("Enter the player runtime : ");
minutes[j] = sc.nextInt();
}
}
}
}
}
您正在循环中用新添加的值替换原始名称。尽量不要从0开始循环。编辑:-您可能还需要使用2D阵列/列表几分钟。
如果您想将播放器添加到这两个变量中,您有两个选项:
创建一个具有更多空间的数组,
或使用不同的数据结构,如List
。第一个选项(创建一个有更多空间的阵列(:
import java.util.Scanner;
public class Input {
public static void main(String args[]) {
String[] runnersNames = {"Shiran", "Hasini", "Chanchala", "Priyankara", "Mayuri", "Sameera", "Supun"
, "Supuni", "Kavindu", "Nadeeka","","","","","","","","","",""};
int[] minutes = {342, 448, 398, 399, 350, 321, 299, 378, 384, 440,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1};
System.out.println("Do you want to add more players? 1.Yes 2.No ");
int n;
Scanner sc = new Scanner(System.in);
System.out.print("your choice : ");
n = sc.nextInt();
if (n == 1) {
for (int i = 0; i < 10; i++) {
System.out.println("Enter the player name : ");
runnersNames[i+10] = sc.nextLine();
for (int j = 0; j < i; j++) {
System.out.println("Enter the player runtime : ");
minutes[j+10] = sc.nextInt();
}
}
}
}
}
第二种选择是更干净一点,我认为:
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Input {
public static void main(String args[]) {
List<String> runnersNames = new ArrayList<>(Arrays.asList(new String[]{"Shiran", "Hasini", "Chanchala", "Priyankara", "Mayuri",
"Sameera", "Supun", "Supuni", "Kavindu", "Nadeeka")});
List<Integer> minutes = new ArrayList<>(Arrays.asList(new Integer[]{342, 448, 398, 399, 350, 321, 299, 378, 384, 440}));
System.out.println("Do you want to add more players? 1.Yes 2.No ");
int n;
Scanner sc = new Scanner(System.in);
System.out.print("your choice : ");
n = sc.nextInt();
if (n == 1) {
for (int i = 0; i < 10; i++) {
System.out.println("Enter the player name : ");
runnersNames.add(sc.nextLine());
for (int j = 0; j < i; j++) {
System.out.println("Enter the player runtime : ");
minutes.add(sc.nextInt());
}
}
}
}
}
然后可以使用get(int index)
方法获取列表中的一个元素。
minutes.get(0);