制作数组时遇到一些问题。我应该做的是创建一个包含5个文本字符串的数组,其中包含来自终端的名称。我该怎么做呢?我知道如何使用我自己的值创建一个数组,但这比我预期的更难解决。是的,我是编程的新手;)
答案 0 :(得分:1)
有很多方法可以做到这一点:
String[] elements = new String[5];
for(int i = 0; i <= 4; i++){
System.out.println("Please enter an element");
elements[i]= input.next();
}
正是你正在寻找的东西。
答案 1 :(得分:0)
我希望这个程序可以帮到你。
import java.util.Scanner;
public abstract class Main {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter number of elements");
int num_of_elements = Integer.parseInt(input.next());
String[] elements =new String[num_of_elements];
for(int i = 0; i < num_of_elements; i++){
System.out.println("Please enter an element");
elements[i]= input.next() + " ";
}
for(int i = 0; i < num_of_elements; i++){
System.out.println("[" + elements[i] + "]");
}
}
}
测试
Please enter number of elements
3
Please enter an element
H
Please enter an element
E
Please enter an element
Y
[H ]
[E ]
[Y ]
测试2
Please enter number of elements
4
Please enter an element
Hello
Please enter an element
How
Please enter an element
are
Please enter an element
you?
[Hello ]
[How ]
[are ]
[you? ]