2 回答

TA貢獻1799條經(jīng)驗 獲得超9個贊
讀取一個字符串應(yīng)該用 while 循環(huán)來完成,但你想做的是在這里完成的。此解決方案僅將字符串保存到第一個索引。
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.
}
}
此解決方案不會保存到第一個位置,而是保存到數(shù)組的每個索引。
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條經(jīng)驗 獲得超3個贊
因此,您創(chuàng)建了一個 String 列表并將 String 分配到 String 數(shù)組的頭部。并且您使用輔助函數(shù)獲得數(shù)組頭部的索引。
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;
}
添加回答
舉報