如何使用 Java 在 Array 中获取用户输入?即我们不是在我们的程序中自己初始化它,而是用户将给它的值.. 请指导!!
原文由 sadia 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何使用 Java 在 Array 中获取用户输入?即我们不是在我们的程序中自己初始化它,而是用户将给它的值.. 请指导!!
原文由 sadia 发布,翻译遵循 CC BY-SA 4.0 许可协议
package userinput;
import java.util.Scanner;
public class USERINPUT {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//allow user input;
System.out.println("How many numbers do you want to enter?");
int num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter the " + num + " numbers now.");
for (int i = 0 ; i < array.length; i++ ) {
array[i] = input.nextInt();
}
//you notice that now the elements have been stored in the array .. array[]
System.out.println("These are the numbers you have entered.");
printArray(array);
input.close();
}
//this method prints the elements in an array......
//if this case is true, then that's enough to prove to you that the user input has //been stored in an array!!!!!!!
public static void printArray(int arr[]){
int n = arr.length;
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
}
原文由 Busker Ott 发布,翻译遵循 CC BY-SA 3.0 许可协议
8 回答6.4k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答3.2k 阅读
2 回答3.9k 阅读
1 回答2.2k 阅读✓ 已解决
3 回答1.6k 阅读✓ 已解决
Here’s a simple code that reads strings from
stdin
, adds them intoList<String>
, and then usestoArray
to convert it toString[]
(if你 真的 需要使用数组)。也可以看看: