为什么我总是在这个字符串数组中输入一个字符串?
public class Source {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// Declare the variable
int a;
// Read the variable from STDIN
a = in.nextInt();
String strs[]=new String[a];
for(int i=0;i<a;i++)
strs[i]=in.nextInt();
}
}
答案 0 :(得分:0)
您可以在循环中更改条件,如下所示:
for (int i = 0; i < a - 1; i++) {
strs[i] = in.nextInt();
}
答案 1 :(得分:0)
您正在多次正确迭代,等于a
。不是a-1
。所以问题似乎无效:
public class Source {
public static void main(String[] args) {
try(Scanner in = new Scanner(System.in)) {
// Declare the variable
int a;
System.out.print("How many Strings would you like to enter? ");
// Read the variable from STDIN
a = in.nextInt();
String[] strs = new String[a]; // this will fail for certain values of `a`
for(int i=0; i<a; i++) {
System.out.format("Enter String number %d: ", i+1);
strs[i]= in.next();
}
System.out.println("Result: " + Arrays.toString(strs));
}
}
}
运行:
您想要输入多少个字符串? 2
输入字符串编号1:Apple
输入字符串编号2:笔
结果:[Apple,Pen]