我试图获取用户的输入,然后将输入存储到数组中。我将获得一个字符串输入,并且使用此代码,我认为它会起作用,但它不起作用。任何帮助将不胜感激!
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]);
}
}
答案 0 :(得分:2)
因为你知道你想拥有一个20字符串的数组:
String[] array = new String[20];
然后你的for循环应该使用数组的长度来确定循环何时应该停止。你循环也缺少增量器。
尝试以下代码让您前进:
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]);
}
答案 1 :(得分:0)
看看你的for循环,它没有增量属性。示例:for(int i = 0; i < 0; i++)
如果你想调试每个循环,我建议你在for循环中打印赋值
for (int i = 0; i < 0;)
{
array[i] = s.nextLine();
System.out.println(array[i]); // Debug
}
答案 2 :(得分:0)
for (int i = 0; i < 0;){
array[i] = s.nextLine();
}
对于第一次迭代,我将初始化为&#39; 0&#39;因为我应该少于&#39; 0&#39; 0根据你的情况,它甚至不会进入循环。将循环更改为
for(int i=0;i<20;i++){
array[i]=s.nextLine();
}