Java 输入变量依赖于另一个变量

Java 输入变量依赖于另一个变量,java,Java,我刚开始用Java编程,我遇到了一个小问题 我想让用户输入一个数字,我只需要用扫描仪就可以了 int s = sc.nextInt(); 但是,如果我想在之后创建一个输入变量,它将要求用户输入变量s拥有的尽可能多的数字,该怎么办呢 例如:s=3 用户需要再输入3个变量 s1=? s2=? s3=? 您需要一个数组或更具动态性的数据结构。在您的情况下,如果询问要输入多少值,可以执行以下操作: printf("How many values?%n"); int count = sc.nextIn

我刚开始用Java编程,我遇到了一个小问题

我想让用户输入一个数字,我只需要用扫描仪就可以了

int s = sc.nextInt();
但是,如果我想在之后创建一个输入变量,它将要求用户输入变量s拥有的尽可能多的数字,该怎么办呢

例如:s=3 用户需要再输入3个变量

s1=?
s2=?
s3=?

您需要一个数组或更具动态性的数据结构。在您的情况下,如果询问要输入多少值,可以执行以下操作:

printf("How many values?%n");
int count = sc.nextInt();
int s[] = new int[count];
for (int n = 0; n < s.length; n++) {
    printf("enter s" + n + "%n");
    s[n] = sc.nextInt()
}
但是使用数组来实现这一点是非常过时的。更具动态性的解决方案如下所示:

List<Integer> s = new ArrayList<Integer>();
while (true) {
    printf("Enter Number or -1 to finish.%n");
    int num = sc.nextInt();
    if (num < 0) break;
    s.add(Integer.valueOf(num));
 }

那适合你吗?您可以选择相应地使用其中一个注释:D

您只需要3个数字吗?在这种情况下,您应该执行int s[]=new int[3];forint i=0;不只是三个数字…数字s定义的所有数字…如果用户选择5作为s的值…他应该键入5个数字
 s = sc.nextInt();  // Gets your input
 // If you don't want to use ArrayList use following:

 int ss[] = new int[s];   // This uses arrays

 // If you want Lists, use the following:
 List<int> mylist = new ArrayList<int>(); // If you want a list of your integers (flexible)
 for (int i = 0; i<s; i++){
     int st = sc.nextInt();
     mylist.add(new Integer(st));  // if you are interested only in Lists
     //ss[i] = sc.nextInt();    // if you are interested only in arrays
 }