2 回答
TA贡献1799条经验 获得超9个赞
读取一个字符串应该用 while 循环来完成,但你想做的是在这里完成的。此解决方案仅将字符串保存到第一个索引。
public static void main(String [] args) {
String [] thisIsAStringArray = new String[20]; //Only 20 string can be saved.
Scanner in = new Scanner(System.in);
for(int i = 0; i < 100;i++) {
thisIsAStringArray[0] = in.nextLine(); ///Save element to first position.
System.out.println("String entered is " + thisIsAStringArray[0]); //Get the element from the first position.
}
}
此解决方案不会保存到第一个位置,而是保存到数组的每个索引。
public static void main(String [] args) {
String [] thisIsAStringArray = new String[20]; //Only 20 string can be saved.
Scanner in = new Scanner(System.in);
for(int i = 0; i < thisIsAStringArray.length;i++) {
thisIsAStringArray[i] = in.nextLine(); ///Save element to first position.
System.out.println("String entered is " + thisIsAStringArray[i]); //Get the element from the first position.
}
}
TA贡献1946条经验 获得超3个赞
因此,您创建了一个 String 列表并将 String 分配到 String 数组的头部。并且您使用辅助函数获得数组头部的索引。
String[] thisIsAStringArray = new String[10];
for (int i=1;1<100;i++) {
System.out.print("Enter a string : ");
Scanner scanner = new Scanner(System. in);
String inputString = scanner.nextLine(); // READ IN THE STRING
System.out.println("String read from console is : \n"+inputString);
int pos= firstNonullPosition(thisIsAStringArray);
if(pos!=-1)
thisIsAStringArray[]=inputString;
else
System.out.println("Array is full!");
System.out.println("The String at the position 0 of the String array thiIsAStringArray is:" +thisIsAStringArray[0]);
}
public static int firstNonullPosition(String[] a)
{
int index=0;
while(a[index]!= null)
{
index++;
if (index > a.length)
return -1;
}
return index;
}
添加回答
举报