我使用扫描仪将字符串输入到数组中。当我使用next();它工作正常,但在某些情况下我需要它来阅读整行。当我使用nextLine();它会跳过第一个元素。
System.out.print("How many extras?: ");
int extras = keybo.nextInt();
String[] extraArray = new String[extras];
for (int i = 1; i<=extras; i++)
{
System.out.println("Enter extra " + i + ": ");
extraArray[i-1] = keybo.nextLine();
}
sandwich1.setExtras(extraArray);
此代码输出:
How many extras?: 3
Enter extra 1: Enter extra 2: bacon
Enter extra 3: lettuce
Extras: , bacon, lettuce
我实际上只是破坏了我的代码,但是当我使用它时:
System.out.print("How many extras?: ");
int extras = keybo.nextInt();
String[] extraArray = new String[extras];
for (int i = 1; i<=extras; i++)
{
System.out.println("Enter extra " + i + ": ");
extraArray[i-1] = keybo.next();
}
我明白了:
How many extras?: 3
Enter extra 1:
bacon
Enter extra 2:
extra cheese
Enter extra 3:
Extras: bacon, extra, cheese
我有什么遗失的东西吗?为什么在没有输入的情况下循环一次?