我正在尝试扫描一个整数并运行一个循环来扫描字符串,直到该整数。但是这段代码会跳过第一个字符串......
import java.util.ArrayList;
import java.util.Scanner;
public class A1 {
public static void main(String[] args) {
ArrayList <String> A = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("How many strings to add:");
int a = sc.nextInt();
for(int i=0; i<a; i++)
{
System.out.printf("Enter %dth string:\n", i+1);
String s = sc.nextLine();
A.add(s);
}
for(int i=0; i<A.size(); i++)
{
System.out.println(A.get(i));
}
}
}
任何解决方案?
答案 0 :(得分:0)
只需将您的代码更改为以下内容:
import java.util.ArrayList;
import java.util.Scanner;
public class A1 {
public static void main(String[] args) {
ArrayList <String> A = new ArrayList<String>();
Scanner sc = new Scanner(System.in);
System.out.println("How many strings to add:");
int a = sc.nextInt();
for(int i=0; i<a; i++)
{
System.out.printf("Enter %dth string:\n", i+1);
String s = sc.next(); //This will wait until you give argument
A.add(s);
}
for(int i=0; i<A.size(); i++)
{
System.out.println(A.get(i));
}
}
}