[英]How do I add user input to an Array in java?
public static void main(String[] args) {
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
for (i= 1; i <= n; i++) {
String g = a + i;
System.out.println(g);
}
}
This is my program. 这是我的程序。 It gets user input for the Class and prints the Roll Number for the students. 它获取班级的用户输入,并为学生打印卷号。
For example: If the class is 10A and the number of students is 10 , it prints a series like 10A1 , 10A2, 10A3 ... 10A10 例如:如果班级为10A ,学生人数为10 ,则它将打印10A1,10A2、10A3 ... 10A10之类的系列
How do I get the program to store these as elements in an array? 如何获得将这些元素存储为数组中的元素的程序?
For example: 例如:
array[0] = 10A1;
array[1] = 10A2;
array[2] = 10A3;
etc. 等等
Your code should look like this: 您的代码应如下所示:
public static void main (String args[])
{
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String []strings = new String[n]; // Creating an are of string with the given number
for(i= 0; i < n ;){
strings[i] = a + ++i; // Storing strings on to the array !
System.out.println(strings[i-1]);
}
}
You can just edit each index in your current for loop: 您可以只编辑当前for循环中的每个索引:
String[] arr;
for(i=0; i < n ; i++){
int j = i+1;
String g = a + j;
System.out.println(g);
arr[i] = g;
}
So all your printed g
's will be part of the array arr
. 因此,所有已打印的g
都将属于数组arr
。
First, declare a String
array of the appropriate size. 首先,声明一个适当大小的String
数组。
Second, in your for
loop, assign the strings you are currently printing, to positions in the array. 其次,在for
循环中,将当前正在打印的字符串分配给数组中的位置。
String[] things = new String[n];
for (i=1; i <= n; i++) {
String g = a + i;
System.out.println(g);
things[i-1] = g;
}
The strings are now in an array. 字符串现在位于数组中。
Following code is modified, for storing values in array. 修改了以下代码,用于将值存储在数组中。
public static void main(String[] args) {
// TODO code application logic here
Scanner user_input = new Scanner(System.in);
int i;
int n;
String a;
System.out.println("Enter the Class:");
a = user_input.next();
System.out.println("Enter the number of Students:");
n = user_input.nextInt();
String[] arr = new String[n]; // create string array of size n.
for(i= 1; i <= n ; i++){
String g = a + i;
System.out.println(g);
arr[i-1]=g; // assign your g veriable vale to array index
}
for(String s : arr){
System.out.println(s); // print your array
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.