Java 用户输入字符串到字符串数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30113062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
User input string into string array
提问by MKatana
I'm trying to get the user's input, then store the input into an array. I'm going to get a string input and with this code, I thought it would work, but it's not working. Any help would be appreciated!
我试图获取用户的输入,然后将输入存储到一个数组中。我将获得一个字符串输入,使用此代码,我认为它会起作用,但它不起作用。任何帮助,将不胜感激!
import java.util.Scanner;
public class NameSorting {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter 20 names to sort");
Scanner s1 = new Scanner(System.in);
for (int i = 0; i < 0;){
array[i] = s1.nextLine();
}
//Just to test
System.out.println(array[0]);
}
}
采纳答案by Shar1er80
Since you know that you want to have an array of 20 string:
因为您知道您想要一个包含 20 个字符串的数组:
String[] array = new String[20];
Then your for loop should use the length of the array to determine when the loop should stop. Also you loop is missing an incrementer.
然后你的 for 循环应该使用数组的长度来确定循环应该何时停止。你的循环也缺少一个增量器。
Try the following code to get you going:
试试下面的代码让你开始:
public static void main(String[] args) throws Exception {
Scanner s = new Scanner(System.in);
String[] array = new String[20];
System.out.println("Please enter 20 names to sort");
for (int i = 0; i < array.length; i++) {
array[i] = s.nextLine();
}
//Just to test
System.out.println(array[0]);
}
回答by Carlos A. Ortiz
Look at your for-loop, it lacks of increment attribute. Example: for(int i = 0; i < 0; i++)
If you want to debug each loop I recommend you to print assignment inside for-loop
看看你的 for 循环,它缺少 increment 属性。示例:for(int i = 0; i < 0; i++)
如果您想调试每个循环,我建议您在 for 循环内打印分配
for (int i = 0; i < 0;)
{
array[i] = s.nextLine();
System.out.println(array[i]); // Debug
}
回答by Santosh
for (int i = 0; i < 0;){
array[i] = s.nextLine();
}
For the first iteration i will be initialised to '0' and since i should be less then '0' as per your condition it wont even go into the loop.change the loop to
对于第一次迭代,我将被初始化为“0”,并且由于根据您的条件我应该小于“0”,因此它甚至不会进入循环。将循环更改为
for(int i=0;i<20;i++){
array[i]=s.nextLine();
}